@tickernelz/paperclip-pro-ui 2026.1009.2 → 2026.1009.3
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.
- package/dist/assets/{Agents.production-DSa6Vl3y.js → Agents.production-BDrotnkr.js} +2 -2
- package/dist/assets/{CompanyActivity.production-CXZY_w67.js → CompanyActivity.production-DVFoP5Wf.js} +1 -1
- package/dist/assets/{CompanyExport-BlNlzmA0.js → CompanyExport-CbGWtqna.js} +1 -1
- package/dist/assets/{CompanySkills.production-Wzc95Tf4.js → CompanySkills.production-DTqClYmE.js} +1 -1
- package/dist/assets/{Costs.production-Dgazqe6X.js → Costs.production-ClgsqTtT.js} +1 -1
- package/dist/assets/{OrgChart.production-BEhpdEr9.js → OrgChart.production-D8k1dx4P.js} +1 -1
- package/dist/assets/{RoutineDetail.production-CpuZ5sxp.js → RoutineDetail.production-BLcjq7J0.js} +1 -1
- package/dist/assets/{Routines.production-Dt1_0n4r.js → Routines.production-CrrER4oK.js} +1 -1
- package/dist/assets/{definition-Doyo4Zr4.js → definition-D733B7hW.js} +1 -1
- package/dist/assets/{index-DzwtTcH-.js → index-aJuthquM.js} +4 -4
- package/dist/index.html +1 -1
- package/dist/sw.js +1 -1
- package/package.json +1 -1
|
@@ -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-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/runtime-IAg0vdY9.js","assets/model-DL5biheO.js","assets/definition-D733B7hW.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-CbGWtqna.js","assets/agent-avatar-url-DtOIjE-b.js","assets/router-CoeH24PK.js","assets/preload-helper-CceJXRIF.js","assets/boxes-CeCVqNtb.js","assets/agents-DA5qW1fs.js","assets/EmptyState-B1JSbXSE.js","assets/button-yf2m1_gs.js","assets/mention-chips-OAQdMAP9.js","assets/StatusIcon-BCy8D6Fj.js","assets/clipboard-NgncerTn.js","assets/loader-circle-DSiPgghG.js","assets/octagon-alert-BbqyswZU.js","assets/MarkdownBody-CvvH69j_.js","assets/check-xeGJ2HPN.js","assets/external-link-CjUn0PMx.js","assets/rotate-ccw-Du0rX6yB.js","assets/PageSkeleton-BmmfQJ6g.js","assets/skeleton-BY2fv9gX.js","assets/Agents.production-BDrotnkr.js","assets/AgentAvatar-Jt6HpvU2.js","assets/tabs-BfWJYNcW.js","assets/dist-BAFQ8Oiq.js","assets/bot-S2JV9WBV.js","assets/heartbeats-DeXOtSp3.js","assets/triangle-alert-VjOLPhJL.js","assets/SidebarContext-BguZPmI9.js","assets/environments-BT_uDOM8.js","assets/Routines.production-CrrER4oK.js","assets/RoutineRunVariablesDialog-C-j5V71-.js","assets/MarkdownEditor-DCE_KC27.js","assets/dist-B6HyW9be.js","assets/dist-DCJXgQu0.js","assets/sheet-_VebRl9q.js","assets/checkbox-CIcktoHJ.js","assets/chevron-right-D0Hti4WB.js","assets/label-DSx2Qxn6.js","assets/select-DarpvIBM.js","assets/chevron-down-CZ7qFy9y.js","assets/useHiddenSettings-BpAre2Wp.js","assets/health-k3cyi4s3.js","assets/badge-DEcdN2HY.js","assets/input-DnT08BOo.js","assets/company-members-CDG03HZV.js","assets/AgentIdentity-2cID8kur.js","assets/card-Cl_LFk7c.js","assets/RoutineDetail.production-BLcjq7J0.js","assets/save-d5benU21.js","assets/CompanySkills.production-DTqClYmE.js","assets/use-adapter-capabilities-CI0JeLXc.js","assets/file-text-D87G0ZiA.js","assets/CompanyActivity.production-DVFoP5Wf.js","assets/Costs.production-ClgsqTtT.js","assets/OrgChart.production-D8k1dx4P.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var ZDe=Object.defineProperty;var r=(e,s)=>ZDe(e,"name",{value:s,configurable:!0});import{i as lM,n as eLe,t as Fy}from"./rolldown-runtime-ZpX3ckPj.js";import{$ as Fpe,$n as Bpe,$r as db,$t as tLe,A as Bi,An as sLe,Ar as y3,At as nLe,B as cr,Bn as rp,Br as $l,Bt as rLe,C as aLe,Cn as e7,Cr as gz,Ct as iLe,D as Id,Dn as zpe,Dr as oLe,Dt as lLe,E as qpe,En as bz,Er as t7,Et as CJ,F as cg,Fi as cLe,Fn as dLe,Fr as uLe,Ft as j3,G as mLe,Gn as Upe,Gr as hLe,Gt as pLe,Hn as w3,Hr as Te,Ht as Kpe,I as r_,Ii as Wpe,In as Vpe,Ir as LL,It as fLe,J as xLe,Jn as gLe,Jr as bLe,Jt as vLe,K as yLe,Kn as SI,Kt as jLe,L as y1,Li as s7,Ln as wLe,Lr as sk,Lt as kLe,M as gh,Mi as CI,Mn as NLe,Mr as SLe,Mt as HR,N as Va,Ni as CLe,Nn as _Le,Nr as k3,Nt as TN,O as Rr,On as ILe,Or as ALe,Ot as Hpe,P as N3,Pi as Pt,Pn as TLe,Pr as RLe,Pt as ELe,Q as Oa,Qn as _J,Qr as Uk,Qt as PLe,R as Rm,Rn as nk,Rr as IJ,Rt as MLe,S as W,Sn as DLe,Sr as S3,St as LLe,T as sa,Tn as $Le,Tr as OLe,Tt as n7,U as FLe,Un as RN,Ur as BLe,Ut as zLe,V as Gpe,Vn as Qpe,Vr as dn,Vt as qLe,W as ps,Wn as Ype,Wr as AJ,Wt as ULe,X as r7,Xn as xf,Xt as TJ,Y as Hf,Yn as Jpe,Yr as C3,Yt as KLe,Z as P,Zn as Xpe,Zr as WLe,Zt as VLe,_ as Cm,_n as Zpe,_r as HLe,_t as RJ,an as GLe,ar as $L,at as EJ,b as PJ,bn as MJ,br as efe,bt as tfe,c as QLe,cn as YLe,cr as JLe,ct as sfe,d as XLe,dn as ZLe,dr as cM,dt as e$e,ei as t$e,en as s$e,er as n$e,et as kf,fn as r$e,fr as nfe,ft as rfe,g as Xl,gi as a$e,gn as GR,gr as i$e,gt as dg,h as By,hi as o$e,hn as j1,hr as l$e,ht as afe,i as dM,in as ife,ir as c$e,it as DJ,j as d$e,jn as u$e,jr as LJ,jt as m$e,k as vz,kn as ub,kt as a7,l as _I,ln as ofe,lr as uM,lt as lfe,m as EN,mn as h$e,mr as p$e,mt as f$e,n as vv,ni as ee,nn as x$e,nr as $J,nt as Nf,o as g$e,on as cfe,or as b$e,ot as dfe,pi as v$e,pn as OJ,pr as y$e,pt as j$e,q as w$e,qn as i7,qr as Ub,qt as ufe,ri as k$e,rn as N$e,rr as S$e,s as qv,sn as C$e,sr as _$e,st as HS,t as Ft,ti as je,tn as I$e,tr as mfe,tt as II,un as hfe,ur as A$e,ut as T$e,v as R$e,vn as FJ,vr as AI,vt as E$e,w as pfe,wn as Kk,wr as ffe,wt as PN,x as o7,xn as P$e,xr as BJ,xt as zJ,y as qJ,yn as xfe,yr as gfe,yt as TI,z as l7,zn as M$e,zr as bfe,zt as D$e}from"./agent-avatar-url-DtOIjE-b.js";import{t as Jc}from"./preload-helper-CceJXRIF.js";import{$ as L$e,A as Sf,At as vfe,B as Ll,Bt as yfe,C as vp,Ct as $$e,D as O$e,Dt as F$e,E as B$e,Et as z$e,F as Ad,Ft as mb,G as Xx,H as jfe,Ht as va,I as mM,It as nt,K as a_,L as Ap,Lt as q$e,M as pd,Mt as ao,N as RI,Nt as U$e,O as Zx,Ot as K$e,P as zl,Pt as ld,Q as UJ,R as io,Rt as W$e,S as V$e,St as ug,T as EI,Tt as QR,U as _3,Ut as fi,V as PI,Vt as hM,W as wfe,X as I3,Y as H$e,Z as kfe,_ as G$e,_t as KJ,a as MN,at as Q$e,b as A3,bt as WJ,ct as Nfe,d as Y$e,dt as Cw,et as J$e,f as ly,ft as St,g as X$e,gt as hl,h as Z$e,ht as DN,i as eOe,it as Sfe,j as c7,jt as tOe,k as Th,kt as sOe,l as nOe,lt as rOe,m as Cfe,mt as T3,n as hb,nt as aOe,o as Mn,ot as I2,p as pM,pt as R3,q as iOe,r as kn,rt as oOe,st as VJ,t as Ke,tt as HJ,u as d7,ut as lOe,v as Em,vt as cOe,w as yp,wt as dOe,x as Pf,xt as Q0,y as uOe,yt as OL,z as mOe,zt as na}from"./router-CoeH24PK.js";import{$ as hOe,$n as xh,$t as pOe,A as fOe,An as GJ,Ar as LN,At as cy,B as Sg,Bn as _fe,Br as xOe,Bt as rk,C as u7,Cn as Ife,Cr as m7,Ct as $u,D as gOe,Dn as E3,Dr as bOe,Dt as vOe,E as yz,En as Afe,Er as MI,Et as Tfe,Fn as QJ,Fr as Ou,Ft as dy,G as zy,Gn as yOe,Gr as fM,Gt as jOe,H as Y0,Hn as P3,Hr as jp,Ht as Rfe,I as Efe,In as Pfe,Ir as Cg,It as i_,J as Mfe,Jn as Dfe,Jt as wOe,K as kOe,Kn as Lfe,Kr as Rh,Kt as NOe,L as SOe,Ln as h7,Lr as COe,Lt as _Oe,M as IOe,Mn as $fe,Mr as xl,Mt as DI,N as AOe,Nn as Ofe,Nr as ec,Nt as jz,O as TOe,On as M3,Or as Mf,Ot as Ffe,Pn as YJ,Pr as JJ,Pt as uy,Q as ROe,Qn as Bfe,Qt as EOe,R as POe,Rn as zfe,Rr as qfe,Rt as MOe,S as DOe,Sn as ak,Sr as Ufe,St as wz,T as Kfe,Tn as ik,Tr as Wfe,Tt as LOe,U as kz,Un as $Oe,Ur as xM,Ut as fc,V as Vfe,Vn as D3,Vr as Hfe,Vt as Dx,W as $N,Wn as OOe,Wr as L3,Wt as ON,X as FOe,Xn as Gfe,Xt as BOe,Y as zOe,Yn as XJ,Yt as ok,Z as qOe,Zn as Qfe,Zt as ZJ,_ as UOe,_n as Yfe,_r as Jfe,_t as KOe,a as WOe,an as yc,ar as Wk,at as Xfe,b as FL,bn as Zfe,br as FN,bt as exe,c as eX,cn as VOe,cr as $3,ct as tX,d as txe,dn as lk,dr as sxe,dt as p7,en as o_,er as nxe,et as HOe,f as l_,fn as GOe,fr as QOe,ft as rxe,g as YOe,gn as axe,gr as JOe,gt as LI,h as O3,hn as XOe,hr as gM,ht as wp,i as ZOe,in as eFe,ir as ixe,it as tFe,j as sFe,jn as nFe,jr as gl,jt as J0,k as f7,kn as sX,kr as BN,kt as rFe,l as BL,ln as aFe,lr as iFe,lt as oxe,m as lxe,mn as cxe,mr as zN,mt as oFe,n as lFe,nn as nX,nr as Nz,nt as dxe,o as cFe,on as uxe,or as x7,ot as Sz,p as mxe,pn as hxe,pr as dFe,pt as qy,q as uFe,qn as F3,qr as qN,qt as mFe,r as mg,rn as g7,rr as Uv,rt as hFe,s as pFe,sn as Vk,sr as pxe,st as fxe,t as b7,tn as fFe,tr as _m,tt as xFe,u as gFe,ur as bFe,ut as vFe,v as rX,vn as xxe,vr as UN,vt as yFe,w as B3,wn as c_,wr as v7,wt as jFe,x as wFe,xn as Vx,xr as kFe,xt as Cz,y as gxe,yn as z3,yr as $I,yt as bxe,z as NFe,zn as q3,zr as SFe,zt as CFe}from"./RoutineRunVariablesDialog-C-j5V71-.js";import{Z as Fn,a as _Fe,at as IFe,et as vxe,o as AFe,ot as TFe,s as RFe}from"./mention-chips-OAQdMAP9.js";import{g as EFe}from"./dist-B6HyW9be.js";import{i as PFe}from"./dist-BAFQ8Oiq.js";import{t as xc}from"./boxes-CeCVqNtb.js";import{D as MFe,E as DFe,S as LFe,a as y7,c as Yr,d as Qc,f as yxe,i as $Fe,l as vi,m as X0,o as OFe,p as _g,r as FFe,s as jxe,t as fd,u as qu,w as BFe,x as zFe}from"./MarkdownEditor-DCE_KC27.js";import{_ as j7,a as wxe,b as bM,c as kxe,d as Jd,f as Xd,g as Zd,h as eu,i as d_,l as tu,m as su,n as qFe,o as kp,p as nu,r as Mh,s as Pm,t as Dh,u as ru,v as _i,y as gc}from"./sheet-_VebRl9q.js";import{a as Mo,c as UFe,i as vM,l as xd,n as KFe,o as Do,r as Hl,s as Nxe,t as gr}from"./AgentAvatar-Jt6HpvU2.js";import{A as Ed,C as ni,D as w7,E as k7,O as Xr,S as bh,T as N7,_ as S7,a as Js,b as pb,c as hn,d as Uy,f as zn,g as Zr,h as qn,i as WFe,j as Ri,k as la,l as VFe,m as Pd,n as Cn,o as jn,p as Un,r as Ys,s as hr,t as pi,u as Xs,v as ea,w as HFe,x as O0,y as ls}from"./checkbox-CIcktoHJ.js";import{_ as GFe,c as ci,d as KN,f as Au,g as Lx,h as WN,i as QFe,l as OI,m as Ko,n as Ky,o as yM,p as VN,s as YFe,t as Qs,u as JFe,v as oo,y as jM}from"./label-DSx2Qxn6.js";import{i as za,n as ba,r as md,t as Ti}from"./tabs-BfWJYNcW.js";import{a as FC,c as ym,d as br,f as _z,g as Sr,h as XFe,i as oa,l as Sxe,m as ZFe,n as hg,o as Cxe,p as dr,r as Np,s as Jl,t as $t,u as Kv}from"./agents-DA5qW1fs.js";import{S as Pu,a as _xe,b as ho,d as Ixe,f as U3,g as pa,l as Axe,m as Yl,n as Txe,o as Rxe,p as Exe,t as Xi,u as eBe,v as Pxe,x as Ec,y as tBe}from"./StatusIcon-BCy8D6Fj.js";import{a as Tl,i as Df,n as uh,r as ha,t as Wy}from"./use-adapter-capabilities-CI0JeLXc.js";import{a as Vy,c as jm,i as FI,n as sBe,o as Mu,r as Bn,s as wM,t as On}from"./EmptyState-B1JSbXSE.js";import{t as no}from"./bot-S2JV9WBV.js";import{t as gs}from"./check-xeGJ2HPN.js";import{t as nn}from"./chevron-down-CZ7qFy9y.js";import{t as En}from"./chevron-right-D0Hti4WB.js";import{a as nBe,c as Ma,i as Nn,l as fb,n as Da,o as Mxe,r as rBe,s as La,t as $a}from"./select-DarpvIBM.js";import{n as Pc,r as Zi,t as Cf}from"./save-d5benU21.js";import{A as pg,C as Iz,D as aBe,_ as Dxe,c as iBe,h as oBe,i as lBe,j as ca,k as yn,l as j0,n as YR,o as cBe,p as Az,r as C7,t as L,u as dBe,y as uBe}from"./button-yf2m1_gs.js";import{i as Ir,n as Si,r as Go,t as fa}from"./clipboard-NgncerTn.js";import{t as Vn}from"./external-link-CjUn0PMx.js";import{C as mBe,S as hBe,_ as pBe,a as fBe,b as xBe,c as gBe,d as Lxe,f as bBe,g as aX,h as vBe,i as yBe,l as jBe,m as $xe,n as Oxe,o as Fxe,p as Bxe,r as wBe,s as kBe,t as Sn,u as NBe,v as _f,w as Lh,x as SBe,y as CBe}from"./MarkdownBody-CvvH69j_.js";import{t as Ha}from"./file-text-D87G0ZiA.js";import{a as kM,i as Yo,n as _Be,o as zxe,r as BI,t as Jr}from"./heartbeats-DeXOtSp3.js";import{t as rt}from"./loader-circle-DSiPgghG.js";import{n as zI,t as cu}from"./useHiddenSettings-BpAre2Wp.js";import{t as Hk}from"./octagon-alert-BbqyswZU.js";import{t as Ci}from"./rotate-ccw-Du0rX6yB.js";import{t as Es}from"./triangle-alert-VjOLPhJL.js";import{n as qa,t as IBe}from"./SidebarContext-BguZPmI9.js";import{n as ABe,t as ct}from"./badge-DEcdN2HY.js";import{n as Nr,t as Pi}from"./environments-BT_uDOM8.js";import{t as ht}from"./input-DnT08BOo.js";import{a as Lf,i as qI,n as UI,o as pr,r as Ig,t as HN}from"./company-members-CDG03HZV.js";import{t as du}from"./health-k3cyi4s3.js";import{t as vn}from"./skeleton-BY2fv9gX.js";import{t as Md}from"./AgentIdentity-2cID8kur.js";import{a as TBe,i as Fl,n as RBe,o as ro,r as Xa,s as ko,t as rn}from"./card-Cl_LFk7c.js";import{t as Ra}from"./PageSkeleton-BmmfQJ6g.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 EBe=class extends v$e{static{r(this,"InfiniteQueryObserver")}constructor(e,s){super(e,s)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type="infinite",super.setOptions(e)}getOptimisticResult(e){return e._type="infinite",super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,s){const{state:n}=e,a=super.createResult(e,s),{isFetching:i,isRefetching:o,isError:l,isRefetchError:c}=a,d=n.fetchMeta?.fetchMore?.direction,u=l&&d==="forward",h=i&&d==="forward",p=l&&d==="backward",f=i&&d==="backward";return{...a,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:o$e(s,n.data),hasPreviousPage:a$e(s,n.data),isFetchNextPageError:u,isFetchingNextPage:h,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!u&&!p,isRefetching:o&&!h&&!f}}};function xb(e,s){return k$e(e,EBe,s)}r(xb,"useInfiniteQuery");var PBe="adapter_auth_missing",MBe="document",DBe=80,LBe={markdown:"md",html:"html",json:"json",text:"txt"};function $Be(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,DBe).replace(/-+$/g,"")||MBe}r($Be,"documentExportSlug");function OBe(e){return LBe[(e??"").trim().toLowerCase()]??"md"}r(OBe,"documentExportExtension");function iX(e,s){const n=s.replace(/^\.+/,"").toLowerCase()||"md";return`${$Be(e)}.${n}`}r(iX,"documentExportFileName");function Tz(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(Tz,"decisionEffectTargetIssueIds");var FBe=new Set(["terminated","pending_approval","paused"]),BBe=new Set(["active","idle","running","error"]);function zBe(e){return BBe.has(e)&&!FBe.has(e)}r(zBe,"isAgentStatusInvokable");function GS(e){return e==="done"||e==="cancelled"}r(GS,"isPipelineTerminalStageKind");function qxe(e){const s={};for(const n of e)(s[n.stageId]??=[]).push(n);return s}r(qxe,"groupWarningsByStage");function Uxe(e){return e==="RESPONSIBLE_USER_UNAUTHORIZED"||e==="RESPONSIBLE_USER_UNAVAILABLE"}r(Uxe,"isResponsibleUserDenialCode");function KI(e){const s=e?.trim();return s&&s.length>0?s:"the responsible user"}r(KI,"responsibleUserLabel");function Rz(e,s={}){const n=KI(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(Rz,"describeResponsibleUserDenial");var qBe=["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 UBe(e){const s=e?.trim();return s&&s.length>0?s:"this task"}r(UBe,"issueLabel$2");function KBe(e){const s=e?.trim();return s&&s.length>0?s:"the current assignee"}r(KBe,"assigneeLabel");function WBe(e){const s=e?.trim();return s&&s.length>0?s:"this agent"}r(WBe,"actorLabel$1");var VBe="create a child issue with the request in its description (issue creation is a separate, open write path) and let its assignee act";function HBe(e,s={}){const n=UBe(s.issueIdentifier),a=WBe(s.actorLabel),i=KBe(s.assigneeLabel),o=KI(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 ${VBe}.`};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=Rz("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=Rz("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(HBe,"describeIssueWriteDenial");function Kxe(e){return(typeof e=="string"?e:e?.name??"").trim()}r(Kxe,"rawNameOf");function Wxe(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(Wxe,"looksLikeNetworkAddress");function Ez(e){return e.split(/[\s._-]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}r(Ez,"titleCaseIdentifier");function GBe(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,""),Ez(n)||"Custom app"}r(GBe,"pluginPackageLabel");function $f(e,s={}){const n=s.title?.trim();if(n)return n;const a=Kxe(e);if(!a||Wxe(a))return"Custom app";const i=GBe(a);if(i)return i;if(a.includes(":")&&!a.includes("://")){const o=a.slice(a.lastIndexOf(":")+1).trim();if(o)return Ez(o)}return/\s/.test(a)||/[A-Z]/.test(a)?a:/[._-]/.test(a)?Ez(a):a}r($f,"humanizeConnectionDisplayName");function oX(e){const s=Kxe(e);return s&&Wxe(s)?`hosted at ${s}`:null}r(oX,"connectionDisplaySecondaryHint");var lX=`I want to connect an MCP (Model Context Protocol) server to Paperclip, and I need a paste-ready config.
|
|
3
3
|
|
|
4
4
|
Target server: <name the server, or ask me if I have not said>
|
|
@@ -303,7 +303,7 @@ self.onmessage = function (e) {
|
|
|
303
303
|
}
|
|
304
304
|
|
|
305
305
|
};
|
|
306
|
-
`;function lrt(){const e=new Blob([ort],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(lrt,"createSandboxedWorker");var Yq=new Map,P5=new Map,xE=new Set,gE=new Map,xSe=null;function crt(e){xSe=e}r(crt,"setDynamicParserResultNotifier");function gSe(e,s){e.worker.postMessage(s)}r(gSe,"sendToWorker");function drt(e){return e.nextId++}r(drt,"nextRequestId");function urt(e,s){return`${s}\0${e}`}r(urt,"lineCacheKey");function mrt(){xSe?.()}r(mrt,"notifyResultReady");function hrt(e,s,n){return new Promise(a=>{const i=drt(e);e.pendingResolves.set(i,a),gSe(e,{type:"parse",id:i,line:s,ts:n})})}r(hrt,"parseLineAsync");function HC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(HC,"drainPendingRequests");function prt(e){return new Promise((s,n)=>{const a=lrt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{HC(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"&&HC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),HC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),HC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},gSe(i,{type:"init",source:e})})}r(prt,"initSandboxedWorker");function frt(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=urt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),hrt(e,i,o).then(d=>{n.delete(l),s.set(l,d),mrt()})),[])},"parseStdoutLine")}}r(frt,"buildParserModule");async function Jq(e){const s=P5.get(e);if(s)return s;if(xE.has(e))return null;const n=gE.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 xE.add(e),null;const o=await prt(await i.text());Yq.set(e,o);const l=frt(o);return P5.set(e,l),l}catch{return xE.add(e),null}finally{gE.delete(e)}})();return gE.set(e,a),a}r(Jq,"loadDynamicParser");function Xq(e){const s=P5.has(e);P5.delete(e),xE.delete(e),gE.delete(e);const n=Yq.get(e);return n&&(HC(n),n.worker.terminate(),Yq.delete(e)),s}r(Xq,"invalidateDynamicParser");var bE=[],c4=new Map,Zq=new Set,bSe=new Map,F$=new Set,W2=new Map,e6=new Set;function vSe(e){return e6.add(e),()=>e6.delete(e)}r(vSe,"onAdapterChange");function ySe(){for(const e of e6)e()}r(ySe,"notifyAdapterChange");crt(ySe);function xrt(){for(const e of[ttt,ptt,Ptt,Ftt,lst,jst,Pst,qst,Zst,cnt,Pnt,Cnt,Xtt,Qnt,E5,irt])Zq.add(e.type),bSe.set(e.type,e),wv(e)}r(xrt,"registerBuiltInUIAdapters");function wv(e){const s=bE.findIndex(n=>n.type===e.type);s>=0?bE.splice(s,1,e):bE.push(e),c4.set(e.type,e),ySe()}r(wv,"registerUIAdapter");function jSe(e){return c4.get(e)??null}r(jSe,"findUIAdapter");xrt();function iS(e){const s=c4.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Jq(e).then(o=>{o&&wv({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:yy,buildAdapterConfig:aN})})),E5.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:yy,buildAdapterConfig:aN}}return s}r(iS,"getUIAdapter");function grt(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 Zq){const i=bSe.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=F$.has(a);if(o&&l&&!c){F$.add(a);const d=(W2.get(a)??0)+1;W2.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;wv({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Jq(a).then(b=>{b&&W2.get(a)===d&&wv({type:a,label:p,parseStdoutLine:b.parseStdoutLine,createStdoutParser:b.createStdoutParser,ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})})),h(f,x)),"parseStdoutLine"),ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})}else(!o||!l)&&c&&(F$.delete(a),W2.delete(a),Xq(a),wv(i))}for(const{type:a,label:i}of e){if(Zq.has(a))continue;const o=c4.get(a);if(o&&o!==E5)continue;let l=!1;const c=o?.parseStdoutLine??E5.parseStdoutLine;wv({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Jq(a).then(h=>{h&&wv({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??yy,buildAdapterConfig:o?.buildAdapterConfig??aN})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??yy,buildAdapterConfig:o?.buildAdapterConfig??aN})}}r(grt,"syncExternalAdapters");function MW(){return[...bE]}r(MW,"listUIAdapters");function t6(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(t6,"resolveStdoutParser");function wSe(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(wSe,"appendTranscriptEntry");function brt(e,s){for(const n of s)wSe(e,n)}r(brt,"appendTranscriptEntries");function vrt(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(vrt,"truncateTranscriptLine");function yrt(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(yrt,"formatTranscriptParserError");function jrt(e,s,n,a){const i=yrt(n)||"unknown parser error",o=vrt(e);return{kind:"result",ts:s,text:bm(`Chat transcript error: ${i}. Falling back for line: ${o}`,a),inputTokens:0,outputTokens:0,cachedTokens:0,costUsd:0,subtype:"transcript_parse_error",isError:!0,errors:[]}}r(jrt,"createTranscriptParseErrorEntry");function DW(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{brt(s,i(n,a).map(c=>yZe(c,l)))}catch(c){o?.(),wSe(s,jrt(n,a,c,l))}}r(DW,"appendParsedTranscriptLine");function kSe(e){const{entries:s,chunks:n,from:a,parseLine:i,reset:o,redactionOptions:l}=e;let c=e.stdoutBuffer;for(let d=a;d<n.length;d+=1){const u=n[d];if(u.stream==="stderr"){s.push({kind:"stderr",ts:u.ts,text:bm(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:bm(u.chunk,l)});continue}const h=(c+u.chunk).split(/\r?\n/);c=h.pop()??"";for(const p of h){const f=p.trim();f&&DW({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(kSe,"foldTranscriptChunks");function NSe(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=t6(s),c=kSe({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&DW({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(NSe,"buildTranscript");var Lte=[];function wrt(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=t6(e),o=[],l="",c=Lte,d=[];const u=r(()=>{i=t6(e),o=[],l="",c=Lte},"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 NSe(f,e,s);const b=o.slice(),v=b.length-1;return v>=0&&(b[v]={...b[v]}),x&&DW({entries:b,line:x,ts:f.length>0?f[f.length-1].ts:new Date().toISOString(),parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),b},"publish");return{update(f){return f===c||(h(f)||u(),l=kSe({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(wrt,"createIncrementalTranscript");function krt({agents:e,value:s,onChange:n,disabled:a=!1,excludeAgentIds:i=[],disabledEmptyLabel:o="Reports to: N/A (CEO)",chooseLabel:l="Reports to..."}){const[c,d]=(0,m.useState)(!1),u=new Set(i),h=e.filter(b=>b.status!=="terminated"&&!u.has(b.id)),p=s?e.find(b=>b.id===s):null,f=p?.status==="terminated",x=!!(s&&!p);return(0,t.jsxs)(br,{open:c,onOpenChange:d,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:W("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",f&&"border-amber-600/45 bg-amber-500/5",a&&"opacity-60 cursor-not-allowed"),disabled:a,children:x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Qc,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-muted-foreground",children:"Unknown manager (stale ID)"})]}):p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(gr,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:W("min-w-0 truncate",f&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${f?" (terminated)":""}`})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Qc,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:a?o:l})]})})}),(0,t.jsxs)(dr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",s===null&&"bg-accent"),onClick:r(()=>{n(null),d(!1)},"onClick"),children:"No manager"}),f&&(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[(0,t.jsx)(gr,{agent:p,size:16,className:"shrink-0 h-3 w-3"}),(0,t.jsxs)("span",{className:"min-w-0 truncate",children:["Current: ",p.name," (terminated)"]})]}),x&&(0,t.jsx)("div",{className:"px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:"Saved manager is missing from this organization. Choose a new manager or clear."}),h.map(b=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",b.id===s&&"bg-accent"),onClick:r(()=>{n(b.id),d(!1)},"onClick"),children:[(0,t.jsx)(gr,{agent:b,size:16,className:"shrink-0 h-3 w-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:b.name}),(0,t.jsx)("span",{className:"text-muted-foreground ml-auto shrink-0",children:AW[b.role]??b.role})]},b.id))]})]})}r(krt,"ReportsToPicker");var Nrt="__secret_folder__:";function Srt(e){return!e||e==="active"?null:(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(Srt,"statusBadge");function SSe(e){return e.split("/").filter(s=>s.length>0)}r(SSe,"splitSecretPath$1");function vE(e){return e.join("/")}r(vE,"pathKey$1");function tC(e){return e.length>0?`/${e.join("/")}`:"/"}r(tC,"pathLabel");function Crt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(Crt,"pathStartsWith");function $te(e){return`${Nrt}${vE(e)}`}r($te,"folderValue");function _rt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=SSe(c.name);if(Crt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=vE(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=tC(u);i.set(h,{key:`folder-${h||"root"}`,value:$te(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-${vE(s)}`,value:$te(c),label:"Up one folder",title:tC(c),searchText:tC(c),kind:"back",folderPath:vE(c),pathHint:tC(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?tC(s):"Browse secrets",options:l}}r(_rt,"buildFolderGroup");function LW({secretId:e,secrets:s,recentlyUsedSecrets:n,disabled:a,onSelect:i,onCreateNew:o,triggerClassName:l,disablePortal:c}){const[d,u]=(0,m.useState)(""),h=(0,m.useMemo)(()=>s.find(j=>j.id===e)??null,[s,e]),p=!!e&&!h,f=(0,m.useMemo)(()=>d?d.split("/"):[],[d]),x=(0,m.useMemo)(()=>s.some(j=>SSe(j.name).length>1),[s]),b=(0,m.useMemo)(()=>{const j=[];p&&j.push({id:"current-missing",label:"Current",options:[{key:`missing-${e}`,value:e,label:`Missing secret (${e.slice(0,8)}…)`,title:`Missing secret (${e})`,missing:!0,disabled:!0}]});const N=(n??[]).filter(w=>w.status==="active"&&w.id!==e);return N.length>0&&j.push({id:"recently-used",label:"Recently used",options:N.map(w=>({key:`recent-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret"}))}),j.push({id:"all-secrets",label:N.length>0?"All secrets":void 0,options:s.map(w=>({key:`all-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret",disabled:w.status!=="active"&&w.id!==e}))}),j},[p,n,e,s]),v=(0,m.useCallback)((j,N)=>{if(!x||QFe(j))return N;const w=_rt(s,f,e),k=N.filter(S=>S.id==="current-missing"||S.id==="recently-used");return w.options.length>0?[...k,w]:k},[f,x,e,s]);return(0,t.jsx)(Ky,{value:e||"",groups:b,onValueChange:r((j,N)=>{if(N.folderPath!==void 0)return u(N.folderPath),!1;u(""),i(j)},"onValueChange"),deriveGroups:v,disabled:a,disablePortal:c,placeholder:"Select secret…",searchPlaceholder:"Search secrets…",emptyMessage:"No matching secrets",triggerClassName:W("h-(--sz-34px) min-h-(--sz-34px) font-mono text-sm",p&&"border-destructive text-destructive",h&&h.status!=="active"&&"border-amber-500/60",l),renderValue:r(j=>{if(!j)return(0,t.jsx)("span",{className:"text-muted-foreground",children:"Select secret…"});if(j.missing)return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5 text-destructive",children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0"}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:j.label})]});const N=j.status&&j.status!=="active";return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5",title:j.title,children:[(0,t.jsx)(Si,{className:W("size-3.5 shrink-0",N?"text-amber-600":"text-muted-foreground")}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:j.label}),N?(0,t.jsxs)("span",{className:"text-amber-600",children:["(",j.status,")"]}):null]})},"renderValue"),renderOption:r((j,{selected:N})=>{if(j.kind==="folder"||j.kind==="back"){const w=j.kind==="back"?uqe:Jl;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",title:j.title??j.label,children:[(0,t.jsx)(w,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("truncate text-sm",N&&"font-medium"),children:j.label}),j.pathHint?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:j.pathHint}):null]})]})}return(0,t.jsxs)("span",{className:W("flex min-w-0 flex-1 items-center gap-1.5",j.disabled&&"opacity-60"),title:j.title??j.label,children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("min-w-0 truncate font-mono text-sm",N&&"font-medium"),children:j.label}),j.pathHint&&j.pathHint!==j.label?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:j.pathHint}):null]}),Srt(j.status)]})},"renderOption"),createItem:o?{render:r(j=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(yn,{className:"size-3.5 shrink-0"}),j.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",j.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(j=>o(j),"onSelect")}:void 0})}r(LW,"SecretPicker");var Irt=/^[a-z][a-z0-9_]*$/,Ote="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 CSe({mode:e,initialName:s,initialValue:n,existingSecretNames:a,onCancel:i,onSubmit:o}){const[l,c]=(0,m.useState)(s),[d,u]=(0,m.useState)(n),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(!1),[b,v]=(0,m.useState)(null),[j,N]=(0,m.useState)(!1),w=l.trim(),k=w?Irt.test(w)?a?.some(T=>T.toLowerCase()===w)?"A secret with this name already exists":null:"Use lowercase letters, digits and _":j?"Name is required":null,S=d.length===0&&j?"Value is required":null,C=!f&&w.length>0&&d.length>0&&!k;async function I(){if(N(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(T){v(T instanceof Error?T.message:"Failed to create secret"),x(!1)}}}r(I,"handleSubmit");const R=e==="create"?"Create & bind":"Store & bind";return(0,t.jsxs)("div",{className:"w-72 space-y-3",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(XFe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(ZFe,{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(Ote,k&&"border-destructive focus-visible:ring-destructive/40"),value:l,autoFocus:!0,spellCheck:!1,placeholder:"secret_name","aria-label":"Secret name","aria-invalid":k?!0:void 0,onChange:r(T=>c(T.target.value),"onChange"),onBlur:r(()=>N(!0),"onBlur"),onKeyDown:r(T=>{T.key==="Enter"&&(T.preventDefault(),I())},"onKeyDown")}),k?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:k}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Value"}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("input",{className:W(Ote,"pr-8",S&&"border-destructive focus-visible:ring-destructive/40"),type:h?"text":"password",value:d,readOnly:e==="store",spellCheck:!1,placeholder:e==="create"?"value":void 0,"aria-label":"Secret value","aria-invalid":S?!0:void 0,onChange:e==="create"?T=>u(T.target.value):void 0}),(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground hover:text-foreground","aria-label":h?"Hide value":"Show value",onClick:r(()=>p(T=>!T),"onClick"),children:h?(0,t.jsx)(Mm,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Ed,{className:"h-3.5 w-3.5"})})]}),S?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:S}):null]}),b?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-destructive",children:b}):null,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 pt-0.5",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",onClick:i,disabled:f,children:"Cancel"}),(0,t.jsxs)(L,{type:"button",size:"sm",onClick:r(()=>{I()},"onClick"),disabled:!C,children:[f?(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(CSe,"SecretPopoverForm");function _Se(e){return(0,t.jsx)(CSe,{mode:"create",...e})}r(_Se,"CreateSecretPopover");function Art(e){return(0,t.jsx)(CSe,{mode:"store",...e})}r(Art,"ConvertToSecretPopover");var Trt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,Rrt=[/^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 Ert(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(Ert,"looksHighEntropy");function Prt(e,s){return s?Trt.test(e)||Rrt.some(n=>n.test(s))?!0:Ert(s):!1}r(Prt,"isSensitiveEnv");var Fte=0;function Mrt(){return Fte+=1,`env-row-${Fte}`}r(Mrt,"nextRowId");function Bx(e="text"){return{id:Mrt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Bx,"emptyRow");function Drt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(Drt,"isSecretRef");function Lrt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(Lrt,"isPlainObj");function $rt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r($rt,"isUserSecretRef");function B$(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Bx(),name:s,textValue:n};if(Drt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Bx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if($rt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Bx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return Lrt(n)?{...Bx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Bx(),name:s}})}r(B$,"rowsFromValue");function yE(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(yE,"valueFromRows");var Bte="CLAUDE_CODE_OAUTH_TOKEN";function Vw(){return yE([{...Bx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(Vw,"buildFixedClaudeOAuthBinding");var Ort=/^[A-Za-z_][A-Za-z0-9_]*$/;function Frt(e,s,n){const a=e.trim();if(!a)return null;if(!Ort.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(Frt,"validateName");function Brt(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(Brt,"computeDuplicateNames");function zrt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:M5(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(zrt,"planSourceSwitch");function ISe(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(ISe,"computeRowHealth");function ASe(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(ASe,"computeUserSecretRowHealth");function M5(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(M5,"secretNameFromKey");function M1(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(M1,"envKeyFromSecretName");var qrt="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",zte="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function Urt({row:e,isLast:s,secrets:n,userSecretDefinitions:a,recentlyUsedSecrets:i,disabled:o,nameIssue:l,showNameIssue:c,dirtyFields:d,onPatch:u,onRemove:h,onNameBlur:p,onNamePaste:f,onEnterInValueLast:x,onCreateSecret:b,onToast:v,focusRequest:j,onFocusConsumed:N}){const w=(0,m.useRef)(null),k=(0,m.useRef)(null),S=(0,m.useRef)(null),[C,I]=(0,m.useState)(null),[R,T]=(0,m.useState)(!1),[A,D]=(0,m.useState)(null),M=ISe(e,n)??ASe(e,a),B=e.source==="secret"?n.find(X=>X.id===e.secretId)??null:null,E=(a?.length??0)>0,z=e.source==="text"&&!e.sensitiveDismissed&&Prt(e.name,e.textValue);(0,m.useEffect)(()=>{j&&(j==="name"?w.current?.focus():e.source==="text"?k.current?.focus():e.source==="secret"?S.current?.querySelector("[role=combobox]")?.focus():S.current?.querySelector("select,input")?.focus(),N())},[j,N,e.source]),(0,m.useEffect)(()=>{if(!A)return;const X=window.setTimeout(()=>D(null),5e3);return()=>window.clearTimeout(X)},[A]);function $(X){if(X==="user_secret"){if(e.source==="user_secret")return;u({source:"user_secret",secretId:"",version:"latest"}),window.setTimeout(()=>S.current?.querySelector("select,input")?.focus(),0);return}const re=zrt(e,X);switch(re.kind){case"noop":return;case"open-store":{const{name:oe,value:G}=re;window.setTimeout(()=>I({mode:"store",name:oe,value:G}),0);return}case"to-secret":u({source:"secret",userSecretKey:"",required:!0}),window.setTimeout(()=>{S.current?.querySelector("[role=combobox]")?.focus()},0);return;case"to-text":re.undoFrom&&D(re.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>k.current?.focus(),0);return}}r($,"switchSource");async function q(X,re){const oe=await b(X,re);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),I(null)}r(q,"submitSecretPopover");function U(){const X=M5(e.name)||"secret",{textValue:re}=e;window.setTimeout(()=>I({mode:"store",name:X,value:re}),0)}r(U,"openStoreAsSecret");const O=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",K=`${e.id}-name-error`,H=`${e.id}-health`,Z=d.name||d.value,se=B?Math.max(0,B.latestVersion):0,ne=e.version==="latest"?"latest":`v${e.version}`,fe=e.version!=="latest";return(0,t.jsxs)("div",{className:W("group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1","@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",Z&&"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(qrt,d.name&&"border-amber-500/70 bg-amber-500/10 focus-visible:ring-amber-500/40",c&&l?.level==="error"&&"border-destructive focus-visible:ring-destructive/40",c&&l?.level==="warn"&&"border-amber-500 focus-visible:ring-amber-500/40"),placeholder:"KEY",value:e.name,spellCheck:!1,disabled:o,"aria-label":"Variable name","aria-invalid":c&&l?.level==="error"?!0:void 0,"aria-describedby":c&&l?K:void 0,onChange:r(X=>u({name:X.target.value}),"onChange"),onBlur:p,onPaste:r(X=>{e.name||f(X.clipboardData.getData("text"))&&X.preventDefault()},"onPaste"),onKeyDown:r(X=>{X.key==="Enter"&&(X.preventDefault(),e.source==="text"?k.current?.focus():S.current?.querySelector("[role=combobox],select,input")?.focus())},"onKeyDown")})}),(0,t.jsxs)("div",{className:"col-span-2 col-start-1 row-start-2 min-w-0 @[40rem]/env:col-span-1 @[40rem]/env:col-start-2 @[40rem]/env:row-start-1",children:[(0,t.jsxs)(br,{open:C!==null,onOpenChange:r(X=>{X||I(null)},"onOpenChange"),children:[(0,t.jsx)(_z,{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)(Zr,{children:[(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)(Xr,{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)(Vqe,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Si,{className:"size-3.5"}):(0,t.jsx)(Ph,{className:"size-3.5"}),(0,t.jsx)(nn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(Un,{side:"top",children:O})]}),(0,t.jsxs)(ea,{align:"start",className:"w-56",children:[(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("text"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"Text value"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Store the value inline as plain text."})]}),(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"Organization secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve a stored organization secret at run start."})]}),(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("user_secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"User secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve the responsible user's own value at run start."})]})]})]}),e.source==="text"?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("input",{ref:k,className:zte,placeholder:"value",value:e.textValue,type:z?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(X=>u({textValue:X.target.value}),"onChange"),onKeyDown:r(X=>{X.key==="Enter"&&s&&(X.preventDefault(),x())},"onKeyDown")}),z?(0,t.jsxs)("div",{className:"flex shrink-0 items-stretch border-l border-border",children:[(0,t.jsxs)("button",{type:"button",onClick:U,disabled:o,className:"flex items-center gap-1 px-2 text-(length:--text-micro) text-amber-700 hover:bg-amber-500/10 dark:text-amber-400",title:"This value looks sensitive — store it as a secret",children:[(0,t.jsx)(bc,{className:"size-3.5"}),(0,t.jsx)("span",{className:"hidden @[30rem]/env:inline",children:"Store as secret"})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>u({sensitiveDismissed:!0}),"onClick"),disabled:o,"aria-label":"Dismiss sensitive-value suggestion",title:"Dismiss — keep this value as plain text",className:"flex items-center px-1.5 text-amber-700/60 hover:bg-amber-500/10 hover:text-amber-700 dark:text-amber-400/60 dark:hover:text-amber-400",children:(0,t.jsx)(Fn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(LW,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(X=>u({secretId:X,version:"latest"}),"onSelect"),onCreateNew:r(X=>I({mode:"create",name:M5(X)||X.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",B&&B.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),B&&B.status==="active"?(0,t.jsxs)(br,{open:R,onOpenChange:T,children:[(0,t.jsx)(_z,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(X=>{X.preventDefault(),X.stopPropagation(),T(re=>!re)},"onClick"),"aria-label":"Version",className:W("absolute right-8 top-1/2 z-10 -translate-y-1/2 rounded px-1.5 py-0.5 text-(length:--text-nano) font-medium",fe?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:ne})}),(0,t.jsxs)(dr,{align:"end",className:"w-44 p-1",role:"radiogroup","aria-label":"Secret version",children:[(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version==="latest",onClick:r(()=>{u({version:"latest"}),T(!1)},"onClick"),className:W("flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",e.version==="latest"&&"font-medium"),children:["latest ",(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"(recommended)"})]}),Array.from({length:se},(X,re)=>se-re).filter(X=>X>0).map(X=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===X,onClick:r(()=>{u({version:X}),T(!1)},"onClick"),className:W("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===X&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",X]},X))]})]}):null]}):(0,t.jsxs)("div",{className:"grid min-w-0 flex-1 grid-cols-(--gtc-13)",children:[E?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(X=>{const re=X.target.value,oe=a?.find(G=>G.key===re);u({userSecretKey:re,...oe&&!e.name.trim()?{name:oe.key.toUpperCase()}:{}})},"onChange"),className:"min-w-0 bg-transparent px-2 py-1.5 text-sm font-mono outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"",children:"Select user secret..."}),e.userSecretKey&&!a?.some(X=>X.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(X=>(0,t.jsxs)("option",{value:X.key,children:[X.name,X.status!=="active"?` (${X.status})`:""]},X.id))]}):(0,t.jsx)("input",{className:zte,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(X=>u({userSecretKey:X.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(X=>u({required:X.target.value==="required"}),"onChange"),className:"border-l border-border bg-transparent px-2 py-1.5 text-xs font-medium text-muted-foreground outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"required",children:"Required"}),(0,t.jsx)("option",{value:"optional",children:"Optional"})]})]})]})}),(0,t.jsx)(dr,{align:"start",className:"w-auto p-3",onInteractOutside:r(X=>{const re=X.detail.originalEvent.target;re&&S.current?.contains(re)&&X.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(Art,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):C?.mode==="create"?(0,t.jsx)(_Se,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):null})]}),M?(0,t.jsx)("p",{id:H,role:"status",className:W("mt-0.5 text-(length:--text-micro)",M.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:M.message}):null,A?(0,t.jsxs)("p",{className:"mt-0.5 inline-flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:["Reverted to text —"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2 hover:text-primary",onClick:r(()=>{u({source:"secret",secretId:A.secretId,version:A.version,textValue:""}),D(null)},"onClick"),children:"Undo"})]}):null]}),c&&l?(0,t.jsx)("p",{id:K,className:W("col-span-2 col-start-1 row-start-3 min-w-0 text-(length:--text-micro) @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",l.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:l.message}):null,(0,t.jsxs)("div",{className:"col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center",children:[e.source==="text"&&!z&&(e.name.trim()||e.textValue)?(0,t.jsxs)(Zr,{children:[(0,t.jsx)(Xr,{asChild:!0,disabled:o,children:(0,t.jsx)("button",{type:"button","aria-label":"More actions",className:"rounded p-1 text-muted-foreground opacity-100 hover:bg-accent hover:text-foreground @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100",children:(0,t.jsx)(Ri,{className:"size-4"})})}),(0,t.jsx)(ea,{align:"end",children:(0,t.jsx)(ls,{onSelect:r(()=>{window.setTimeout(U,0)},"onSelect"),children:"Store as secret…"})})]}):null,(0,t.jsx)("button",{type:"button",onClick:h,disabled:o,"aria-label":`Remove ${e.name.trim()||"variable"}`,className:"rounded p-1 text-muted-foreground opacity-100 hover:bg-destructive/10 hover:text-destructive @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100",children:(0,t.jsx)(Fn,{className:"size-4"})})]})]})}r(Urt,"EnvironmentVariableRow");var Krt=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function Wrt(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(Wrt,"stripInlineComment");function Vrt(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 Wrt(s).trim()}r(Vrt,"unquote");function Hrt(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=Krt.exec(a);if(!i)continue;const o=i[1],l=Vrt(i[2]);s.push({key:o,value:l})}return s}r(Hrt,"parseDotenv");var Grt=["PAPERCLIP_"],Qrt="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 s6(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(s6,"normalizedEnvEntries");function sC(e){return JSON.stringify(s6(e))}r(sC,"normalizedEnvKey");var z$=3;function q$(e){const s=e.slice(0,z$).join(", ");return e.length>z$?`${s} +${e.length-z$} more`:s}r(q$,"formatChangedNames");function qte(e){return e.map(s=>({...s}))}r(qte,"cloneRows");function Yrt(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(Yrt,"rowDirtyFields");var jy=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=Grt,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=Xc(),b=(0,m.useRef)(null),[v,j]=(0,m.useState)(()=>B$(s)),N=(0,m.useRef)(v),[w,k]=(0,m.useState)(()=>qte(v)),S=(0,m.useMemo)(()=>sC(s),[]),C=(0,m.useRef)(S),I=(0,m.useRef)(S),R=(0,m.useRef)(null),[T,A]=(0,m.useState)(S),[D,M]=(0,m.useState)(()=>new Set(B$(s).map(ie=>ie.name.trim()).filter(Boolean))),[B,E]=(0,m.useState)(null);(0,m.useEffect)(()=>{N.current=v},[v]);function z(ie,ue=N.current){C.current=ie,A(ie),k(qte(ue))}r(z,"markCommitted");function $(ie){M(ue=>{const ke=new Set(ue);for(const be of ie){const Ie=be.name.trim();Ie&&ke.add(Ie)}return ke})}r($,"touchCommittedNames");function q(ie){const ue=B$(ie);return j(ue),$(ue),ue}r(q,"adoptExternalValue"),(0,m.useEffect)(()=>{const ie=sC(s);if(ie===I.current)return;I.current=ie;const ue=sC(yE(N.current)),ke=ue!==C.current,be=R.current===ie;if(be&&(R.current=null),!ke){z(ie,q(s));return}(be||ue===ie)&&($(N.current),z(ie))},[s]);const U=(0,m.useMemo)(()=>yE(v),[v]),O=(0,m.useMemo)(()=>sC(U),[U]),K=O!==T;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const H=(0,m.useMemo)(()=>{const ie=new Map(s6(yE(w)).map(([Ie,Ue])=>[Ie,JSON.stringify(Ue)])),ue=new Map(s6(U).map(([Ie,Ue])=>[Ie,JSON.stringify(Ue)])),ke=[],be=[];for(const[Ie,Ue]of ue)ie.has(Ie)?ie.get(Ie)!==Ue&&be.push(Ie):ke.push(Ie);return{added:ke,changed:be,removed:[...ie.keys()].filter(Ie=>!ue.has(Ie))}},[w,U]),Z=(0,m.useMemo)(()=>{const ie=[];return H.added.length>0&&ie.push(`New: ${q$(H.added)}`),H.changed.length>0&&ie.push(`Edited: ${q$(H.changed)}`),H.removed.length>0&&ie.push(`Removed: ${q$(H.removed)}`),ie.join(" · ")},[H]);(0,m.useEffect)(()=>{if(c||!K)return;function ie(ue){ue.preventDefault(),ue.returnValue=""}return r(ie,"handleBeforeUnload"),window.addEventListener("beforeunload",ie),()=>window.removeEventListener("beforeunload",ie)},[c,K]);const se=(0,m.useCallback)(()=>c||!K?null:(R.current=O,(0,hp.flushSync)(()=>{n(U)}),U??{}),[c,U,O,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:se}),[se]),(0,m.useEffect)(()=>{const ie=b.current?.closest("form");if(!ie)return;function ue(){se()}return r(ue,"handleSubmit"),ie.addEventListener("submit",ue,!0),()=>ie.removeEventListener("submit",ue,!0)},[se]),(0,m.useEffect)(()=>{const ie=b.current;if(!ie)return;const ue=ie;function ke(be){const Ie=be.target;if(!(Ie instanceof Element)||ue.contains(Ie))return;const Ue=Ie.closest("button");if(!Ue||Ue.disabled)return;const at=`${Ue.getAttribute("aria-label")??""} ${Ue.textContent??""}`;(Ue.type==="submit"||/\b(save|create|update|test|import)\b/i.test(at))&&se()}return r(ke,"handleDocumentClick"),document.addEventListener("click",ke,!0),()=>document.removeEventListener("click",ke,!0)},[se]);function ne(ie){j(ie)}r(ne,"updateDraft");function fe(ie,ue){ne(v.map(ke=>ke.id===ie?{...ke,...ue}:ke))}r(fe,"patchRow");function X(ie){ne(v.filter(ue=>ue.id!==ie))}r(X,"removeRow");function re(){const ie=Bx();j([...v,ie]),E({rowId:ie.id,field:"name"})}r(re,"addRow");function oe(ie){const ue=v.find(ke=>ke.id===ie)?.name.trim();ue&&M(ke=>{if(ke.has(ue))return ke;const be=new Set(ke);return be.add(ue),be})}r(oe,"markTouched");function G(ie,ue){const ke=Hrt(ie);if(ke.length===0)return!1;const be=v.filter(Ie=>Ie.id!==ue).map(Ie=>({...Ie}));for(const{key:Ie,value:Ue}of ke){const at=be.find(dt=>dt.name.trim()===Ie);at?(at.name=Ie,at.source="text",at.textValue=Ue,at.secretId="",at.sensitiveDismissed=!1,at.userSecretKey="",at.required=!0):be.push({...Bx(),name:Ie,textValue:Ue})}return ne(be),x?.pushToast({title:`Imported ${ke.length} variable${ke.length===1?"":"s"}`,tone:"success"}),!0}r(G,"bulkImport");function Y(ie){const ue=v.map(Ie=>({...Ie})),ke=ue[ue.length-1];let be;ke&&!ke.name&&!ke.textValue&&!ke.secretId&&!ke.userSecretKey?be=ke:(be=Bx(),ue.push(be)),be.source="secret",be.secretId=ie.id,be.version="latest",be.name||(be.name=M1(ie.name)),ne(ue)}r(Y,"bindRecentSecret");function Q(){K&&(R.current=O,n(U))}r(Q,"saveDraft");function te(){R.current=null,I.current=sC(s);const ie=q(s);z(I.current,ie)}r(te,"revertDraft");const ae=(0,m.useMemo)(()=>Brt(v),[v]),le=(0,m.useMemo)(()=>v.reduce((ie,ue)=>ISe(ue,a)||ASe(ue,i)?ie+1:ie,0),[v,a,i]),he=(0,m.useMemo)(()=>{const ie=new Set(v.filter(ue=>ue.source==="secret"&&ue.secretId).map(ue=>ue.secretId));return(l??[]).filter(ue=>ue.status==="active"&&!ie.has(ue.id)).slice(0,8)},[l,v]),ce=v.length>0,ge=u===void 0?Qrt:u,me=(0,m.useMemo)(()=>new Map(w.map(ie=>[ie.id,ie])),[w]);return(0,t.jsx)(Pd,{children:(0,t.jsxs)("div",{ref:b,className:"@container/env space-y-2",children:[le>1?(0,t.jsxs)("p",{className:"inline-flex items-center gap-1.5 text-(length:--text-micro) font-medium text-amber-700 dark:text-amber-400",children:[(0,t.jsx)(Zi,{className:"size-3.5"}),le," bindings need attention"]}):null,ce?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-(--gtc-14)",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Value"}),(0,t.jsx)("span",{})]}),v.map((ie,ue)=>{const ke=Frt(ie.name,ae,d),be=D.has(ie.name.trim());return(0,t.jsx)(Urt,{row:ie,isLast:ue===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:ke,showNameIssue:be,dirtyFields:Yrt(ie,me.get(ie.id)),onPatch:r(Ie=>fe(ie.id,Ie),"onPatch"),onRemove:r(()=>X(ie.id),"onRemove"),onNameBlur:r(()=>oe(ie.id),"onNameBlur"),onNamePaste:r(Ie=>G(Ie,ie.id),"onNamePaste"),onEnterInValueLast:re,onCreateSecret:o,onToast:r(Ie=>x?.pushToast({title:Ie,tone:"success"}),"onToast"),focusRequest:B?.rowId===ie.id?B.field:null,onFocusConsumed:r(()=>E(null),"onFocusConsumed")},ie.id)})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No environment variables"}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[(0,t.jsxs)("button",{type:"button",onClick:re,disabled:c,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(yn,{className:"size-3.5"}),"Add variable"]}),he.length>0&&!c?(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5",children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Si,{className:"size-3"}),"Recently used:"]}),he.map(ie=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>Y(ie),"onClick"),className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",title:`Bind ${ie.name}`,children:["+ ",ie.name]},ie.id))]}):null]}),K&&!c&&!p?(0,t.jsxs)("div",{role:"status",className:"mt-3 flex w-full flex-col gap-3 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-3 text-amber-950 shadow-sm dark:bg-amber-500/15 dark:text-amber-100 @[34rem]/env:flex-row @[34rem]/env:items-center @[34rem]/env:justify-between",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)("span",{className:"size-2 rounded-full bg-amber-500 shadow-(--shadow-extract-13)"}),(0,t.jsx)("span",{children:"Unsaved changes"})]}),Z?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:Z,children:Z}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:te,className:"inline-flex h-9 items-center gap-1.5 rounded-md border border-amber-500/30 bg-background px-3 text-sm font-medium text-foreground transition-colors hover:bg-amber-500/10 dark:bg-background/80",children:[(0,t.jsx)(Ci,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Q,className:"inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90",children:[(0,t.jsx)(Cf,{className:"size-4"}),"Save"]})]})]}):null,ge?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ge}):null,v.some(ie=>ie.source==="user_secret"&&ie.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Ph,{className:"mt-0.5 size-3 shrink-0"}),(0,t.jsx)("span",{children:"User secrets resolve from the user responsible for the run. Required bindings fail until that user sets their value under Secrets → My secrets."})]}):null]})})},"EnvironmentVariablesEditor")),Jrt="env.",hA="access.",n6=/^[A-Za-z_][A-Za-z0-9_]*$/;function TSe(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(TSe,"deliveryModeForConfigPath");function RSe(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(RSe,"deliveryModeLabel");function Xrt(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(Xrt,"deliveryModeDescription");function ESe(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(ESe,"aliasFromConfigPath");function Zrt(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(Zrt,"consumerTypeLabel");var eat={numeric:!0,sensitivity:"base"};function GC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(GC,"getSecretPathRowName");function cN(e){return e.split("/").filter(s=>s.length>0)}r(cN,"splitSecretPath");function U$(e){return cN(e).join("/")}r(U$,"normalizeSecretPath");function Ute(e,s){return s.every((n,a)=>e[a]===n)}r(Ute,"startsWithSegments");function Kte(e,s){return e.localeCompare(s,void 0,eat)}r(Kte,"compareNames");function tat(e,s){const n=cN(s),a=e.map(c=>({row:c,name:GC(c),segments:cN(GC(c))})),i=new Set,o=[];for(const c of a){if(!Ute(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(!Ute(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)=>Kte(c.name,d.name)),o.sort((c,d)=>Kte(GC(c),GC(d))),{folders:l,secrets:o}}r(tat,"buildSecretPathListing");function sat(e){const s=cN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(sat,"buildSecretPathBreadcrumbs");function nat(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(nat,"validateSecretFolderSegment");function O_({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(O_,"SecretPathName");function rat(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(rat,"fingerprintLabel");function PSe({fingerprint:e,length:s,className:n}){const{pushToast:a}=da(),i=rat(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(Oz,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{fa(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:W("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(Oz,{className:"size-3 shrink-0"}),i,(0,t.jsx)(Ir,{className:"size-3 shrink-0 opacity-60"})]})}r(PSe,"FingerprintChip");function $W({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($W,"ProposalJustification");function F_({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)(gr,{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(F_,"AgentRefChip");function OW({configPath:e}){const s=TSe(e),n=s==="env",a=s==="api";return(0,t.jsxs)(ct,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal",n&&"border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",a&&"border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",!n&&!a&&"border-border bg-muted/40 text-muted-foreground"),children:[n?(0,t.jsx)(Qve,{className:"size-3"}):a?(0,t.jsx)(TM,{className:"size-3"}):null,RSe(s)]})}r(OW,"DeliveryBadge$1");function FW({className:e}){return(0,t.jsxs)(ct,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-medium","border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",e),children:[(0,t.jsx)(bc,{className:"size-3"})," Proposed"]})}r(FW,"ProposedBadge");function d4(e){return ESe(e.configPath)}r(d4,"bindingEnvKey");function BW(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(BW,"bindingSecretLabel");function Wte(e){return e instanceof dn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Wte,"readableError");function MSe(e,s=[]){const n=Pt(),{pushToast:a}=da(),[i,o]=(0,m.useState)(null),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(null),f=(0,m.useCallback)(()=>{e&&(n.invalidateQueries({queryKey:["secret-proposals",e]}),n.invalidateQueries({queryKey:P.secrets.list(e)}))},[e,n]),x=je({mutationFn:r(w=>{const{proposal:k}=w;if(k.kind==="secret"){const S=w.folder.trim()?`${w.folder.trim().replace(/\/+$/,"")}/${w.leaf.trim()}`:w.leaf.trim();return yr.approveProposal(e,k.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return yr.approveProposal(e,k.id,{cascade:w.cascade||void 0})},"mutationFn"),onSuccess:r(w=>{a({title:w.kind==="secret"?"Secret approved":"Binding approved",body:w.kind==="secret"?w.proposedName??"Secret created":`${w.target?.name??"Agent"} · ${d4(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Wte(w)),"onError")}),b=je({mutationFn:r(({proposal:w,reason:k})=>yr.rejectProposal(e,w.id,{reason:k.trim()}),"mutationFn"),onSuccess:r(w=>{a({title:"Proposal rejected",body:w.kind==="secret"?w.proposedName??void 0:void 0,tone:"info"}),c(null),u(""),p(null),f()},"onSuccess"),onError:r(w=>p(Wte(w)),"onError")}),v=(0,m.useCallback)(w=>{p(null);const k=(w.proposedName??"").split("/"),S=k.pop()??"";o({proposal:w,folder:k.join("/"),leaf:S,description:w.proposedDescription??"",providerConfigId:s.find(C=>C.provider==="local_encrypted"&&C.isDefault)?.id??"",cascade:!!w.secretProposalId})},[s]),j=(0,m.useCallback)(w=>{p(null),u(""),c(w)},[]),N=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(aat,{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)(oat,{proposal:l,reason:d,error:h,pending:b.isPending,onReasonChange:u,onCancel:r(()=>{c(null),u(""),p(null)},"onCancel"),onConfirm:r(()=>l&&b.mutate({proposal:l,reason:d}),"onConfirm")})]});return{requestApprove:v,requestReject:j,isBusy:x.isPending||b.isPending,dialogs:N}}r(MSe,"useProposalReview");function aat({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)(Ys,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Js,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(jn,{children:c?"The value is created as the proposing agent recorded it. Re-folder or rename it before it lands.":"Grant the target agent access to this secret. This runs with your permissions."})]}),(0,t.jsxs)("div",{className:"space-y-1.5 rounded-md border border-border bg-muted/30 p-2.5 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[(0,t.jsx)("span",{children:"Proposed by"}),(0,t.jsx)(F_,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)($W,{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)(Qs,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(ht,{id:"approve-folder",value:e.folder,onChange:r(p=>i({...e,folder:p.target.value}),"onChange"),placeholder:"dev/github",className:"font-mono text-xs"})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Qs,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(ht,{id:"approve-name",value:e.leaf,onChange:r(p=>i({...e,leaf:p.target.value}),"onChange"),placeholder:"client-secret",autoFocus:!0,"aria-invalid":!e.leaf.trim(),className:"font-mono text-xs"})]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:["Lands as"," ",d?(0,t.jsx)(O_,{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)(Qs,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(ht,{id:"approve-description",value:e.description,onChange:r(p=>i({...e,description:p.target.value}),"onChange"),placeholder:"Optional"})]}),u.length>0?(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Qs,{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)(PSe,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(iat,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"ghost",onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)(L,{onClick:l,disabled:n||!h,children:n?"Approving…":c?"Approve & create":e.cascade?"Approve secret & bind":"Approve binding"})]})]}):null})})}r(aat,"ApproveDialog");function iat({draft:e,onChange:s}){const{proposal:n}=e,a=BW(n),i=d4(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)(F_,{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)(OW,{configPath:n.configPath}),(0,t.jsx)("code",{className:"font-mono text-xs",children:i||n.configPath})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Secret"}),(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(Si,{className:"size-3.5 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:a.name}),a.pending?(0,t.jsx)(FW,{}):null]})]})]}),n.secretProposalId?(0,t.jsxs)("label",{className:"flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 p-2.5 text-xs",children:[(0,t.jsx)(pi,{checked:e.cascade,onCheckedChange:r(o=>s({...e,cascade:o===!0}),"onCheckedChange"),className:"mt-0.5","aria-label":"Also approve the proposed secret"}),(0,t.jsxs)("span",{className:"text-foreground/90",children:["Also approve the proposed secret"," ",(0,t.jsx)("span",{className:"font-medium",children:a.name})," and create it in the same step. The binding can’t land without it."]})]}):null]})}r(iat,"BindingApproveBody");function oat({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(Ys,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Js,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Reject proposal"}),(0,t.jsxs)(jn,{children:["The reason is sent back to"," ",(0,t.jsx)(F_,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Qs,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Cn,{id:"reject-reason",value:s,onChange:r(d=>i(d.target.value),"onChange"),rows:3,autoFocus:!0,placeholder:"Why is this being rejected?"})]}),n?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:n}):null,(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"ghost",onClick:o,disabled:a,children:"Cancel"}),(0,t.jsx)(L,{variant:"destructive",onClick:l,disabled:a||!c,children:a?"Rejecting…":"Reject"})]})]}):null})})}r(oat,"RejectDialog");function DSe({proposal:e,onApprove:s,onReject:n,disabled:a,size:i="sm"}){const o=!e.viewerCanApprove,l=i==="xs"?"h-7 px-2 text-xs":"",c=(0,t.jsx)(L,{size:"sm",className:l,disabled:a||o,onClick:r(()=>s(e),"onClick"),children:"Approve"});return(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[o?(0,t.jsx)(Pd,{children:(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)(Un,{className:"max-w-72",children:e.approveBlockReason??"You don’t have permission to approve this."})]})}):c,(0,t.jsx)(L,{size:"sm",variant:"outline",className:l,disabled:a,onClick:r(()=>n(e),"onClick"),children:"Reject"})]})}r(DSe,"ProposalActions");function LSe(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(LSe,"asRecord$16");function $Se(e){const s=LSe(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($Se,"readSecretRef");function lat(e){const s=LSe(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=$Se(i);o&&n.push({name:a,...o})}return n}r(lat,"parseEnvSecretRefs");function cat(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=$Se(a);i&&s.push({name:n.slice(hA.length),...i})}return s}r(cat,"parseAccessGrants");function dat(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(dat,"summarizeAgentBindings");var Vte=0;function OSe(){return Vte+=1,`access-row-${Vte}`}r(OSe,"nextAccessRowId");function K$(e){return e.map(s=>({id:OSe(),alias:s.name,secretId:s.secretId,version:s.version}))}r(K$,"entriesToRows");function Hte(e){const s={};for(const n of e){const a=n.alias.trim();!a||!n6.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(Hte,"rowsToAccessMap");function Gte(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(Gte,"normalizeAccessMapKey");function Qte({mode:e}){return e==="env"?(0,t.jsxs)(ct,{variant:"outline",className:"h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",children:[(0,t.jsx)(Qve,{className:"size-3"})," Env var"]}):(0,t.jsxs)(ct,{variant:"outline",className:"h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",children:[(0,t.jsx)(TM,{className:"size-3"})," API access"]})}r(Qte,"DeliveryBadge");function uat({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter(B=>B.kind==="binding"),[o]),u=(0,m.useMemo)(()=>lat(e),[e]),h=(0,m.useMemo)(()=>cat(e),[e]),p=(0,m.useMemo)(()=>dat(u,h),[u,h]),f=(0,m.useMemo)(()=>Hte(K$(h)),[h]),x=(0,m.useMemo)(()=>Gte(f),[f]),[b,v]=(0,m.useState)(()=>K$(h)),[j,N]=(0,m.useState)(null),w=(0,m.useRef)(new Map),k=(0,m.useRef)(x),S=(0,m.useRef)(x);(0,m.useEffect)(()=>{x!==S.current&&(S.current=x,x!==k.current&&v(K$(h)))},[x,h]);const C=r(B=>s.find(E=>E.id===B)?.name??`${B.slice(0,8)}…`,"secretName");function I(B){v(B);const E=Hte(B);k.current=Gte(E),n(E)}r(I,"emit");function R(B,E){I(b.map(z=>z.id===B?{...z,...E}:z))}r(R,"patchRow");function T(B){I(b.filter(E=>E.id!==B))}r(T,"removeRow");function A(){v(B=>[...B,{id:OSe(),alias:"",secretId:"",version:"latest"}])}r(A,"addRow");const D=(0,m.useMemo)(()=>{const B=new Map;for(const E of b){const z=E.alias.trim();z&&B.set(z,(B.get(z)??0)+1)}return B},[b]),M=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[M?(0,t.jsx)("div",{className:"space-y-1.5",children:p.map(B=>(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs",children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:C(B.secretId)}),B.envKeys.length>0?(0,t.jsx)(Qte,{mode:"env"}):null,B.apiAliases.length>0?(0,t.jsx)(Qte,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...B.envKeys.map(E=>`${Jrt}${E}`),...B.apiAliases.map(E=>`${hA}${E}`)].join(" · ")})]},B.secretId))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No secrets are bound to this agent yet."}),d.length>0&&l&&c?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Proposed access"}),d.map(B=>{const E=BW(B),z=d4(B);return(0,t.jsxs)("div",{className:"flex flex-col gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 text-xs sm:flex-row sm:items-center",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,t.jsx)(OW,{configPath:B.configPath}),(0,t.jsx)("code",{className:"font-mono",children:z||B.configPath}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"→"}),(0,t.jsx)(Si,{className:"size-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:E.name}),E.pending?(0,t.jsx)(FW,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",B.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",B.justification,"”"]})]})]}),(0,t.jsx)(DSe,{proposal:B,onApprove:l,onReject:c,disabled:i,size:"xs"})]},B.id)})]}):null,(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"API access (no env var)"}),b.length>0?(0,t.jsx)("div",{className:"space-y-2",children:b.map(B=>{const E=B.alias.trim(),z=!!E&&!n6.test(E),$=!!E&&(D.get(E)??0)>1,q=s.find(U=>U.id===B.secretId)??null;return(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-65) items-start gap-1.5",children:[(0,t.jsx)("div",{children:(0,t.jsx)(ht,{value:B.alias,onChange:r(U=>R(B.id,{alias:U.target.value}),"onChange"),onBlur:r(U=>{const O=U.target.value.trim();if(O&&!n6.test(O)){const K=M1(O);K&&K!==O&&R(B.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(z||$)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(br,{open:j?.rowId===B.id,onOpenChange:r(U=>{!U&&j?.rowId===B.id&&N(null)},"onOpenChange"),children:[(0,t.jsx)(_z,{asChild:!0,children:(0,t.jsx)("div",{ref:r(U=>{U?w.current.set(B.id,U):w.current.delete(B.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(LW,{secretId:B.secretId,secrets:s,onSelect:r(U=>R(B.id,{secretId:U,version:"latest",alias:!B.alias.trim()&&U?M1(C(U)):B.alias}),"onSelect"),onCreateNew:a?U=>{window.setTimeout(()=>{N({rowId:B.id,name:M5(U)||U.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(dr,{align:"start",className:"w-auto p-3",onInteractOutside:r(U=>{const O=U.detail.originalEvent.target;O&&w.current.get(B.id)?.contains(O)&&U.preventDefault()},"onInteractOutside"),children:j?.rowId===B.id&&a?(0,t.jsx)(_Se,{initialName:j.name,initialValue:"",existingSecretNames:s.map(U=>U.name),onCancel:r(()=>N(null),"onCancel"),onSubmit:r(async(U,O)=>{const K=await a(U,O);R(B.id,{secretId:K.id,version:"latest",alias:B.alias.trim()||M1(K.name)}),N(null)},"onSubmit")}):null})]}),(0,t.jsxs)("select",{className:"h-9 shrink-0 rounded-md border border-border bg-background px-2 text-xs outline-none disabled:cursor-not-allowed disabled:opacity-60",value:B.version===void 0?"latest":String(B.version),onChange:r(U=>{const O=U.target.value;R(B.id,{version:O==="latest"?"latest":Number.parseInt(O,10)})},"onChange"),disabled:i||!q,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),q?Array.from({length:Math.max(0,q.latestVersion)},(U,O)=>{const K=q.latestVersion-O;return K<=0?null:(0,t.jsxs)("option",{value:K,children:["v",K]},K)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>T(B.id),"onClick"),disabled:i,"aria-label":"Remove API access",className:"mt-1 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:(0,t.jsx)(la,{className:"size-3.5"})})]}),z?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):$?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},B.id)})}):null,(0,t.jsxs)("button",{type:"button",onClick:A,disabled:i,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(yn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[Xrt("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(uat,"AgentSecretAccessEditor");function mat(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(mat,"asNonEmptyString$3");function hat(e){return mat(e)!==null}r(hat,"hasLegacyWorkingDirectory");function pat(e){return e.isCreate?!1:hat(e.adapterConfig?.cwd)}r(pat,"shouldShowLegacyWorkingDirectoryField");var FSe=new Set;function fat(e){return FSe.has(e)}r(fat,"isAdapterTypeHidden");function xat(e){FSe=new Set(e)}r(xat,"setDisabledAdapterTypes");function gat(e){return!Ch(e).hideFromVisualSelection}r(gat,"isVisualAdapterChoice");function BSe(e,s=MW()){const n=e??Bf;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Ch(a.type).comingSoon,hidden:fat(a.type),experimental:!!Ch(a.type).experimental}))}r(BSe,"listAdapterOptions");function zSe(e={}){const s=e.enabled??!0,{data:n}=ee({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&grt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&xat(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(zSe,"useDisabledAdaptersSync");function bat(e={}){const s=e.enabled??!0,{data:n}=ee({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(bat,"useAdapterRegistryLoaded");function D5(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(D5,"omitUndefinedEntries");function V2(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=D5(s.adapterType!==void 0?{...Object.fromEntries(l$e.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=D5({...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(V2,"buildAgentUpdatePatch");var vat="kubernetes";function yat(e){return e.driver!=="sandbox"?!1:e.config?.provider===vat}r(yat,"isKubernetesSandboxEnvironment");function zW(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>yat(n))??null}}r(zW,"resolveForcedKubernetesEnvironment");var W$={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},nC={};function jat(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(jat,"supportsAdapterModelRefresh");function wat(e,s){return DNe(e,s).model}r(wat,"resolvePaperclipRunnerTransitionModel");function Yte(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(Yte,"isOverlayDirty");function r6(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)=>r6(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&&r6(o,a[i]))}return!1}r(r6,"overlayValuesEqual");function kat(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!r6(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(kat,"subtractPersistedOverlay");var Zm="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function Nat(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(Nat,"parseCommaArgs");function Sat(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(Sat,"formatArgList");var Cat=[{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"}],_at=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],Iat=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],Aat=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],Tat=2,Jte=10,Rat=1,qSe=300;function jE(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(jE,"clampInteger");function Eat(e){return jE(e,0,qSe)*1e3}r(Eat,"clampDelayMsFromSeconds");function Pat({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(Pat,"ConfigSections");function USe(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=Pt(),b=(0,m.useRef)(null),v=zSe(),{data:j=[]}=ee({queryKey:f?P.secrets.list(f):["secrets","none"],queryFn:r(()=>yr.list(f),"queryFn"),enabled:!!f}),{data:N=[]}=ee({queryKey:f?P.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>yr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:k=[]}=ee({queryKey:f?P.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>yr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>k.filter(Ze=>Ze.kind==="binding"&&Ze.target?.id===w),[k,w]),C=MSe(f,[]),{data:I}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),retry:!1}),R=(0,m.useMemo)(()=>{const Ze=new Set(v);return I?.enableNativeRunner!==!0&&Ze.add("paperclip_runner"),Ze},[v,I?.enableNativeRunner]),T=I?.enableEnvironments===!0,A=I?.enableManagedSandboxOnly===!0,D=I===void 0||A,{data:M}=ee({queryKey:P.instance.generalSettings,queryFn:r(()=>Nr.getGeneral(),"queryFn"),retry:!1}),{data:B}=ee({queryKey:P.instance.settings,queryFn:r(()=>Nr.get(),"queryFn"),retry:!1}),{data:E=[]}=ee({queryKey:f?P.environments.list(f):["environments","none"],queryFn:r(()=>Pi.list(f),"queryFn"),enabled:!!f&&(T||M?.executionMode==="kubernetes")}),{forced:z,kubernetesEnvironment:$}=(0,m.useMemo)(()=>zW(M?.executionMode,E),[M?.executionMode,E]),q=je({mutationFn:r(Ze=>{if(!f)throw new Error("Select an organization to create secrets");return yr.create(f,Ze)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.list(f)})},"onSuccess")}),U=je({mutationFn:r(async({file:Ze,namespace:At})=>{if(!f)throw new Error("Select an organization to upload images");return vb.uploadImage(f,Ze,At)},"mutationFn")}),[O,K]=(0,m.useState)(W$),[H,Z]=(0,m.useState)(!1),[se,ne]=(0,m.useState)(0),fe=(0,m.useRef)(null),X=(0,m.useRef)(null),re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(fe.current!==null&&e.agent!==fe.current&&!re.current){const Ze=X.current;X.current=null,K(At=>Ze?kat(At,Ze):{...W$})}fe.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(Yte(O)||H);function G(Ze,At,fs){const Ks=O[Ze];return At in Ks?Ks[At]:fs}r(G,"eff");function Y(Ze,At,fs){K(Ks=>({...Ks,[Ze]:{...Ks[Ze],[At]:fs}}))}r(Y,"mark");function Q(){return b.current?.flushPendingDraft()??null}r(Q,"flushEnvironmentDraft");const te=(0,m.useCallback)(Ze=>{a||K(At=>{const fs={...e.agent.adapterConfig??{},...At.adapterConfig},Ks={...At.adapterConfig};for(const[Ln,Cr]of Object.entries(Ze))Ks[`${hA}${Ln}`]=Cr;for(const Ln of Object.keys(fs))Ln.startsWith("access.")&&(Ln.slice(7)in Ze||(Ks[Ln]=void 0));return{...At,adapterConfig:Ks}})},[a,a?void 0:e.agent]),ae=(0,m.useCallback)(()=>{K({...W$}),Z(!1),ne(Ze=>Ze+1)},[]),le=(0,m.useCallback)(async()=>{if(a)return;const Ze=Q(),At=Ze?{...O,adapterConfig:{...O.adapterConfig,env:Ze}}:O;Yte(At)&&await e.onSave(V2(e.agent,At))},[a,oe,O,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(oe),e.onSaveActionChange?.(le),e.onCancelActionChange?.(ae))},[a,oe,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,le,ae]),(0,m.useEffect)(()=>{if(!a)return()=>{e.onSaveActionChange?.(null),e.onCancelActionChange?.(null),e.onDirtyChange?.(!1)}},[a,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const he=a?{}:e.agent.adapterConfig??{},ce=a?{}:e.agent.runtimeConfig??{},ge=a?{}:ce.heartbeat??{},me=a?{}:ce.debug??{},ie=a?e.values.adapterType:O.adapterType??e.agent.adapterType,ue=Wy(),ke=ue(ie),be=ke.supportsInstructionsBundle||ke.supportsSkills||ke.supportsLocalAgentJwt,Ie=be&&!D&&pat({isCreate:a,adapterConfig:he}),Ue=(0,m.useMemo)(()=>iS(ie),[ie]),at=(0,m.useMemo)(()=>new Set(Nze(ie)),[ie]),dt=a?e.values:null,de=a?Ze=>e.onChange(Ze):null;a&&dt.claudeStoredSessionId;const Be=r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),pt=r(Ze=>{if(!a||!de)return;const At=dt.envBindings??{};de({envBindings:{...At,...Vw()},claudeStoredSessionId:Ze}),Be()},"handleClaudeLoginStored"),vt=r(async()=>{if(a)return;const Ze={...Q()??G("adapterConfig","env",he.env??nC),...Vw()},At={...O,adapterConfig:{...O.adapterConfig,env:Ze}};K(At),await e.onSave({...V2(e.agent,At),applyStoredClaudeLogin:!0}),Be()},"handleClaudeLoginStoredEdit"),Le=r(async Ze=>{if(a||!Ze.companyIdentityDiffers)return;const At={...Q()??G("adapterConfig","env",he.env??nC),CODEX_HOME:{type:"secret_ref",secretId:Ze.secretId,version:"latest"}},fs={...O,adapterConfig:{...O.adapterConfig,env:At}};K(fs),X.current=fs,re.current=!0;try{await e.onSave(V2(e.agent,fs))}catch(Ks){throw X.current=null,Ks}finally{re.current=!1}Be()},"handleCodexAccountBindingEdit"),Qe=r(()=>{if(!a||!de)return;const Ze=dt.envBindings??{};de({envBindings:{...Ze,...Vw()},claudeApplyStoredLogin:!0}),Be()},"handleApplyStoredClaudeLogin"),ut=r(async()=>{if(a)return;const Ze={...Q()??G("adapterConfig","env",he.env??nC),...Vw()},At={...O,adapterConfig:{...O.adapterConfig,env:Ze}};K(At),await e.onSave({...V2(e.agent,At),applyStoredClaudeLogin:!0}),Be()},"handleApplyStoredClaudeLoginEdit"),Ye=a?dt.defaultEnvironmentId??"":G("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),it=(0,m.useMemo)(()=>Ye?(E.find(Ze=>Ze.id===Ye)??null)?.driver==="local"?"":Ye:"",[E,Ye]),kt=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===it)??null,[it,E]),tt=(0,m.useMemo)(()=>{const Ze=B?.defaultEnvironmentId??null;return Ze?(E.find(At=>At.id===Ze)??null)?.driver==="local"?"":Ze:""},[E,B?.defaultEnvironmentId]),Pe=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===tt)??null,[E,tt]),Ce=(0,m.useMemo)(()=>{try{return iN({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:B?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(E),managedSandboxOnly:I?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:oN(E),visibleEnvironmentIds:E.map(Ze=>Ze.id)})}catch{return null}},[Ye,B?.defaultEnvironmentId,E,I?.enableManagedSandboxOnly]),He=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===Ce)??null,[E,Ce]),{data:Je}=ee({queryKey:f?P.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>Pi.capabilities(f),"queryFn"),enabled:!!f&&ke.login!=null});(0,m.useEffect)(()=>{!a||!de||!z||!$||it!==$.id&&de({defaultEnvironmentId:$.id})},[a,de,z,$,it]);const lt=(0,m.useMemo)(()=>E.filter(Ze=>{if(!at.has(Ze.driver)||Ze.driver==="local")return!1;if(Ze.driver!=="sandbox")return!0;const At=typeof Ze.config?.provider=="string"?Ze.config.provider:null;return At!==null&&At!=="fake"}),[E,at]),Ee=(0,m.useMemo)(()=>!kt||lt.some(Ze=>Ze.id===kt.id)?lt:[...lt,kt],[kt,lt]),Xe=T&&(z||it.length>0||lt.length>=1),Ae=Pe?Yv(Pe):A?"Paperclip Computer":"Local",De=ie==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":G("adapterConfig","provider",he.provider==="acpx"&&he.acpxAgent==="codex"?"codex":he.provider??"codex")):void 0,_t=ie==="opencode_local"&&Zpe.safeParse(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection).data?.provider==="openrouter"?"openrouter":De,ye=f?P.agents.adapterModels(f,ie,it||null,_t):["agents","none","adapter-models",ie],{data:gt,error:We}=ee({queryKey:ye,queryFn:r(()=>$t.adapterModels(f,ie,{environmentId:it||null,provider:_t}),"queryFn"),enabled:!!f}),[Ot,zt]=(0,m.useState)(null),[Cs,ze]=(0,m.useState)(!1),ft=gt??n??[],Ut="command",{data:Ns,refetch:Is}=ee({queryKey:f?P.agents.detectModel(f,ie):["agents","none","detect-model",ie],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return $t.detectModel(f,ie)},"queryFn"),enabled:!!(f&&be&&ie!=="opencode_local"&&ie!=="paperclip_runner")}),Ct=Ns?.model??null;Ns?.candidates;const{data:ds=[]}=ee({queryKey:f?P.agents.list(f):["agents","none","list"],queryFn:r(()=>$t.list(f),"queryFn"),enabled:!!(!a&&f)}),$e={mode:s,isCreate:a,adapterType:ie,values:a?e.values:null,set:a?Ze=>e.onChange(Ze):null,config:he,eff:G,mark:Y,models:ft,hideInstructionsFile:h||D,managedSandboxOnly:D},[xe,Qt]=(0,m.useState)(!1),[Dt,rs]=(0,m.useState)(!1),ws=HNe(ie),Bs=r(Ze=>(0,t.jsxs)(t.Fragment,{children:[ie==="claude_local"&&(0,t.jsx)(ett,{...$e,section:Ze}),(0,t.jsx)(Ue.ConfigFields,{...$e,section:Ze,hideModel:be})]}),"renderAdapterFields"),[er,Fe]=(0,m.useState)(!1),[st,xt]=(0,m.useState)(!1);function Oe(Ze){if(a){const fs=Ue.buildAdapterConfig(dt);return Ze&&Object.assign(fs,Ze),D5(fs)}const At={...he,...O.adapterConfig};return Ze&&Object.assign(At,Ze),D5(At)}r(Oe,"buildAdapterConfigForTest");const Bt=je({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const Ze=Q(),At=Ze?{env:Ze}:void 0;let fs=B,Ks=E,Ln=I?.enableManagedSandboxOnly===!0;if(!Ye)try{const[_r,jr,sr]=await Promise.all([x.ensureQueryData({queryKey:P.instance.settings,queryFn:r(()=>Nr.get(),"queryFn")}),x.ensureQueryData({queryKey:P.environments.list(f),queryFn:r(()=>Pi.list(f),"queryFn")}),x.ensureQueryData({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")})]);fs=_r,Ks=jr,Ln=sr?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Cr=iN({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:fs?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(Ks),managedSandboxOnly:Ln,managedSandboxEnvironmentId:oN(Ks),visibleEnvironmentIds:Ks.map(_r=>_r.id)}),Vr=Oe(At),Pr=a?void 0:e.agent.id,Ar=a?void 0:CJ.safeParse(O.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const _r=ie==="paperclip_runner"?Vr.provider==="codex"?"codex_local":Vr.provider==="acpx"&&Vr.acpxAgent==="grok"?"grok_local":Vr.provider==="acpx"&&Vr.acpxAgent==="claude"?"claude_local":ie:ie;return TNe({companyId:f,adapterType:ie,providerAdapter:_r,adapterConfig:Vr,agentId:Pr,aiConnection:Ar,environmentId:Cr})}return $t.testEnvironment(f,ie,{adapterConfig:Vr,agentId:Pr,aiConnection:Ar,environmentId:Cr})},"mutationFn")}),[wt,Xt]=(0,m.useState)(!1),[Yt,hs]=(0,m.useState)(null),Ts="Test",as=!a&&!!e.isSaving,Zn=wt||as||!f,en=(0,m.useRef)(Bt.reset);en.current=Bt.reset;const nr=(0,m.useRef)(()=>{});nr.current=()=>{if(!a||!de)return;const Ze=dt.envBindings??{},At=dt.claudeStoredSessionId!=null||dt.claudeApplyStoredLogin===!0,fs=Bte in Ze;if(!At&&!fs)return;const Ks={...Ze};delete Ks[Bte],de({envBindings:Ks,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{en.current(),hs(null),nr.current()},[ie,Ce]);const tn=ke.login!=null,xn=Bt.data,Ht=xn!=null&&ue(xn.adapterType).login!=null,qs=xn&&Ht?xn.checks.find(Ze=>Ze.code==="adapter_auth_missing")??null:null,Vs=typeof He?.config?.provider=="string"?He.config.provider:null,Lt=Vs!=null&&Je?.sandboxProviders?.[Vs]?.supportsLoginPty===!0,is=ke.login!=null,Ms=(a||!(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection))&&tn&&He?.driver==="sandbox"&&!!Ce&&!!f&&!!qs&&(!is||Lt),bs=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");Xt(!0),hs(null),Bt.reset();try{return await Bt.mutateAsync()}catch(Ze){throw hs(Ze instanceof Error?Ze.message:"Environment test failed"),Ze}finally{Xt(!1)}},[f,Bt]),gn=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{gn.current=()=>{Zn||bs().catch(()=>{})}},[bs,Zn]);const Pn=(0,m.useCallback)(()=>{gn.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Pn),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Pn]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Zn,pending:wt}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Zn,wt]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Yt??(Bt.error instanceof Error?Bt.error.message:Bt.error?"Environment test failed":null),result:Bt.data??null,login:Ms&&f&&Ce?{companyId:f,adapterType:ie,environmentId:Ce}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Yt,Bt.data,Bt.error,Ms,f,ie,Ce]);const $r=a?dt.model??"":G("adapterConfig","model",String(he.model??"")),mt=typeof $r=="string"?$r:"";async function vs(){if(f){ze(!0),zt(null);try{const Ze=await $t.adapterModels(f,ie,{refresh:!0,environmentId:it||null,provider:_t});x.setQueryData(ye,Ze)}catch(Ze){zt(Ze instanceof Error?Ze.message:"Failed to refresh adapter models.")}finally{ze(!1)}}}r(vs,"handleRefreshModels");const Fs=ie==="codex_local"?"modelReasoningEffort":ie==="cursor"?"mode":ie==="opencode_local"?"variant":ie==="grok_local"?"reasoningEffort":ie==="pi_local"?"thinking":"effort",Hs=ie==="codex_local"?_W(mt,"Auto").map(Ze=>({id:Ze.value,label:Ze.label})):ie==="cursor"?_at:ie==="opencode_local"?Cat:ie==="kimi_local"?Aat:ie==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(Ze=>({id:Ze,label:Ze}))]:ie==="claude_local"||ie==="grok_local"?[{id:"",label:"Auto"},...I5(ie,mt).map(Ze=>({id:Ze,label:Ze==="xhigh"?"X-High":Ze[0].toUpperCase()+Ze.slice(1)}))]:Iat,zs=a?dt.thinkingEffort:ie==="codex_local"?G("adapterConfig","modelReasoningEffort",String(he.modelReasoningEffort??he.reasoningEffort??"")):ie==="cursor"?G("adapterConfig","mode",String(he.mode??"")):ie==="opencode_local"?G("adapterConfig","variant",String(he.variant??"")):G("adapterConfig",Fs,String(he[Fs]??"")),Us=ie!=="gemini_local"&&ie!=="cursor_cloud"&&ie!=="paperclip_runner",ur=ie==="codex_local"?a?!!dt.search:G("adapterConfig","search",!!he.search):!1,Dn=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:dt.heartbeatEnabled,intervalSec:dt.intervalSec}};const Ze={...ce.heartbeat&&typeof ce.heartbeat=="object"?ce.heartbeat:{},...O.heartbeat};return{...ce,heartbeat:Ze}},[a,O.heartbeat,ce,dt]),Er=PJ(Dn.heartbeat),Jn=PJ(Er.maxTurnContinuation),tr=R$e(Jn.enabled,!0),pn=jE(qJ(Jn.maxAttempts,Tat),0,Jte),yt=jE(qJ(Jn.delayMs,Rat*1e3)/1e3,0,qSe);function Ps(Ze){Y("heartbeat","maxTurnContinuation",{...Jn,...Ze})}r(Ps,"updateMaxTurnContinuation");const Zs=(0,t.jsx)(jy,{ref:b,onDirtyChange:Z,hideDraftActions:!a&&e.hideInlineSave,value:a?dt.envBindings??nC:G("adapterConfig","env",he.env??nC),secrets:j,userSecretDefinitions:N,onCreateSecret:r(async(Ze,At)=>await q.mutateAsync({name:Ze,value:At}),"onCreateSecret"),onChange:r(Ze=>a?de({envBindings:Ze??{},envVars:""}):Y("adapterConfig","env",Ze),"onChange")},se);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end border-b border-primary/20 bg-background/90 px-4 py-2 backdrop-blur-sm",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)(L,{size:"sm",onClick:le,disabled:e.isSaving,children:e.isSaving?"Saving...":"Save"})]})}),e.environmentVariablesPlacement==="secrets"&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:Zs})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Secret access"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Secret access"}),(0,t.jsxs)("div",{className:W(i?"space-y-3 rounded-lg border border-border p-4":"space-y-3 px-4 pb-3"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:Ni.secretAccess}),(0,t.jsx)(uat,{config:{...he,...O.adapterConfig},secrets:j,onChange:te,onCreateSecret:r((Ze,At)=>q.mutateAsync({name:Ze,value:At}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(Pat,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)(L,{size:"sm",onClick:le,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(Ss,{label:"Name",hint:Ni.name,children:(0,t.jsx)(Ka,{value:G("identity","name",e.agent.name),onCommit:r(Ze=>Y("identity","name",Ze),"onCommit"),immediate:!0,className:Zm,placeholder:"Agent name"})}),(0,t.jsx)(Ss,{label:"Title",hint:Ni.title,children:(0,t.jsx)(Ka,{value:G("identity","title",e.agent.title??""),onCommit:r(Ze=>Y("identity","title",Ze||null),"onCommit"),immediate:!0,className:Zm,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(Ss,{label:"Reports to",hint:Ni.reportsTo,children:(0,t.jsx)(krt,{agents:ds,value:G("identity","reportsTo",e.agent.reportsTo??null),onChange:r(Ze=>Y("identity","reportsTo",Ze),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),be&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Prompt Template",hint:Ni.promptTemplate,children:(0,t.jsx)(fd,{value:G("adapterConfig","promptTemplate",String(he.promptTemplate??"")),onChange:r(Ze=>Y("adapterConfig","promptTemplate",Ze??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async Ze=>{const At=`agents/${e.agent.id}/prompt-template`;return(await U.mutateAsync({file:Ze,namespace:At})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-900 dark:text-amber-100",children:"Prompt template is replayed on every heartbeat. Keep it compact and dynamic to avoid recurring token cost and cache churn."})]})]})]}),z?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:$?(0,t.jsxs)("div",{className:W(Zm,"flex items-center text-muted-foreground"),children:[$.name," · Kubernetes sandbox"]}):(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"This instance requires the Kubernetes sandbox, but no managed Kubernetes environment is available for this organization yet. Configure one before creating agents; execution will not fall back to local."})})})]}):Xe?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:Zm,value:it,onChange:r(Ze=>{const At=Ze.target.value;if(a){de({defaultEnvironmentId:At});return}Y("identity","defaultEnvironmentId",At||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Ae]}),Ee.map(Ze=>(0,t.jsx)("option",{value:Ze.id,children:Yv(Ze)},Ze.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:W(i?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium",children:e.sectionTitles?.adapter??"Adapter"}):(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),c&&(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:Pn,disabled:Zn,children:wt?`${Ts}...`:Ts})]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(Ss,{label:"Adapter type",hint:Ni.adapterType,children:(0,t.jsx)(WSe,{value:ie,disabledTypes:R,onChange:r(Ze=>{if(a){const{adapterType:At,...fs}=ab,Ks={...fs,adapterType:Ze};Ze==="codex_local"?Ks.dangerouslyBypassSandbox=!0:Ze==="gemini_local"?Ks.model="auto":Ze==="kimi_local"?Ks.model="kimi-code/kimi-for-coding":Ze==="cursor"?Ks.model="auto":Ze==="opencode_local"?Ks.model="openai/gpt-5.2-codex":Ze==="paperclip_runner"&&(Ks.model=nN),de(Ks)}else K(At=>({...At,adapterType:Ze,adapterConfig:{model:Ze==="gemini_local"?"auto":Ze==="kimi_local"?"kimi-code/kimi-for-coding":Ze==="opencode_local"?"openai/gpt-5.2-codex":Ze==="cursor"?"auto":Ze==="paperclip_runner"?wat(ie,he.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...Ze==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:Ze==="paperclip_runner"?{...DNe(ie,G("adapterConfig","model",he.model))}:{}}}))},"onChange")})}),!a&&f&&(0,t.jsx)(ANe,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:ie==="paperclip_runner"?G("adapterConfig","provider",he.provider)==="codex"?"codex_local":G("adapterConfig","provider",he.provider)==="opencode"?"opencode_local":G("adapterConfig","provider",he.provider)==="acpx"&&G("adapterConfig","acpxAgent",he.acpxAgent)==="grok"?"grok_local":G("adapterConfig","provider",he.provider)==="acpx"&&G("adapterConfig","acpxAgent",he.acpxAgent)==="claude"?"claude_local":ie:ie,routerAdapterType:ie,value:CJ.safeParse(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection).data,model:String(G("adapterConfig","model",he.model)??""),environmentId:it||void 0,legacy:!0,onChange:r(Ze=>Y("runtime","runtimeConfig",{...ce,aiConnection:Ze}),"onChange")}),d&&!e.compactTestFeedback&&(Yt||Bt.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Yt??(Bt.error instanceof Error?Bt.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&Bt.data&&(0,t.jsx)(Bat,{result:Bt.data}),d&&Ms&&(0,t.jsx)(qW,{companyId:f,adapterType:ie,environmentId:Ce,onStored:a?pt:vt,onApplyStored:a?Qe:ut,onAccountBinding:a?void 0:Le},`${ie}:${Ce}`),Ie&&(0,t.jsx)(Ss,{label:"Working directory (deprecated)",hint:Ni.cwd,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[(0,t.jsx)(Go,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(Ka,{value:a?dt.cwd:G("adapterConfig","cwd",String(he.cwd??"")),onCommit:r(Ze=>a?de({cwd:Ze}):Y("adapterConfig","cwd",Ze||void 0),"onCommit"),immediate:!0,className:"w-full bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",placeholder:"/path/to/project"}),(0,t.jsx)(Dd,{})]})}),Bs("adapter"),be&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(UW,{models:ft,value:mt,onChange:r(Ze=>{const At=I5(ie,Ze),fs=["codex_local","claude_local","grok_local"].includes(ie)&&!!zs&&!At.includes(String(zs));if(a){de({model:Ze,...fs?{thinkingEffort:""}:{}});return}Y("adapterConfig","model",Ze||void 0),fs&&(Y("adapterConfig",Fs,void 0),Y("adapterConfig","reasoningEffort",void 0))},"onChange"),open:er,onOpenChange:Fe,defaultLabel:ie==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:ie!=="opencode_local"&&ie!=="pi_local"&&ie!=="paperclip_runner",required:ie==="opencode_local"||ie==="pi_local",groupByProvider:ie==="opencode_local"||ie==="pi_local",preserveOrder:PW(ie),creatable:!0,detectedModel:Ct,detectedModelCandidates:[],onDetectModel:ie==="opencode_local"||ie==="paperclip_runner"?void 0:async()=>(await Is()).data?.model??null,onRefreshModels:jat(ie)?vs:void 0,refreshingModels:Cs,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Ot||We)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Ot??(We instanceof Error?We.message:"Failed to load adapter models.")}),ie==="opencode_local"&&kt&&kt.driver!=="local"&&(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Live OpenCode model discovery only runs for Local environments. Using the curated list and manual entry for ",kt.name,"."]}),Us&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(zat,{value:zs,options:Hs,onChange:r(Ze=>a?de({thinkingEffort:Ze}):Y("adapterConfig",Fs,Ze||void 0),"onChange"),open:st,onOpenChange:xt}),ie==="codex_local"&&ur&&zs==="minimal"&&(0,t.jsx)("p",{className:"text-xs text-amber-400",children:"Codex may reject `minimal` thinking when search is enabled."})]})]})]})]}),(0,t.jsxs)("div",{"data-config-section":"configuration",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Configuration"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Configuration"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[!a&&typeof he.bootstrapPromptTemplate=="string"&&he.bootstrapPromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Bootstrap prompt (legacy)",hint:Ni.bootstrapPrompt,children:(0,t.jsx)(fd,{value:G("adapterConfig","bootstrapPromptTemplate",String(he.bootstrapPromptTemplate??"")),onChange:r(Ze=>Y("adapterConfig","bootstrapPromptTemplate",Ze||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async Ze=>{const At=`agents/${e.agent.id}/bootstrap-prompt`;return(await U.mutateAsync({file:Ze,namespace:At})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"Bootstrap prompt is legacy and will be removed in a future release. Consider moving this content into the agent's prompt template or instructions file instead."})]}),Bs("configuration"),(be||ie==="process"||ws?.fields.some(Ze=>zq(Ze.key)==="advanced"))&&(0,t.jsx)(pE,{title:"Advanced",open:Dt,onToggle:r(()=>rs(!Dt),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[be&&(0,t.jsxs)(t.Fragment,{children:[" ",!D&&(0,t.jsx)(Ss,{label:"Command",hint:Ni.localCommand,children:(0,t.jsx)(Ka,{value:a?dt.command:G("adapterConfig",Ut,String(he.command??"")),onCommit:r(Ze=>a?de({command:Ze}):Y("adapterConfig",Ut,Ze||null),"onCommit"),immediate:!0,className:Zm,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[ie]??ie.replace(/_local$/,"")})}),(0,t.jsx)(Ss,{label:"Extra args (comma-separated)",hint:Ni.extraArgs,children:(0,t.jsx)(Ka,{value:a?dt.extraArgs:G("adapterConfig","extraArgs",Sat(he.extraArgs)),onCommit:r(Ze=>a?de({extraArgs:Ze}):Y("adapterConfig","extraArgs",Ze?.trim()?Nat(Ze):null),"onCommit"),className:Zm,placeholder:"e.g. --verbose, --foo=bar"})})]}),Bs("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(be||ws?.fields.some(Ze=>zq(Ze.key)==="environment"))&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:be?Zs:Bs("environment")})]}),a&&u?(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(FC,{className:"h-3 w-3"})," Run Policy"]}):(0,t.jsxs)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[(0,t.jsx)(FC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(hte,{label:"Heartbeat on interval",hint:Ni.heartbeatInterval,checked:dt.heartbeatEnabled,onCheckedChange:r(Ze=>de({heartbeatEnabled:Ze}),"onCheckedChange"),number:dt.intervalSec,onNumberChange:r(Ze=>de({intervalSec:Ze}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Ni.intervalSec,showNumber:dt.heartbeatEnabled}),(0,t.jsx)(pE,{title:"Advanced Run Policy",open:xe,onToggle:r(()=>Qt(!xe),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Bs("runPolicy")})})]})]}):a?null:(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(FC,{className:"h-3 w-3"})," Run Policy"]}):(0,t.jsxs)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[(0,t.jsx)(FC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg overflow-hidden":""),children:[(0,t.jsx)("div",{className:W(i?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(hte,{label:"Heartbeat on interval",hint:Ni.heartbeatInterval,checked:G("heartbeat","enabled",ge.enabled===!0),onCheckedChange:r(Ze=>Y("heartbeat","enabled",Ze),"onCheckedChange"),number:G("heartbeat","intervalSec",Number(ge.intervalSec??300)),onNumberChange:r(Ze=>Y("heartbeat","intervalSec",Ze),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Ni.intervalSec,showNumber:G("heartbeat","enabled",ge.enabled===!0)})}),(0,t.jsx)(pE,{title:"Advanced Run Policy",bordered:i,open:xe,onToggle:r(()=>Qt(!xe),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Bs("runPolicy"),be&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!ws?.fields.some(Ze=>Ze.key==="timeoutSec")&&(0,t.jsx)(Ss,{label:"Timeout (sec)",hint:Ni.timeoutSec,children:(0,t.jsx)(Rc,{value:G("adapterConfig","timeoutSec",Number(he.timeoutSec??0)),onCommit:r(Ze=>Y("adapterConfig","timeoutSec",Ze),"onCommit"),immediate:!0,className:Zm})}),!ws?.fields.some(Ze=>Ze.key==="graceSec")&&(0,t.jsx)(Ss,{label:"Interrupt grace period (sec)",hint:Ni.graceSec,children:(0,t.jsx)(Rc,{value:G("adapterConfig","graceSec",Number(he.graceSec??15)),onCommit:r(Ze=>Y("adapterConfig","graceSec",Ze),"onCommit"),immediate:!0,className:Zm})})]})}),(0,t.jsx)(Cd,{label:"Wake on demand",hint:Ni.wakeOnDemand,checked:G("heartbeat","wakeOnDemand",ge.wakeOnDemand!==!1),onChange:r(Ze=>Y("heartbeat","wakeOnDemand",Ze),"onChange")}),(0,t.jsx)(Ss,{label:"Cooldown (sec)",hint:Ni.cooldownSec,children:(0,t.jsx)(Rc,{value:G("heartbeat","cooldownSec",Number(ge.cooldownSec??10)),onCommit:r(Ze=>Y("heartbeat","cooldownSec",Ze),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsx)(Ss,{label:"Max concurrent runs",hint:Ni.maxConcurrentRuns,children:(0,t.jsx)(Rc,{value:G("heartbeat","maxConcurrentRuns",Number(ge.maxConcurrentRuns??20)),onCommit:r(Ze=>Y("heartbeat","maxConcurrentRuns",Ze),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(Cd,{label:"Continue after max-turn stop",hint:Ni.maxTurnContinuationEnabled,checked:tr,onChange:r(Ze=>Ps({enabled:Ze}),"onChange")}),tr?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Continuation attempts",hint:Ni.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Rc,{value:pn,onCommit:r(Ze=>Ps({maxAttempts:jE(Ze,0,Jte)}),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsx)(Ss,{label:"Continuation delay (sec)",hint:Ni.maxTurnContinuationDelaySec,children:(0,t.jsx)(Rc,{value:yt,onCommit:r(Ze=>Ps({delayMs:Eat(Ze)}),"onCommit"),immediate:!0,className:Zm})})]}):null]})]})})]})]}),!a&&p?(0,t.jsxs)("div",{className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"mb-3 flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)(Kv,{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)(Kv,{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)(Cd,{label:"Capture raw provider traces",hint:"Stores exact provider traffic for every future run until disabled. Traces may contain sensitive prompts and tool arguments, are administrator-only, and expire after 24 hours.",checked:G("debug","providerTrace",me.providerTrace)==="raw",onChange:r(Ze=>Y("debug","providerTrace",Ze?"raw":void 0),"onChange")}),G("debug","providerTrace",me.providerTrace)==="raw"?(0,t.jsxs)("div",{className:"mt-3 flex items-start gap-2 rounded-md border border-border bg-background/60 px-3 py-2 text-xs text-foreground",children:[(0,t.jsx)(Kv,{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)(qNe,{state:wt?"running":Yt||Bt.error?"fail":xn?.status??"idle",result:xn??null,error:Yt??(Bt.error instanceof Error?Bt.error.message:null),onTest:Pn,disabled:Zn})]})}r(USe,"AgentConfigForm");var a6=new Set(["authenticated","failed","timed_out","cancelled"]),i6=2e3;function o6({value:e,label:s}){const[n,a]=(0,m.useState)(!1),i=(0,m.useRef)(null);return(0,m.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-xs","aria-label":s,title:s,className:"text-muted-foreground hover:text-foreground",onClick:r(async()=>{try{await fa(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(gs,{className:"size-3"}):(0,t.jsx)(Ir,{className:"size-3"})})}r(o6,"AdapterLoginCopyButton");function Mat({status:e,message:s}){return e==="authenticated"?(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}):(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsxs)("span",{children:[e==="timed_out"?"Login timed out":e==="cancelled"?"Login cancelled":"Login failed",s?`: ${s}`:"."]})]})}r(Mat,"AdapterLoginTerminalState");var Dat={claude_local:"Anthropic",codex_local:"OpenAI"};function KSe(e){const s=Dat[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(KSe,"adapterLoginTitle");function qW(e){return Wy()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(Fat,{...e}):(0,t.jsx)(Lat,{...e})}r(qW,"AdapterLoginPanel");var V$=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 Lat({companyId:e,adapterType:s,environmentId:n,autoStart:a,onConnected:i,onAccountBinding:o,chrome:l="panel",aiConnection:c,onPromptReady:d}){const[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,b]=(0,m.useState)(null),[v,j]=(0,m.useState)("idle"),N=(0,m.useRef)(!1),w=je({mutationFn:r(()=>$t.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(re=>{N.current=!1,f(null),b(null),j("idle"),h(re.sessionId)},"onSuccess"),onError:r(re=>{f(re instanceof Error?re.message:"Could not start the login.")},"onError")}),k=(0,m.useCallback)(()=>{N.current=!1,h(null),b(null),f(null)},[]),S=je({mutationFn:r(()=>$t.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:k,onError:r(re=>{f(re instanceof Error?re.message:"Could not cancel the login.")},"onError")}),C=ee({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 V$(re.sessionId);return re}catch(re){if(re instanceof dn&&re.status===404)return null;throw re}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[I,R]=(0,m.useState)(!1),T=ee({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>$t.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!I,retry:r((re,oe)=>oe instanceof dn&&oe.status===404?!1:re<3,"retry"),refetchInterval:r(re=>{const oe=re.state.data?.status;return oe&&a6.has(oe)?!1:i6},"refetchInterval")});(0,m.useEffect)(()=>{const re=T.data?.prompt??null;re&&b(re)},[T.data]);const A=T.data??w.data??null,D=A?.status??null,M=x,B=D?a6.has(D):!1,E=!!u&&!B,z=w.isPending||E||v==="saving",$=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if($.current||!C.isFetched)return;$.current=!0;const re=C.data;re&&(N.current=!0,f(null),b(re.prompt??null),h(re.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const re=T.error;if(!(re instanceof dn&&re.status===404)||!N.current||I)return;R(!0);const oe=u;(async()=>(oe&&await $t.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),k()))()},[T.error,I,u,e,s,k]);const q=(0,m.useRef)(!1),U=je({mutationFn:r(async()=>{const re=C.error;re instanceof V$&&await $t.cancelAdapterAuthLogin(e,s,re.sessionId)},"mutationFn"),onSuccess:r(async()=>{q.current=!1,$.current=!1,f(null),await C.refetch()},"onSuccess"),onError:r(()=>f("Could not cancel the previous sign-in. Retry before starting a new one."),"onError")}),O=(0,m.useRef)(w.mutate);O.current=w.mutate,(0,m.useEffect)(()=>{if(!(!a||q.current)){if(C.isError){q.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(q.current=!0,!C.data&&O.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),H=(0,m.useRef)(i);H.current=i,(0,m.useEffect)(()=>{D!=="authenticated"||K.current||(K.current=!0,H.current?.(u??void 0))},[D]);const Z=(0,m.useRef)(null),se=(0,m.useRef)(o);se.current=o;const ne=T.data?.codexAccountBinding??null,fe=(0,m.useCallback)(async re=>{const oe=se.current;if(oe){j("saving");try{await oe(re),j("bound")}catch{j("failed")}}},[]);(0,m.useEffect)(()=>{D!=="authenticated"||!u||Z.current!==u&&(!ne||!ne.companyIdentityDiffers||!se.current||(Z.current=u,fe(ne)))},[D,u,ne,fe]);const X=(0,m.useRef)(d);if(X.current=d,(0,m.useEffect)(()=>{X.current?.(M?.url??null)},[M]),l==="onboarding"){const re=B&&D&&D!=="authenticated";return(0,t.jsx)(XNe,{loading:!M&&!p&&!re,providerName:YNe(s),authorizationUrl:M?.url,mode:"displayed_code",children:p?(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:p}),C.error instanceof V$&&(0,t.jsx)(L,{type:"button",variant:"outline",disabled:U.isPending,onClick:r(()=>U.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):re?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D==="timed_out"?"The login timed out. Start it again.":D==="cancelled"?"The login was cancelled.":"The login did not finish. Start it again."}):(0,t.jsx)(Pet,{code:M?.code??"",autoCopy:!0})})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:KSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[E&&(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:S.isPending,onClick:r(()=>S.mutate(),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:z,onClick:r(()=>w.mutate(),"onClick"),children:"Sign in"})]})]}),p&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:p}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[E&&!M&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),E&&M&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Copy the code, then open the authentication page."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Code"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:M.code})]}),(0,t.jsx)(o6,{value:M.code,label:"Copy code"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Authentication URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:M.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(o6,{value:M.url,label:"Copy URL"}),(0,t.jsx)(L,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authentication page",title:"Open the authentication page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:M.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Vn,{className:"size-3"})})})]})]})]}),B&&D&&(0,t.jsx)(Mat,{status:D,message:A?.failure?.message??null}),D==="authenticated"&&v==="saving"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Binding this agent to the signed-in account..."})]}),D==="authenticated"&&v==="bound"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Agent bound to the signed-in account."})]}),D==="authenticated"&&v==="failed"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro)",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 text-destructive"}),(0,t.jsx)("span",{className:"text-destructive",children:"Could not bind this agent to the signed-in account."}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:r(()=>{ne&&fe(ne)},"onClick"),children:"Retry"})]})]})]})}r(Lat,"DisplayedCodeLoginPanel");var $at=new Set(["failed","timed_out","cancelled"]),Xte="The login did not finish. Start the login again.",Oat=9e5,Zte="The login timed out. Start the login again.";function Fat({companyId:e,adapterType:s,environmentId:n,onStored:a,onApplyStored:i,autoStart:o,onConnected:l,onCodeSubmitted:c,onSubmitFailed:d,chrome:u="panel",aiConnection:h,onPromptReady:p}){const[f,x]=(0,m.useState)(null),[b,v]=(0,m.useState)(null),[j,N]=(0,m.useState)(null),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[I,R]=(0,m.useState)(null),[T,A]=(0,m.useState)(!1),[D,M]=(0,m.useState)(!1),[B,E]=(0,m.useState)(!1),[z,$]=(0,m.useState)(!1),q=(0,m.useRef)(!1),[U,O]=(0,m.useState)(!1),K=(0,m.useRef)(!1),H=r(()=>{v(null),N(null),k(!1),C(""),R(null),A(!1),M(!1),$(!1),E(!1),q.current=!1},"resetLocalState"),Z=ee({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await $t.getClaudeOAuthTokenStatus(e)}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),retry:r((tt,Pe)=>Pe instanceof dn&&Pe.status===404?!1:tt<2,"retry")}).data??null,se=je({mutationFn:r(()=>$t.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...Z&&!h?{overwrite:{expectedSecretId:Z.secretId,expectedLatestVersion:Z.latestVersion}}:{}}),"mutationFn"),onSuccess:r(tt=>{K.current=!1,H(),x(tt.sessionId)},"onSuccess"),onError:r(tt=>{v(tt instanceof Error?tt.message:"Could not start the login.")},"onError")}),ne=r(()=>{K.current=!1,x(null),H()},"clearActiveSession"),fe=je({mutationFn:r(()=>$t.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{ne()},"onSuccess"),onError:r(tt=>{if(tt instanceof dn&&tt.status===404){ne();return}v(tt instanceof Error?tt.message:"Could not cancel the login.")},"onError")}),X=(0,m.useCallback)(tt=>{$t.cancelClaudeSetupTokenLogin(e,tt).catch(()=>{})},[e]),re=ee({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const tt=await $t.getActiveClaudeSetupTokenLoginSession(e);if(!tt)return null;if(h&&tt.environmentId!==n||!!tt.aiConnection!=!!h||h&&(tt.aiConnection?.provider!==h.provider||tt.aiConnection?.method!==h.method||tt.aiConnection?.connectionId!==h.connectionId||tt.aiConnection?.ownership!==h.ownership||tt.aiConnection?.allAgents!==h.allAgents||JSON.stringify(tt.aiConnection?.agentIds)!==JSON.stringify(h.agentIds)))throw new Error("Another sign-in attempt is active. Finish or cancel it in its original account setup before starting this one.");return tt}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,G]=(0,m.useState)(!1),Y=!!f&&!D&&!z&&!oe,Q=ee({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>$t.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:Y,retry:r((tt,Pe)=>Pe instanceof dn&&Pe.status===404?!1:tt<3,"retry"),refetchInterval:r(tt=>{if(D||z)return!1;const Pe=tt.state.data?.status;return Pe&&a6.has(Pe)?!1:i6},"refetchInterval")});(0,m.useEffect)(()=>{const tt=Q.error;if(tt instanceof dn&&tt.status===404){if(K.current){if(oe)return;G(!0);const Pe=f;(async()=>(Pe&&await $t.cancelClaudeSetupTokenLogin(e,Pe).catch(()=>{}),G(!1),ne()))();return}$(!0)}},[Q.error,oe,f,e]);const te=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(te.current||!re.isFetched)return;te.current=!0;const tt=re.data;tt&&(K.current=!0,H(),x(tt.sessionId),tt.prompt&&(N(tt.prompt.authorizationUrl),tt.prompt.transportAdvisory&&k(!0)))},[re.isFetched,re.data]);const ae=ee({queryKey:["claude-setup-token-prompt",e,f],enabled:Y&&!j,queryFn:r(async()=>{try{return await $t.getClaudeSetupTokenLoginPrompt(e,f)}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),refetchInterval:r(tt=>D||tt.state.data?.authorizationUrl?!1:i6,"refetchInterval")});(0,m.useEffect)(()=>{const tt=ae.data?.authorizationUrl??null;tt&&N(tt),ae.data?.transportAdvisory&&k(!0)},[ae.data]);const le=je({mutationFn:r(tt=>$t.submitClaudeSetupTokenBrowserCode(e,f,tt),"mutationFn"),onError:r(tt=>{v(tt instanceof Error?tt.message:"Could not submit the browser code.")},"onError")}),he=je({mutationFn:r(()=>$t.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(tt=>{R(tt.storedSessionId),a?.(tt.storedSessionId)},"onSuccess"),onError:r(()=>{A(!0)},"onError")}),ce=Q.data?.status??se.data?.status??null,ge=Q.data?.expiresAt??se.data?.expiresAt??null,me=(0,m.useRef)(he.mutate);me.current=he.mutate,(0,m.useEffect)(()=>{ce==="authenticated"&&!q.current&&(q.current=!0,me.current())},[ce]);const ie=I!==null,ue=T||z||!!(ce&&$at.has(ce)),ke=ce==="authenticated"&&!ie&&!T,be=!!f&&!ie&&!ue&&!D,Ie=se.isPending||be;(0,m.useEffect)(()=>{if(!be)return;const tt=ge!==null?new Date(ge).getTime():NaN,Pe=Number.isFinite(tt)?Math.max(0,tt-Date.now()):Oat,Ce=setTimeout(()=>{f&&X(f),M(!0)},Pe);return()=>clearTimeout(Ce)},[be,ge,f,X]);const Ue=S.trim(),at=be&&!!j&&!ke&&ELe(Ue)&&!le.isPending&&!B,dt=(0,m.useRef)(c);dt.current=c;const de=(0,m.useRef)(d);de.current=d;const Be=r(()=>{at&&(v(null),le.mutate(Ue),E(!0),dt.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),pt=(0,m.useRef)(!1),vt=(0,m.useRef)(se.mutate);vt.current=se.mutate,(0,m.useEffect)(()=>{if(!(!o||pt.current)){if(re.isError){pt.current=!0,v(re.error instanceof Error?re.error.message:"Could not check for an active login.");return}re.isSuccess&&(pt.current=!0,!re.data&&vt.current())}},[o,re.isSuccess,re.isError,re.data,re.error]);const Le=(0,m.useRef)(Be);Le.current=Be;const Qe=u==="onboarding",ut=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Qe||!ut.current||(ut.current=!1,at&&Le.current())},[Qe,at,S]);const Ye=(0,m.useRef)(!1),it=(0,m.useRef)(l);it.current=l,(0,m.useEffect)(()=>{!ie||Ye.current||(Ye.current=!0,it.current?.(f??void 0))},[ie]),(0,m.useEffect)(()=>{B&&(!b&&!ue&&!D||(E(!1),de.current?.()))},[B,b,ue,D]);const kt=(0,m.useRef)(p);if(kt.current=p,(0,m.useEffect)(()=>{kt.current?.(j)},[j]),u==="onboarding"){const tt=ue||D;return(0,t.jsxs)(XNe,{loading:!j&&!b&&!tt,providerName:YNe(s),authorizationUrl:j??void 0,mode:"submitted_code",children:[w&&(0,t.jsxs)("p",{className:"flex items-start gap-2 pl-2 text-xs text-amber-700 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"mt-0.5 size-3 shrink-0"}),"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."]}),b?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:b}):tt?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D&&!ue?Zte:Xte}):(0,t.jsx)(i4,{value:S,onChange:C,onSubmit:Be,onPaste:r(()=>{ut.current=!0},"onPaste"),masked:!0,disabled:le.isPending||ke||B})]})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:KSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[be&&(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:fe.isPending,onClick:r(()=>fe.mutate(),"onClick"),children:"Cancel"}),i&&Z&&!be&&!ie&&!U&&(0,t.jsx)(L,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),O(!0)},"onClick"),children:"Use saved login"}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Ie,onClick:r(()=>se.mutate(),"onClick"),children:Z&&!be&&!ie?"Sign in to replace":"Sign in"})]})]}),Z&&!be&&!ie&&!U&&(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"You have a saved Claude login. Use it to bind this agent, or log in again to replace the stored token."}),U&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"The saved Claude login is bound to this agent now."})]}),b&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:b}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[be&&!j&&!ke&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),be&&j&&!ke&&(0,t.jsxs)("div",{className:"space-y-2",children:[w&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 mt-0.5"}),(0,t.jsx)("span",{children:"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."})]}),(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Open the authorization page, then enter the browser code it shows."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Authorization URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:j})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(o6,{value:j,label:"Copy URL"}),(0,t.jsx)(L,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authorization page",title:"Open the authorization page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:j,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Vn,{className:"size-3"})})})]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Browser code"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{"aria-label":"Browser code",type:"text",autoComplete:"off",spellCheck:!1,value:S,onChange:r(tt=>C(tt.target.value),"onChange"),onKeyDown:r(tt=>{tt.key==="Enter"&&(tt.preventDefault(),Be())},"onKeyDown"),className:"flex-1 min-w-0 rounded-md border border-border bg-background px-2 py-1 font-mono text-xs text-foreground"}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:!at,onClick:Be,children:"Submit"})]})]})]}),ke&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),ie&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),ue&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Xte})]}),D&&!ue&&!ie&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Zte})]})]})]})}r(Fat,"SubmittedBrowserCodeLoginPanel");function Bat({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(Bat,"AdapterEnvironmentResult$1");function WSe({value:e,onChange:s,disabledTypes:n}){const[a,i]=(0,m.useState)(!1),o=Ch(e),l=(0,m.useMemo)(()=>BSe(c=>rN[c]??Bf(c)).filter(c=>!n.has(c.value)),[n]);return(0,t.jsxs)(br,{open:a,onOpenChange:i,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e==="opencode_local"?(0,t.jsx)(qq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{className:"truncate",children:rN[e]??Bf(e)}),o.experimental&&(0,t.jsx)(ese,{})]}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:l.map(c=>(0,t.jsxs)("button",{disabled:c.comingSoon,className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",c.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",c.value===e&&!c.comingSoon&&"bg-accent"),onClick:r(()=>{c.comingSoon||(s(c.value),i(!1))},"onClick"),children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[c.value==="opencode_local"?(0,t.jsx)(qq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{children:c.label}),c.experimental&&(0,t.jsx)(ese,{})]}),c.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},c.value))})]})}r(WSe,"AdapterTypeDropdown");function ese(){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(ese,"ExperimentalBadge$1");function UW({models:e,value:s,onChange:n,open:a,onOpenChange:i,allowDefault:o,required:l,groupByProvider:c,preserveOrder:d,creatable:u,detectedModel:h,detectedModelCandidates:p,onDetectModel:f,onRefreshModels:x,refreshingModels:b,detectModelLabel:v,emptyDetectHint:j,defaultLabel:N}){const[w,k]=(0,m.useState)(""),[S,C]=(0,m.useState)(!1),I=e.find(E=>E.id===s),R=w.trim(),T=!!(u&&R&&!e.some(E=>E.id.toLowerCase()===R.toLowerCase())),A=(0,m.useMemo)(()=>{const E=new Set;h&&E.add(h);for(const z of p??[])z&&E.add(z);return E},[h,p]),D=(0,m.useMemo)(()=>e.filter(E=>{if(A.has(E.id))return!1;if(!w.trim())return!0;const z=w.toLowerCase(),$=Kq(E.id)??"";return E.id.toLowerCase().includes(z)||E.label.toLowerCase().includes(z)||$.toLowerCase().includes(z)}),[e,w,A]),M=(0,m.useMemo)(()=>{if(!c)return[{provider:"models",entries:d?D:[...D].sort((z,$)=>z.id.localeCompare($.id))}];const E=new Map;for(const z of D){const $=Kq(z.id)??"other",q=E.get($)??[];q.push(z),E.set($,q)}return Array.from(E.entries()).sort(([z],[$])=>z.localeCompare($)).map(([z,$])=>({provider:z,entries:[...$].sort((q,U)=>q.id.localeCompare(U.id))}))},[D,c,d]);async function B(){if(f){C(!0);try{const E=await f();E&&(n(E),i(!1),k(""))}finally{C(!1)}}}return r(B,"handleDetectModel"),(0,t.jsx)(Ss,{label:"Model",hint:Ni.model,children:(0,t.jsxs)(br,{open:a,onOpenChange:r(E=>{i(E),E||k("")},"onOpenChange"),children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!s&&"text-muted-foreground"),children:I?I.label:s||(o?N??"Default":l?"Select model (required)":"Select model")}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsxs)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[(0,t.jsxs)("div",{className:"relative mb-1",children:[(0,t.jsx)("input",{className:"w-full px-2 py-1.5 pr-6 text-xs bg-transparent outline-none border-b border-border placeholder:text-muted-foreground/50",placeholder:u?"Search models... (type to create)":"Search models...",value:w,onChange:r(E=>k(E.target.value),"onChange"),autoFocus:!0}),w&&(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:r(()=>k(""),"onClick"),children:(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,t.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),f&&!w.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{B()},"onClick"),disabled:S,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,t.jsx)("path",{d:"M3 3v5h5"})]}),S?"Detecting...":h?v?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":v??"Detect from config"]}),x&&!w.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{x()},"onClick"),disabled:b,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M3 12a9 9 0 0 1 15.28-6.36L21 8"}),(0,t.jsx)("path",{d:"M21 3v5h-5"}),(0,t.jsx)("path",{d:"M21 12a9 9 0 0 1-15.28 6.36L3 16"}),(0,t.jsx)("path",{d:"M8 16H3v5"})]}),b?"Refreshing...":"Refresh models"]}),s&&(!e.some(E=>E.id===s)||A.has(s))&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:s,children:e.find(E=>E.id===s)?.label??s}),(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-green-500/15 text-green-400 border-green-500/20",children:"current"})]}),h&&h!==s&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(h),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:h,children:e.find(E=>E.id===h)?.label??h}),(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-blue-500/15 text-blue-400 border-blue-500/20",children:"detected"})]}),p?.filter(E=>E&&E!==h&&E!==s).map(E=>{const z=e.find($=>$.id===E);return(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(E),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:E,children:z?.label??E}),(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-sky-500/15 text-sky-400 border-sky-500/20",children:"config"})]},`detected-${E}`)}),(0,t.jsxs)("div",{className:"max-h-(--sz-240px) overflow-y-auto",children:[o&&(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!s&&"bg-accent"),onClick:r(()=>{n(""),i(!1)},"onClick"),children:"Default"}),T&&(0,t.jsxs)("button",{type:"button",className:"flex items-center justify-between gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:r(()=>{n(R),i(!1),k("")},"onClick"),children:[(0,t.jsx)("span",{children:"Use manual model"}),(0,t.jsx)("span",{className:"text-xs font-mono text-muted-foreground",children:R})]}),M.map(E=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[c&&(0,t.jsxs)("div",{className:"px-2 py-1 text-(length:--text-nano) uppercase tracking-wide text-muted-foreground",children:[E.provider," (",E.entries.length,")"]}),E.entries.map(z=>(0,t.jsx)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",z.id===s&&"bg-accent"),onClick:r(()=>{n(z.id),i(!1)},"onClick"),children:(0,t.jsx)("span",{className:"block w-full text-left truncate",title:z.id,children:c?$et(z.id):z.label})},z.id))]},E.provider)),D.length===0&&!T&&A.size===0&&(0,t.jsx)("div",{className:"px-2 py-2 space-y-2",children:(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:f?j??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r(UW,"ModelDropdown");function zat({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(Ss,{label:"Thinking effort",hint:Ni.thinkingEffort,children:(0,t.jsxs)(br,{open:a,onOpenChange:i,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:s.map(l=>(0,t.jsxs)("button",{className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",l.id===e&&"bg-accent"),onClick:r(()=>{n(l.id),i(!1)},"onClick"),children:[(0,t.jsx)("span",{children:l.label}),l.id?(0,t.jsx)("span",{className:"text-xs text-muted-foreground font-mono",children:l.id}):null]},l.id||"auto"))})]})})}r(zat,"ThinkingEffortDropdown");function VSe(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=Hpe.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=HR();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(VSe,"useAgentAppearanceDraft");var rC=null,H2=new Set,aC={subscribe(e){return H2.add(e),()=>{H2.delete(e)}},getSnapshot(){return rC},acquire(e){if(rC)return!1;rC=e;for(const s of H2)s();return!0},release(e){if(rC===e){rC=null;for(const s of H2)s()}}};function B_({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)(()=>TN(s??e?.appearance,e?.id),[s,e?.appearance,e?.id]),b=(0,m.useRef)(null),v=(0,m.useRef)(null),j=(0,m.useRef)(null),N=(0,m.useRef)(Symbol("agent-character")),w=(0,m.useSyncExternalStore)(aC.subscribe,aC.getSnapshot,()=>null),[k,S]=(0,m.useState)(!1),[C,I]=(0,m.useState)(!0),[R,T]=(0,m.useState)(!1),[A,D]=(0,m.useState)(!1),M=k&&!C&&!R&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const B=matchMedia("(prefers-reduced-motion: reduce)"),E=r(()=>I(B.matches),"change");E(),B.addEventListener("change",E);const z=new IntersectionObserver($=>S($[0]?.isIntersecting??!1));return b.current&&z.observe(b.current),()=>{z.disconnect(),B.removeEventListener("change",E)}},[]),(0,m.useEffect)(()=>{M&&w===null&&aC.acquire(N.current),M||aC.release(N.current)},[M,w]),(0,m.useEffect)(()=>()=>aC.release(N.current),[]),(0,m.useEffect)(()=>{if(!M||w!==N.current)return;let B=!1;return D(!1),Promise.all([Jc(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),Jc(()=>import("./definition-Doyo4Zr4.js"),__vite__mapDeps([2,3,1]))]).then(([E,z])=>{B||!v.current||(j.current=E.createCharacter(v.current,z.characterDefinition(x,i),{animation:z.animationId(a),trackingRegion:l?.current??b.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>T(!0),"onError")}),D(!0))}).catch(()=>{B||T(!0)}),()=>{B=!0,j.current?.destroy(),j.current=null,D(!1)}},[M,w,l,c,n,d,u]),(0,m.useEffect)(()=>{j.current&&Jc(()=>import("./definition-Doyo4Zr4.js").then(B=>{j.current?.setDefinition(B.characterDefinition(x,i)),j.current?.setAnimation(B.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,A]),(0,t.jsxs)("span",{ref:b,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:W("relative inline-block shrink-0",KFe[n],h),children:[(0,t.jsx)(gr,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:W("size-full",A&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(B_,"AgentCharacter");var qat=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function HSe(e,{cloud:s,nativeRunnerEnabled:n}){return e==="paperclip_runner"?n:s?qat.has(e):!0}r(HSe,"isNewAgentAdapterAllowed");var Uat={claude_local:{src:"/brands/claude-color.svg"},codex_local:{src:"/brands/codex-color.svg"},gemini_local:{src:"/brands/adapters/gemini-color.svg"},kimi_local:{src:"/brands/adapters/kimi-color-light.svg",dark:"/brands/adapters/kimi-color.svg"},...Object.fromEntries([["cursor","cursor"],["cursor_cloud","cursor"],["grok_local","grok"],["hermes_local","hermesagent"],["hermes_gateway","hermesagent"],["pi_local","pi"]].map(([e,s])=>[e,{src:`/brands/adapters/${s}.svg`,dark:`/brands/adapters/${s}-dark.svg`}]))};function KW({type:e,className:s="size-6"}){const n=Ch(e).icon,a=Uat[e];return a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("img",{src:a.src,className:W("shrink-0 object-contain",a.dark&&"dark:hidden",s),alt:""}),a.dark&&(0,t.jsx)("img",{src:a.dark,className:W("hidden shrink-0 object-contain dark:block",s),alt:""})]}):(0,t.jsx)(n,{className:s})}r(KW,"AdapterMark");function Kat(){const{selectedCompanyId:e}=ps(),{appearance:s}=VSe(`${e}:new-agent`);return(0,t.jsx)(B_,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(Kat,"AgentBasicsCharacter");function GSe({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!$c(),c=ee({queryKey:P.instance.experimentalSettings,queryFn:Nr.getExperimental,enabled:e,retry:!1}),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(a),[f,x]=(0,m.useState)("codex"),[b,v]=(0,m.useState)("name"),{data:j,isPending:N,error:w}=ee({queryKey:P.adapters.all,queryFn:uh.list,enabled:e}),k=(j??[]).filter(C=>C.loaded&&!C.disabled&&HSe(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Ch(C.type).comingSoon),S=k.some(C=>C.type===h);return(0,t.jsx)(Ys,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Js,{className:W("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",b==="name"&&"sm:max-w-(--sz-560px)"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 px-6 py-5 text-xs text-muted-foreground","aria-label":"New agent progress",children:[(0,t.jsx)("span",{className:W(b==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(En,{className:"size-3"}),(0,t.jsx)("span",{className:W(b==="adapter"&&"font-medium text-foreground"),children:"2. Adapter"})]}),(0,t.jsxs)("form",{className:"flex min-h-0 flex-col",onSubmit:r(C=>{C.preventDefault(),d.trim()&&(b==="name"?v("adapter"):S&&n({name:d.trim(),adapterType:h,runnerProvider:f}))},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex min-h-0 flex-col gap-7 overflow-y-auto px-6 pb-8 sm:px-10",children:[(0,t.jsxs)("div",{className:"flex flex-col items-center gap-4 text-center",children:[e&&(0,t.jsx)(Kat,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Xs,{className:"text-3xl font-semibold tracking-tight",children:b==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(jn,{className:"text-base",children:b==="name"?"Start with a name. Make them your own.":`How should ${d.trim()} work?`})]})]}),b==="name"?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{htmlFor:o,className:"text-sm font-medium",children:"Agent name"}),(0,t.jsx)(ht,{id:o,autoFocus:!0,maxLength:100,placeholder:"e.g. Darnold",value:d,onChange:r(C=>u(C.target.value),"onChange"),className:"h-12 text-base"}),i&&(0,t.jsx)(L,{type:"button",variant:"link",className:"px-0 text-muted-foreground",onClick:i,children:"Invite an external agent"})]}):(0,t.jsxs)("fieldset",{className:"space-y-4",children:[(0,t.jsx)("legend",{className:"sr-only",children:"Adapter"}),N&&(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading adapters…"}),w&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.message}),(0,t.jsx)("div",{className:W("grid grid-cols-2 gap-3",k.length!==4&&"sm:grid-cols-3"),children:k.map(C=>{const I=Ch(C.type);return(0,t.jsxs)("label",{className:"relative cursor-pointer",children:[(0,t.jsx)("input",{type:"radio",name:"new-agent-adapter",value:C.type,checked:h===C.type,onChange:r(()=>p(C.type),"onChange"),className:"peer sr-only"}),(0,t.jsxs)("span",{className:W("flex h-full flex-col items-center gap-2 rounded-lg border px-3 py-4 text-center peer-focus-visible:ring-2 peer-focus-visible:ring-ring hover:bg-accent/40",h===C.type?"border-foreground/40 bg-accent":"border-border bg-card"),children:[(0,t.jsx)(KW,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:I.label}),h===C.type&&(0,t.jsx)(gs,{className:"absolute right-2 top-2 size-3.5"})]})]},C.type)})}),S&&h==="paperclip_runner"&&(0,t.jsxs)("label",{className:"flex flex-col gap-2 text-sm font-medium",children:["Runner",(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:f,onChange:r(C=>x(C.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"codex",children:"Codex (app server)"}),(0,t.jsx)("option",{value:"claude",children:"Claude (ACPX)"}),(0,t.jsx)("option",{value:"grok",children:"Grok Build (ACPX)"}),(0,t.jsx)("option",{value:"opencode",children:"OpenCode"})]})]})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border px-6 py-4",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:r(()=>b==="name"?s():v("name"),"onClick"),children:b==="name"?"Cancel":(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Tl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)(L,{type:"submit",disabled:!d.trim()||b==="adapter"&&!S,children:[b==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(pl,{className:"size-4"})]})]})]})]})})}r(GSe,"AgentBasicsDialog");var Wat={subscription:"Subscription",api:"API"};function Vat({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)(aS,{initial:!1,mode:"sync",children:(0,t.jsx)(Il.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:xte},animate:{opacity:1,y:0,transition:fet},exit:{opacity:0,y:xte,transition:xet},children:Wat[e]},e)})})}r(Vat,"CredentialTag");function Hat({source:e,mode:s,selected:n,onSelect:a,buttonRef:i,settling:o}){return(0,t.jsxs)("button",{ref:i,type:"button",role:"radio","aria-checked":n,onClick:a,className:W("flex min-w-0 flex-1 cursor-pointer flex-col items-center gap-1.5 self-stretch rounded-md border p-3","transition-(--tp-border-color-background-color) ease-(--motion-ease-standard)",o?"duration-(--motion-duration-slow)":"duration-(--motion-duration-fast)","outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",n?"border-foreground/40 bg-accent":"border-border bg-card hover:bg-accent/40"),children:[(0,t.jsx)("span",{className:"flex size-(--sz-30px) shrink-0 items-center justify-center",children:e.icon}),(0,t.jsx)("span",{className:"text-(length:--text-compact) font-medium text-foreground",children:e.label}),(0,t.jsx)(Vat,{mode:s})]})}r(Hat,"ModelSourceTile");function QSe({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)(aS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Il.div,{layout:!0,transition:QNe,exit:{opacity:0,transition:_et},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(Hat,{source:h,mode:s,selected:h.id===n,onSelect:r(()=>a(h.id),"onSelect"),settling:l,buttonRef:r(p=>{p?c.current.set(h.id,p):c.current.delete(h.id)},"buttonRef")})},h.id))})})}r(QSe,"ModelSourceTiles");var H$={subscription:"Use API key instead",api:"Use subscription instead"},Gat={subscription:"api",api:"subscription"};function YSe({mode:e,onChange:s}){return(0,t.jsxs)("button",{type:"button",onClick:r(()=>s(Gat[e]),"onClick"),className:W("group grid cursor-pointer px-3 py-2 text-left text-sm font-medium","rounded-md outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)"),children:[Object.keys(H$).map(n=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:H$[n]},n)),(0,t.jsx)(aS,{initial:!1,mode:"sync",children:(0,t.jsx)(Il.span,{className:W("col-start-1 row-start-1 justify-self-start whitespace-nowrap","underline decoration-muted-foreground/40 underline-offset-4","text-muted-foreground transition-colors","group-hover:text-foreground group-hover:decoration-foreground/40"),initial:{opacity:0},animate:{opacity:1,transition:RW},exit:{opacity:0,transition:get},children:H$[e]},e)})]})}r(YSe,"CredentialModeLink");function JSe({onBack:e,primaryLabel:s,primaryDisabled:n,loading:a,loadingLabel:i,primaryIcon:o,onPrimary:l}){const c=a&&i?i:s,d=o??(a?"spinner":"arrow");return(0,t.jsxs)("div",{className:"flex items-center justify-between pt-9",children:[e?(0,t.jsxs)(L,{variant:"ghost",size:"lg",className:"rounded-full has-[>svg]:pl-4 has-[>svg]:pr-5",onClick:e,disabled:a,children:[(0,t.jsx)(Tl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Il.div,{layout:!0,transition:yet,className:"min-w-0",children:(0,t.jsx)(L,{size:"lg",className:"w-full rounded-full px-6",onClick:l,disabled:n||a,children:(0,t.jsxs)(Il.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:jet,children:[d==="spinner"?(0,t.jsx)(rt,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(pl,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(JSe,"FooterNav");function XSe({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onBack:l,testConnection:c,testError:d,managedAccount:u}){const h=ee({queryKey:P.health,queryFn:du.get,enabled:i}),p=i&&(h.data?.localAiLoginSupported??h.data?.deploymentMode==="local_trusted"),f=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{f.current++},[]);const x=r(()=>{f.current++,D(!1),N(!1),k(null),C("preparing")},"cancel"),[b,v]=(0,m.useState)(u?.initialMethod==="api_key"?"api":u?"subscription":null),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)("preparing"),I=(0,m.useRef)("ready"),[R,T]=(0,m.useState)(""),[A,D]=(0,m.useState)(!1),[M,B]=(0,m.useState)(null),[E,z]=(0,m.useState)(null),$=s==="claude_local"?"Claude":s==="grok_local"?"Grok":"OpenAI",q=s==="claude_local"?"ANTHROPIC_API_KEY":s==="grok_local"?"XAI_API_KEY":"OPENAI_API_KEY",U=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",O=CNe(e,q),K=u?{...O,options:[],subscriptions:[],loading:!1}:O,[H,Z]=(0,m.useState)(null),se=K.subscriptions.length?K.subscriptions.find(ge=>ge.id===(H??K.subscriptions[0]?.id)):void 0,[ne,fe]=(0,m.useState)(null),X=K.options.find(ge=>ge.id===(ne??K.options[0]?.id)),re=u?{...K.storedLogin,data:void 0,isPending:!1,isError:!1}:K.storedLogin,oe=(0,m.useRef)(null),G=b??(K.subscriptions.length>0||s==="claude_local"&&!se&&re.data?"subscription":K.options.length?"api":"subscription"),Y=G==="api"?"api_key":"subscription",Q=u?.intent.connectionId&&(u.fixedMethod!==!1||u.initialMethod===Y),te=u?{...u.intent,connectionId:Q?u.intent.connectionId:void 0,name:Q?u.intent.name:u.nameForMethod?.(Y)??u.intent.name}:void 0,ae=Kwe(e,te??{provider:U,method:"subscription",name:`My ${$} subscription`,ownership:"personal",agentIds:[],allAgents:!0},p&&G==="subscription"&&!se&&!re.data,{allowHostClaude:h.data?.deploymentMode==="local_trusted"}),le=ee({queryKey:P.agents.authSignal(e,s,n),queryFn:r(()=>$t.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!u});async function he(){if(A||u?.disabled)return;const ge=++f.current;D(!0),B(null);try{if(u&&te){if(G==="subscription"&&!p)return;const ue=oe.current??await(G==="api"?Yc.create(e,{...te,method:"api_key",apiKey:R.trim()}):ae.connect(te));oe.current=ue,T(""),ge===f.current&&u.onComplete({...ue,method:G==="api"?"api_key":"subscription"});return}let me=G==="api"?X?X.aiConnection?{env:{},aiConnection:X.aiConnection}:{env:{[q]:X.binding}}:E??{env:{},credentials:{[q]:R.trim()}}:{...se?.aiConnection?{aiConnection:se.aiConnection}:{},env:se?.binding?{CODEX_HOME:se.binding}:{},...s==="claude_local"&&!se&&re.data?{env:Vw(),applyStoredClaudeLogin:!0}:{}};if(G==="subscription"&&p&&!se&&!re.data&&(oe.current??=await ae.connect(),me={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}}),me.credentials&&(await Yc.create(e,{provider:U,method:"api_key",name:`My ${$} API`,ownership:"personal",apiKey:me.credentials[q],agentIds:[],allAgents:!0}),me={env:{},aiConnection:{provider:U,method:"api_key",mode:"responsible_user"}}),ge!==f.current)return;G==="api"&&(T(""),X||z(me));const ie=await c(me);if(ge!==f.current)return;ie?o(me):B("The provider did not respond. Check the connection and try again.")}catch(me){if(ge!==f.current)return;u&&T(""),B(me instanceof Error?me.message:"Could not connect to the provider.")}finally{ge===f.current&&D(!1)}}r(he,"connect");const ce=G==="subscription"&&a&&n&&!se&&!K.loading&&!re.data&&(!!u||le.data?.status!=="present"||H==="");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(QSe,{label:"Connect your model provider",sources:[{id:s,label:$,icon:(0,t.jsx)(KW,{type:s})}],mode:G,selectedId:j?s:null,collapsed:j,onSelect:r(()=>{u?.disabled||N(!0)},"onSelect")}),(!j||u)&&!u?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(YSe,{mode:G,onChange:r(ge=>{x(),N(j),oe.current=null,v(ge),T(""),z(null),B(null)},"onChange")})}),!j&&K.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[K.options.length," saved API"," ",K.options.length===1?"key available":"keys available","."]}),G==="subscription"&&K.subscriptions.length>0&&(0,t.jsx)(gk,{options:K.subscriptions,value:se?.id??"",onChange:Z,loading:!1,error:!1,kind:"subscription",disabled:A}),(0,t.jsx)(Il.div,{initial:!1,animate:{height:j?"auto":0,opacity:j?1:0},transition:{height:_d,opacity:r4},className:"overflow-hidden",children:j&&(0,t.jsx)("div",{className:"pt-5",children:G==="api"?(0,t.jsxs)(a4,{instruction:K.options.length?"Choose a saved API key or enter a new one":`Provide your ${$} API key to connect`,children:[(0,t.jsx)(gk,{...K,value:X?.id??"",disabled:A,onChange:r(ge=>{fe(ge),T(""),z(null),B(null)},"onChange")}),!X&&(0,t.jsx)(i4,{label:"API key",masked:!0,autoFocus:!0,value:R,placeholder:E?"Key entered. Retry the connection.":"Enter API key here",onChange:r(ge=>{fe(""),T(ge),z(null)},"onChange"),onSubmit:r(()=>{he()},"onSubmit"),disabled:A})]}):ce?(0,t.jsx)(qW,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:te??{provider:U,method:"subscription",name:`My ${$} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(ge=>{k(ge),C(me=>ge?me==="preparing"?"ready":me:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{I.current=S==="waiting"?"waiting":"ready",C("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{C(ge=>ge==="connecting"?I.current:ge)},"onSubmitFailed"),onConnected:r(ge=>{if(u){if(!ge){B("The login did not return a saved connection. Try again.");return}const ie=f.current;C("connecting"),Yc.loginResult(e,ge).then(ue=>{ie===f.current&&u.onComplete({...ue,method:"subscription"})}).catch(()=>{ie===f.current&&(C("ready"),B("Could not retrieve the saved connection. Go back and retry."))});return}const me={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}};z(me),o(me)},"onConnected")}):se?null:p&&!re.data?(0,t.jsx)(EW,{adapterType:s,login:{...ae,retry:r(()=>{B(null),ae.retry()},"retry")}}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:re.data?"Use your saved Claude subscription for this agent.":a?"Use the existing provider connection for this environment.":"This environment does not support browser sign-in. Choose a sign-in environment or connect with an API key."})})}),G==="subscription"&&re.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not check your saved Claude subscription. Try again."}),M&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:d??M}),i&&h.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not prepare sign-in. Reload this page to try again."}),(0,t.jsx)(JSe,{onBack:r(()=>{j?x():l()},"onBack"),primaryLabel:j&&ce?S==="waiting"?"Waiting for code":S==="connecting"?"Connecting":`Sign in to ${$}`:A?"Connecting":G==="subscription"&&(re.data||se)?"Use saved subscription":G==="api"&&X?"Use saved API key":"Connect",primaryDisabled:u?.disabled||!!u&&G==="subscription"&&!a&&!p||i&&h.isPending||ae.preparing||!!ae.error||!u&&le.isPending||K.loading||s==="claude_local"&&re.isPending||!j&&!(G==="subscription"&&se)||!!ce&&(!w||S!=="ready")||G==="api"&&!R.trim()&&!E&&!X,loading:A,primaryIcon:j&&ce?S==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(ce){if(!w||S!=="ready")return;window.open(w,"_blank","noreferrer,noopener"),C("waiting")}else he()},"onPrimary")})]})}r(XSe,"AgentProviderConnection");function L5(e){return e.provider==="openrouter"?(0,t.jsx)(Yat,{...e}):(0,t.jsx)(Qat,{...e})}r(L5,"AiConnectionCredentialStep");function Qat({companyId:e,provider:s,initialMethod:n,fixedMethod:a,connectionId:i,name:o,hideName:l,nameForMethod:c,ownership:d,agentIds:u,allAgents:h,environmentId:p,onComplete:f,onCancel:x}){const[b,v]=(0,m.useState)(o),[j,N]=(0,m.useState)(),w=Pt(),k=ee({queryKey:P.environments.list(e),queryFn:r(()=>Pi.list(e),"queryFn")}),S=ee({queryKey:P.environments.capabilities(e),queryFn:r(()=>Pi.capabilities(e),"queryFn")}),C=ee({queryKey:P.instance.settings,queryFn:Nr.get}),I=ee({queryKey:P.instance.experimentalSettings,queryFn:Nr.getExperimental}),R=ee({queryKey:P.instance.generalSettings,queryFn:Nr.getGeneral}),T=zW(R.data?.executionMode,k.data??[]);let A=null,D;try{A=T.forced?T.kubernetesEnvironment?.id??null:iN({agentDefaultEnvironmentId:p??j,instanceDefaultEnvironmentId:C.data?.defaultEnvironmentId,localDefaultEnvironmentId:lN(k.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:oN(k.data),visibleEnvironmentIds:k.data?.map(O=>O.id)})}catch(O){D=O instanceof Error?O.message:"Could not resolve the sign-in environment."}const M=(k.data??[]).filter(O=>O.status==="active"&&(O.driver==="local"||O.driver==="sandbox"&&typeof O.config.provider=="string"&&S.data?.sandboxProviders?.[O.config.provider]?.supportsLoginPty===!0));!T.forced&&!p&&!j&&!M.some(O=>O.id===A)&&(A=M[0]?.id??null);const B=k.data?.find(O=>O.id===A),E=typeof B?.config.provider=="string"?B.config.provider:"",z=B?.driver==="sandbox"&&S.data?.sandboxProviders?.[E]?.supportsLoginPty===!0,$=[k,S,C,I,R].some(O=>O.isPending),q=D??[k,S,C,I,R].find(O=>O.error)?.error?.message,U={provider:s,method:"subscription",name:b,ownership:d,agentIds:u,allAgents:h,connectionId:i};return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-6",children:[!l&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(ht,{value:b,onChange:r(O=>v(O.target.value),"onChange"),disabled:!!i})]}),!p&&!T.forced&&M.length>1&&(0,t.jsxs)($a,{value:A??"",onValueChange:N,children:[(0,t.jsx)(La,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Ma,{placeholder:"Sign-in environment"})}),(0,t.jsx)(Da,{children:M.map(O=>(0,t.jsx)(Nn,{value:O.id,children:O.name},O.id))})]}),q&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:q}),$?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(XSe,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:A,canLogin:z,localEnvironment:B?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:U,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:$||!!q||!b.trim(),onComplete:r(O=>{w.invalidateQueries({queryKey:["ai-connections",e]}),f(O)},"onComplete")}},A??"local")]})}r(Qat,"SubscriptionConnectionStep");function Yat({companyId:e,provider:s,connectionId:n,name:a,hideName:i,nameForMethod:o,ownership:l,agentIds:c,allAgents:d,onComplete:u,onCancel:h}){const[p,f]=(0,m.useState)(a),[x,b]=(0,m.useState)(""),v=Pt(),j=je({mutationFn:r(()=>Yc.create(e,{provider:s,method:"api_key",name:n?p:o?.("api_key")??p,ownership:l,agentIds:c,allAgents:d,connectionId:n,apiKey:x}),"mutationFn"),onSuccess:r(N=>{v.invalidateQueries({queryKey:["ai-connections",e]}),u({...N,method:"api_key"})},"onSuccess"),onSettled:r(()=>b(""),"onSettled")});return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-4",children:[!i&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(ht,{value:p,onChange:r(N=>f(N.target.value),"onChange"),disabled:!!n})]}),j.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error.message}),(0,t.jsx)(ZNe,{providerName:"OpenRouter",value:x,onChange:b,onSubmit:r(()=>j.mutate(),"onSubmit"),disabled:j.isPending,placeholder:"Enter API key here",autoFocus:!0}),(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)(L,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)(L,{disabled:!p.trim()||!x.trim()||j.isPending,onClick:r(()=>j.mutate(),"onClick"),children:j.isPending?"Connecting…":"Connect"})]})]})}r(Yat,"ApiKeyConnectionStep");var Jat=null;function oS(){const e=(0,m.useContext)(CI),{data:s,isFetched:n,isError:a}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:e!=null},e??(Jat??=new qN));return e?{enabled:!a&&s?.enableChatConnectors===!0,loaded:n}:{enabled:!1,loaded:!0}}r(oS,"useChatConnectorsEnabled");var Xat=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function ZSe(e){return e.replace(Xat,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(ZSe,"sanitizeProsumerCopy");var Zat={zapier:{tagline:"Reach 9,000+ apps your team already uses.",short:"Reach 9,000+ apps from your agents."},github:{tagline:"Read code and pull requests, comment on issues.",short:"Read code and pull requests, comment on issues."},slack:{tagline:"Send and read messages in your team's channels.",short:"Send and read messages in your channels."},notion:{tagline:"Read and update pages in your workspace.",short:"Read and update pages in your workspace."},railway:{tagline:"Inspect services, read logs, and manage deployments.",short:"Connect Railway for deployments, logs, and container access."},posthog:{tagline:"Explore product usage, errors, flags, and experiments.",short:"Sign in with PostHog. Project pinning and access controls are optional."},neon:{tagline:"Manage Postgres projects, branches, and queries.",short:"Sign in with Neon. Project pinning and read-only mode are optional."},linear:{tagline:"Create, update and read tickets.",short:"Create, update and read tickets."},"google-sheets":{tagline:"Read and update selected spreadsheets.",short:"Read spreadsheets or update the files you choose."},gmail:{tagline:"Read mail and create drafts for your review.",short:"Read mail and create drafts for your review."},"google-drive":{tagline:"Find, read, and create files in Drive.",short:"Find, read, and create files in Drive."},"google-docs":{tagline:"Read and update documents.",short:"Read and update documents."},"google-slides":{tagline:"Read and update presentations.",short:"Read and update presentations."},"google-calendar":{tagline:"Review calendars and manage events.",short:"Review calendars and manage events."},"google-chat":{tagline:"Read conversations and send messages.",short:"Read conversations and send messages."},"google-people":{tagline:"Look up contacts and people in your directory.",short:"Look up contacts and people in your directory."},"google-workspace-search":{tagline:"Search across your Google workspace.",short:"Search across your Google workspace."},hubspot:{tagline:"Look up contacts and update deal stages.",short:"Look up contacts and update deal stages."},intercom:{tagline:"Read and reply to customer conversations.",short:"Read and reply to customer conversations."},figma:{tagline:"Read files and post comments on frames.",short:"Read files and post comments on frames."},stripe:{tagline:"Read customers, invoices, and payouts.",short:"Read customers, invoices, and payouts."},context7:{tagline:"Look up up-to-date docs for your libraries.",short:"Look up up-to-date docs for your libraries."}},eit={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function eCe(e,s){const n=Zat[e];if(n)return n;if(s){const a=ZSe(s);if(a)return{tagline:a,short:a}}return eit}r(eCe,"appCopyFor");function tse(e,s,n){return n<=1?`Your ${e} key`:ZSe(s)||`Your ${e} key`}r(tse,"credentialFieldLabel");var tit=1500;function Cp(e=tit){const[s,n]=(0,m.useState)("idle"),a=(0,m.useRef)(null),i=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const o=(0,m.useCallback)(async l=>{const c=++i.current;let d="copied";try{await fa(l)}catch{d="failed"}return i.current!==c||(n(d),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{i.current===c&&(n("idle"),a.current=null)},e)),d},[e]);return{status:s,copied:s==="copied",failed:s==="failed",copy:o}}r(Cp,"useCopyAction");function WW(){const e=Xc()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await fa(s),e?.({title:n,tone:"success",dedupeKey:`copy:${n}`}),!0}catch{return e?.({title:"Couldn’t copy to clipboard",body:"Select and copy the value manually.",tone:"error",dedupeKey:"copy-failed"}),!1}},[e])}r(WW,"useCopyToast");var sit="/cloud/connections/handoff",nit="/cloud/connections/reauth",$5="paperclip.cloud-oauth-handoff.v1",ng=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function VW(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new ng("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 ng("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(VW,"parseHandoff");function rit(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new ng("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new ng("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new ng("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(rit,"handoffFailure");async function ait(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(sit,{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 ng(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(ait,"postCloudHandoff");function iit(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!==nit||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(iit,"exactReauthenticationTarget");async function dN(e,s={}){const n=VW(e.handoff);if(!n){const l=d5(e.authorizationUrl);if(!l.ok)throw new ng(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await ait(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=iit(i.reauthenticationUrl,n.session);if(l)return l}throw rit(a.status,i?.error)}const o=d5(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new ng("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(dN,"prepareOAuthNavigation");function z_(e,s=window.sessionStorage){const n=VW({kind:"paperclip_cloud",session:e});if(!n)throw new ng("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem($5,JSON.stringify(a))}r(z_,"savePendingCloudHandoff");function oit(e=window.sessionStorage){const s=e.getItem($5);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 VW({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem($5),null}}r(oit,"readPendingCloudHandoff");function sse(e=window.sessionStorage){e.removeItem($5)}r(sse,"clearPendingCloudHandoff");function u4(e){return!!(e&&Vpe({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(u4,"appSupportsToolCatalogSetup");var lit=TLe.filter(e=>Upe(e).some(s=>rp(s))).map(e=>e.slug);function cit(e){return lit.some(s=>s===e)}r(cit,"isMcpDirectOAuthConnectSlug");function q_(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(q_,"appSourceConnectHref");function dit(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(dit,"appSourceResumeHref");function G$(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(G$,"vercelConnectSourceHref");function uit(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(uit,"resolveAppsConnectRouteKey");function mit(e,{chatConnectorsEnabled:s=!1}={}){if(e.get("byo")==="1")return!!(e.get("reconnect")?.trim()&&e.get("applicationId")?.trim()&&e.get("link")?.trim());const n=e.get("source")??"";if(/^ai-router-(?:[a-f0-9]{2})+$/.test(n))return!0;const a=RN(n);return!s&&a?.methods.some(i=>i.transport==="chat_sdk")&&!a.methods.some(i=>(i.purpose??"tool")!=="channel"&&i.transport!=="chat_sdk")?!1:SI(n)&&e.get("reconnect")?.trim()?!0:n==="agentmail"||s?Vpe(a):u4(a)}r(mit,"canEnterAppsConnect");var Q$=" for the organization",hit=" for the company";function nse(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(Q$)?n:a.endsWith(hit)?`${n.slice(0,n.length-16).trimEnd()}${Q$}`:`${n}${Q$}`}r(nse,"connectionNameForGrantKind");function pit(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(pit,"grantStatusLabel");function fit(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(fit,"grantStatusTone");function xit(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(xit,"grantAccountLabel");function git(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(git,"audienceUserIds");function bit(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(bit,"organizationGrant");function vit(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(vit,"personalGrantFor");function yit(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(yit,"memberLabel");var rse=0;function l6(){return rse+=1,{id:`header-${rse}`,name:"",value:""}}r(l6,"newCustomHeaderRow");function D1(e){try{return new URL(e).host||null}catch{return null}}r(D1,"endpointHost");function tCe(e=window.location.origin){const s=new URL("/api/tools/oauth/callback",e),n=s.hostname.toLowerCase().replace(/^\[|\]$/g,"");return s.protocol==="http:"&&(n==="127.0.0.1"||n==="::1")&&(s.hostname="localhost"),s.toString()}r(tCe,"oauthCallbackUrlForBrowser");function Y$(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(Y$,"defaultGenericMcpName");function ase(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(ase,"genericConnectGuidance");function sCe(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=ZLe(a);if(!i.ok)return OJ(a,i.reason);const o=r$e(n.value);if(!o.ok)return OJ(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(sCe,"customHeaderError");function jit(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(jit,"genericConnectPayload");function wit(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&&sCe(e.headers)===null:!0:!1}r(wit,"canSubmitGenericConnect");function uN(e){const s=new Set;let n=!1;for(const a of e??[])a.targetType==="company"?n=!0:a.targetType==="agent"&&s.add(a.targetId);return{onAll:n,agentIds:s}}r(uN,"installStateFrom");function nCe(e,s){return e.onAll||e.agentIds.has(s)}r(nCe,"isAgentInstalled");function rCe(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(rCe,"installPayload");var kit="Has access — tick to load its tools into this agent's context.";function aCe(e){return`paperclip.connector-enrollment-access:${e}`}r(aCe,"enrollmentAccessStorageKey");function Nit(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(Nit,"validEnrollmentAccessState");function Sit(e,s,n){try{window.sessionStorage.setItem(aCe(s),JSON.stringify({...n,companyId:e}))}catch{}}r(Sit,"saveEnrollmentAccessState");function Cit(e){const s=aCe(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Nit(a)?a:null}catch{return null}}r(Cit,"consumeEnrollmentAccessState");function ise(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(ise,"githubRecoveryUrl");function ose(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(ose,"oauthCallbackErrorMessage");var _it={key:"setup",success:"complete"};function lse(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(lse,"requestedConnectionInitialStep");function Iit(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return xg(n)!==e.requestedAppKey?null:SI(e.requestedAppKey)}r(Iit,"requestedConnectionEntry");function Ait(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?xg(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(Ait,"retainedReconnectMatches");function Tit(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(Tit,"isVercelConnectUnavailable");function Rit(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(Rit,"isConnectionDefinitionUnavailable");function Eit(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(Eit,"requestedConnectionSetupResolution");function cse(e,s,n,a){const i=_it[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(cse,"appConnectHref");function G2(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(G2,"withConnectionIntent");var dse=["Pick app","Add your key"],use={gallery:0,key:1},Pit={key:0},Mit=["Add MCP URL"],Dit=["Sign in"];function J$(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(J$,"defaultGrantKindFor");function Lit(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(Lit,"configuredAgentIdentity");function QC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(QC,"isGoogleSheetsRobotMethod");function iC(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(iC,"defaultMethodConfig");function Aw(e,s){if(!e)return[];const n=pA(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(Aw,"connectionMethodsForCredentialSource");function pA(e){return Upe(e).filter(s=>(s.purpose??"tool")!=="channel")}r(pA,"availableToolConnectionMethods");function Q2(e,s){const n=pA(e);return s?n.find(a=>a.key===s)??null:i7(n)}r(Q2,"availableToolConnectionMethod");function vk(e){return i7(e)}r(vk,"recommendedSetupConnectionMethod");function mse(e){return vk(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(mse,"recommendedManagedConnectorMethod");function hse(e){if(!e)return!1;const s=pA(e),n=s.length===1?s[0]:null;return!!(n&&rp(n)&&!M$e(n))}r(hse,"canUseAutomaticOAuthFastPath");function pse(e){if(!e)return null;const s=pA(e),n=s.length===1?s[0]:null;return n&&rp(n)?n:null}r(pse,"automaticOAuthMethod");function $it(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r($it,"appSourceSlug");function Oit(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(Oit,"connectionSourceSlug");function fse(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&$it(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)||Oit(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(fse,"reusableOAuthConnection");function iCe(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(iCe,"readConnectionIntentOAuthOutcome");function m4(e={}){const[s]=fi(),n=va(),{selectedCompanyId:a}=ps(),i=G9(),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&&j1(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||j1(l)||K3(l))),h=ee({queryKey:["tools","connection",d],queryFn:r(()=>Zt.getConnection(d),"queryFn"),enabled:u}),p=l||h.data?.config?.sourceTemplateKey,f=s.get("method")||h.data?.config?.connectionMethodKey;if(u&&h.isPending)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection…"});if(u&&h.isError)return(0,t.jsxs)("div",{role:"alert",className:"space-y-3 p-6",children:[(0,t.jsx)("p",{children:"Could not load this connection. Your saved access and credentials have not changed."}),(0,t.jsx)(L,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(K3(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"&&j1(p)&&(!f||GR(p,f))){const x=sfe(p,s.get("targetToolkit"));return(0,t.jsx)(hGe,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(Fit,{...e})}r(m4,"ConnectionSetupFlow");function Fit({additionalSettings:e,connectionSettings:s,additionalSettingsValid:n=!0,byoOnly:a=!1,credentialSource:i="paperclip_vault",host:o="page",serviceSlug:l,requestedAgentId:c,interactionId:d,forceNewConnection:u=!1,existingConnections:h=[],configuredConnection:p,onUseExisting:f,onComplete:x,onOAuthDeclined:b,aiConnection:v,onPhaseChange:j,onCancel:N,renderCredentialStep:w}={}){const k=Pt(),S=Mn(),C=(0,m.useCallback)((bt,_e)=>{o==="page"&&(_e?S(bt,_e):S(bt))},[o,S]),I=va(),{selectedCompany:R,selectedCompanyId:T}=ps(),{enabled:A}=oS(),{enabled:D}=G9(),{setBreadcrumbs:M}=Bn(),{pushToast:B}=xi(),[E]=fi(),z=d?.trim()||E.get("intent")?.trim()||null,$=I.appKey??E.get("appKey")??void 0,q=E.get("source")?.trim()||null,U=u||E.get("new")==="1",O=E.get("stage")?.trim()||null,K=E.get("method")?.trim()||null,H=E.get("resume")?.trim()||null,Z=E.get("oauth"),se=E.get("code"),ne=ise(E.get("installation_url")),fe=ise(E.get("management_url")),X=p?.id??(E.get("reconnect")?.trim()||null),re=E.get("identity")==="user"?"user":E.get("identity")==="organization"?"organization":null,oe=i==="vercel_connect",G=l??q,Y=i==="paperclip_vault"&&cit(G)?G:null,Q=uit({serviceSlug:l,appKey:$,sourceSlug:q}),te=(l??q??$)==="zapier",ae=te?void 0:Q,le=!!p||o==="page"&&(a||E.get("byo")==="1"),[he]=(0,m.useState)(()=>o==="page"&&E.get("cloud_connector")==="enrolled"&&ae?Cit(ae):null),[ce]=(0,m.useState)(()=>{const bt=E.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(bt)?bt:"",name:p?.name??E.get("name")?.trim()??"",applicationId:p?.applicationId??(E.get("applicationId")?.trim()||void 0)}}),[ge,me]=(0,m.useState)(()=>lse({requestedAppKey:ae,routeStage:O,resumeConnectionId:H,hasPrefilledLink:!!ce.link,zapierSource:te})),[ie,ue]=(0,m.useState)(null),[ke,be]=(0,m.useState)(""),[Ie,Ue]=(0,m.useState)(ce.link),[at,dt]=(0,m.useState)(ce.name||(te?"Zapier":"")),[de,Be]=(0,m.useState)(!1),[pt,vt]=(0,m.useState)(""),[Le,Qe]=(0,m.useState)("auto"),[ut,Ye]=(0,m.useState)(()=>[l6()]),[it,kt]=(0,m.useState)(""),[tt,Pe]=(0,m.useState)(""),[Ce,He]=(0,m.useState)(!1),[Je,lt]=(0,m.useState)(null),[Ee,Xe]=(0,m.useState)(!1),[Ae,De]=(0,m.useState)({}),[_t,ye]=(0,m.useState)(""),[gt,We]=(0,m.useState)(""),[Ot,zt]=(0,m.useState)(""),[Cs,ze]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[ft,Ut]=(0,m.useState)(null),[Ns,Is]=(0,m.useState)({}),[Ct,ds]=(0,m.useState)(""),[$e,xe]=(0,m.useState)(null),[Qt,Dt]=(0,m.useState)(null),[rs,ws]=(0,m.useState)({}),[Bs,er]=(0,m.useState)("all"),[Fe,st]=(0,m.useState)(new Set),[xt,Oe]=(0,m.useState)(()=>new Set(he?.agentIds??(c?[c]:[]))),[Bt,wt]=(0,m.useState)(he?.grantKind??re??(c?"user":"organization")),[Xt,Yt]=(0,m.useState)(he?.installChoice??(c?"specific":"all")),hs=!!(H&&(Z==="failed"||Z==="denied")),[Ts,as]=(0,m.useState)(hs?"error":"entry"),[Zn,en]=(0,m.useState)(()=>hs?ose(Z,se):null),[nr,tn]=(0,m.useState)(null),xn=(0,m.useRef)(!1),Ht=(0,m.useRef)(!1),qs=(0,m.useRef)(null),Vs=(0,m.useRef)(null),[Lt,is]=(0,m.useState)(null),Ms=(0,m.useRef)(null),[bs,gn]=(0,m.useState)(null),[Pn,$r]=(0,m.useState)(null),mt=(0,m.useRef)(null),[vs,Fs]=(0,m.useState)(h.length>0&&!!f),[Hs,zs]=(0,m.useState)(null),[Us,ur]=(0,m.useState)(null),[Dn,Er]=(0,m.useState)(null),Jn=(0,m.useCallback)(()=>{o!=="dialog"||Ms.current?.closed===!1||(Ms.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),tr=(0,m.useCallback)(bt=>{if(o!=="dialog"){Lm(bt);return}$r(bt);const _e=Ms.current;if(!_e||_e.closed){as("error"),en("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),j?.("needs_retry");return}_e.location.assign(bt),_e.focus()},[o,j]),pn=(0,m.useCallback)(()=>{Ms.current=null,en(null),as("redirecting"),j?.("authorizing")},[j]);(0,m.useEffect)(()=>{if(o!=="dialog"||Ts!=="redirecting")return;const bt=window.setInterval(()=>{Ms.current?.closed&&(as("error"),en("The sign-in window closed. If authorization did not finish, try again."),$r(null),j?.("needs_retry"))},1e3);return()=>window.clearInterval(bt)},[o,Ts,j]);const yt=(0,m.useCallback)(async bt=>{mt.current?.abort();const _e=new AbortController;mt.current=_e;try{const ot=await dN(bt,{signal:_e.signal});if(ot.kind==="reauthentication"){const Nt=o==="dialog"?Ms.current:window;if(!Nt||Nt.closed||!bt.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");z_(bt.handoff.session,Nt.sessionStorage),as("starting")}else tn(ot.host),as("redirecting");tr(ot.url)}catch(ot){if(_e.signal.aborted)return;as("error"),en(ot instanceof Error?ot.message:"Paperclip couldn’t start secure sign-in. Try again."),j?.("needs_retry")}finally{mt.current===_e&&(mt.current=null)}},[o,j,tr]);(0,m.useEffect)(()=>()=>mt.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!z)return;const bt=r(_e=>{const ot=iCe(_e,window.location.origin,z);if(ot==="connected"){as("entry"),$r(null),x?.({resolvedByCallback:!0});return}if(ot==="declined"){as("error"),en("Authorization was cancelled. You can try again."),j?.("needs_retry");return}ot==="failed"&&(as("error"),en("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",bt),()=>window.removeEventListener("message",bt)},[z,o,x,b]),(0,m.useEffect)(()=>{if(o!=="dialog"||z||!bs)return;let bt=!1,_e=!1;const ot=window.setInterval(async()=>{if(_e||bt)return;const Nt=Ms.current;if(!Nt||Nt.closed){gn(null),as("error"),en("The sign-in window closed. Try again to finish connecting GitHub.");return}let us;try{us=new URL(Nt.location.href)}catch{return}if(!(us.origin!==window.location.origin||!us.pathname.includes(bs))){if(us.searchParams.has("oauth")){gn(null),as("error"),en("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(us.searchParams.get("success")==="1"){_e=!0;try{const Ls=await Zt.getConnection(bs);!bt&&Ls.status==="active"&&(gn(null),Nt.close(),x?.({connectionId:Ls.id}))}catch{bt||(gn(null),as("error"),en("Could not confirm the connection. Try again."))}finally{_e=!1}}}},1e3);return()=>{bt=!0,window.clearInterval(ot)}},[z,bs,o,x]);const Ps=r(()=>{Qe("auto"),Ye([l6()]),kt(""),Pe(""),He(!1),lt(null),Xe(!1)},"resetGenericAuthState"),Zs=r(bt=>{if(o==="page"&&!z&&i==="paperclip_vault"&&j1(bt.slug)){C(`/apps/connect?source=${bt.slug}`);return}if(bt.slug==="zapier"){ue(null),be(""),Ue(""),dt("Zapier"),Be(!1),vt(""),Ps(),De({}),Dt(null),me("key"),C(G2("/apps/connect?source=zapier",z));return}if(i==="paperclip_vault"&&hse(bt)){C(q_(bt.slug,z));return}ue(bt),be(bt.name),Ue(""),dt(""),Be(!1),vt(""),Ps(),De({}),ye(""),We(""),zt("");const _e=vk(Aw(bt,i));ze(_e?.key??""),Is(iC(_e)),ds(""),xe(null),Dt(null),Oe(new Set(c?[c]:[])),Yt(c?"specific":"all"),wt(Br??J$(_e,!!c)),me("key"),C(i==="vercel_connect"?G2(G$(bt.slug),z):q_(bt.slug,z))},"useMatchedGalleryEntry"),Ze=r(()=>{me("gallery"),C(G2(i==="vercel_connect"?G$():a?"/apps/byo":"/apps",z))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return M([{label:"Connectors",href:"/apps"},{label:oe?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>M([])},[a,o,M,oe]);const At=ee({queryKey:P.apps.gallery(T??"__none__"),queryFn:r(()=>Zt.listGallery(T),"queryFn"),select:(0,m.useCallback)(bt=>z?{...bt,apps:bt.apps.map(_e=>({..._e,methods:_e.methods.filter(ot=>v?ot.ai?.provider===v.provider&&(v.mode==="responsible_user"||ot.ai.method===v.method):ot.transport!=="runtime_auth")})).filter(_e=>_e.methods.length>0)}:bt,[z,v?.provider,v?.method,v?.mode]),enabled:!!T}),fs=(0,m.useMemo)(()=>(At.data?.apps??[]).filter(bt=>D||!K3(bt.slug)).filter(bt=>bt.slug==="agentmail"||A||!bt.methods.some(_e=>_e.transport==="chat_sdk")||u4(bt)),[At.data,A,D]),Ks=ae?SI(ae):null,Ln=Ks?.methods.find(bt=>nk(bt)&&!rp(bt)),Cr=!(Ln&&Cs===Ln.key)&&!!Ks?.methods.some(bt=>bt.oauthStrategy==="paperclip_cloud_connector"||bt.oauthStrategy==="paperclip_id_connector"),Vr=!!ie?.methods.some(bt=>bt.oauthStrategy==="paperclip_cloud_connector"||bt.oauthStrategy==="paperclip_id_connector"),Pr=ie&&Cr&&!Vr?mse(Ks):null,[Ar,_r]=(0,m.useState)(null),jr=ee({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>Zt.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Ar?2e3:!1,enabled:!!(T&&Cr&&!Vr)}),[sr,Ga]=(0,m.useState)(null),ka=(0,m.useCallback)(()=>{Ms.current?.close(),Ms.current=null,_r(null)},[]),Ds=(0,m.useCallback)(()=>{!T||!ae||Sit(T,ae,{grantKind:Bt,installChoice:Xt,agentIds:Xt==="specific"?[...xt]:[]})},[Bt,xt,Xt,ae,T]),$n=(0,m.useCallback)(bt=>{const _e=d5(bt);if(!_e.ok){ka(),Ga(_e.message);return}if(o==="dialog"){_r(_e.url);const ot=Ms.current;ot&&!ot.closed?(ot.location.assign(_e.url),ot.focus()):Ga("Open authorization in a new tab to continue.");return}Lm(_e.url)},[o,ka]);(0,m.useEffect)(()=>{!Ar||jr.data?.status!=="active"||(ka(),Ga(null),At.refetch())},[Ar,jr.data?.status,At.refetch,ka]);const mr=je({mutationFn:r(()=>Zt.startCloudConnectorEnrollment(T,R?.name,ae?cse(ae,"key",i,{resumeConnectionId:H,reconnectConnectionId:X,interactionId:z})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(bt=>{if(!bt.verificationUrl){ka(),Ga("Paperclip Cloud did not return an enrollment link. Try again.");return}$n(bt.verificationUrl)},"onSuccess"),onError:r(bt=>{ka(),Ga(bt instanceof Error?bt.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),_n=ee({queryKey:P.tools.applications(T??"__none__"),queryFn:r(()=>Zt.listApplications(T),"queryFn"),enabled:!!T&&(!!Y||!!H||!!X),refetchOnMount:"always"}),on=ee({queryKey:P.tools.connections(T??"__none__"),queryFn:r(()=>Zt.listConnections(T),"queryFn"),enabled:!!T&&(!!Y||!!H||!!X),refetchOnMount:"always"}),Hr=(0,m.useMemo)(()=>u?null:fse(Y,_n.data?.applications??[],on.data?.connections??[],U?{applicationId:ce.applicationId,draftOnly:!0}:{}),[_n.data,on.data,U,Y,ce.applicationId,u]),ss=(0,m.useMemo)(()=>X?(on.data?.connections??[]).find(bt=>bt.id===X)??null:null,[on.data,X]),Hn=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!on.isFetchedAfterMount||!ss||Hn.current===ss.id)return;const bt=ss.config?.url??ss.transportConfig?.url??ss.transportConfig?.serverUrl??ss.config?.serverUrl;typeof bt!="string"||!/^https?:\/\//i.test(bt)||(Hn.current=ss.id,Ue(_e=>_e||bt))},[p,on.isFetchedAfterMount,ss]);const Gn=(0,m.useMemo)(()=>ss?(_n.data?.applications??[]).find(bt=>bt.id===ss.applicationId)??null:null,[_n.data,ss]),un=Ait({requestedAppKey:ae,byo:le,applicationId:ce.applicationId,reconnectConnection:ss,reconnectApplication:Gn}),Kn=(0,m.useMemo)(()=>H?(on.data?.connections??[]).find(bt=>bt.id===H)??null:null,[on.data,H]),Lr=Kn??ss,Br=Lr?Lr.credentialPolicy==="per_user"?"user":Lr.credentialPolicy==="per_agent"?"agent":"organization":re,Se=Kn?.authKind==="oauth"?Kn:Hr,Jt=Hr?Hr.credentialPolicy==="per_user"?"user":Hr.credentialPolicy==="per_agent"?"agent":"organization":null,ln=Br??Jt;(0,m.useEffect)(()=>{ln&&wt(ln)},[ln]);const rr=(0,m.useMemo)(()=>Ie&&!ie?w3(Ie,fs):null,[ie,fs,Ie]),ra=ie?Q2(ie,Cs||null):null,Ea=ra&&rp(ra)?ra:pse(ie),os=i==="paperclip_vault"&&Ea?ie:null,Re=i==="paperclip_vault"&&hse(ie)?ie:null,Kt=!!Y&&(!_n.isFetchedAfterMount||!on.isFetchedAfterMount),Vt=r(bt=>{me(bt),ie&&C(cse(ie.slug,bt,i,{connectionMethodKey:ie.methods.find(_e=>_e.key===Cs)?.ai?Cs:void 0,resumeConnectionId:H,reconnectConnectionId:X,interactionId:z}))},"setAppStep"),fn=Kn??ss??Se,an=ie?.agentInstructions,ar=ie&&an?ft?.slug===ie.slug?ft.value:fn?fn.agentInstructions??{...Kk(an),enabled:!1}:Kk(an):null,Mr=!ar||!!ar.text.trim(),qt=je({mutationFn:r(async bt=>(ar&&JSON.stringify(ar)!==JSON.stringify(bt.agentInstructions)&&await Zt.updateConnection(bt.id,{agentInstructions:ar}),Zt.startOAuth(bt.id,{asCurrentUser:bt.credentialPolicy==="per_user",...bt.credentialPolicy==="per_agent"?{asAgentId:Lit(bt)??[...xt][0]}:{},...z?{interactionId:z}:{}})),"mutationFn"),onSuccess:r(bt=>{yt(bt)},"onSuccess"),onError:r(bt=>{const _e=bt instanceof dn&&bt.body&&typeof bt.body=="object"?bt.body.details:null;as("error"),j?.("needs_retry"),en(_e?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":bt instanceof Error?bt.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),cs=qt.mutate,In=(0,m.useCallback)(bt=>{j?.("authorizing"),Jn(),o==="dialog"&&!z&&gn(bt.id),cs(bt)},[cs,j,Jn,o,z]),wr=r(async bt=>{if(c)return;const _e=rCe(T,(ln??Bt)!=="agent"&&Xt==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:xt});await Zt.putConnectionInstalls(bt,_e)},"applyAccessInstalls"),wn=ln??Bt,ya=je({mutationFn:r(async bt=>{const _e=bt??ie;let ot;if(_e){const Nt=ln??Bt,us=Q2(_e,Cs||null),Ls=QC(_e,us)?mq(Ct).ids:[],Na=ke.trim(),ta=nse(Na||_e.name,Nt);ot=await Zt.connectApp(T,{galleryKey:_e.slug,...ar?{agentInstructions:ar}:{},...Cs?{connectionMethodKey:Cs}:{},name:ta,credentialSource:i,...i==="paperclip_vault"?{credentialValues:Ae}:{},...i==="vercel_connect"?{vercelConnect:{connector:Ot.trim()}}:{},..._t.trim()?{oauthClient:{clientId:_t.trim(),...gt?{clientSecret:gt}:{}}}:{},configValues:QC(_e,us)?{allowedSpreadsheetIds:Ls}:Object.keys(Ns).length>0?Ns:void 0,applicationId:ce.applicationId,...H??qs.current?{resumeConnectionId:H??qs.current}:X?{reconnectConnectionId:X}:{},...Nt!=="organization"?{grantKind:Nt}:{},...Nt==="agent"?{subjectAgentId:[...xt][0]}:{}}),qs.current=null}else{const Nt=jit({link:Ie,name:at,authMode:Le,needsKey:de,keyValue:pt,headers:ut,oauthClientId:it,oauthClientSecret:tt}),us=nse(Nt.name??Y$(Ie)??"Custom app",wn);ot=await Zt.connectApp(T,{...Nt,...X?{reconnectConnectionId:X}:{},...te||rr?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:us,applicationId:ce.applicationId,...wn!=="organization"?{grantKind:wn}:{},...wn==="agent"?{subjectAgentId:[...xt][0]}:{}})}return ot.auth?.kind==="oauth"&&!H&&!X&&await wr(ot.connectionId),ot},"mutationFn"),onSuccess:r(bt=>{if(bt.auth?.kind==="oauth"){if(Dt(bt),bt.auth.manualClientRequired){lt(ase("oauth_manual_client_required",null)),Qe("oauth"),He(!0),Xe(!1);return}if(o==="dialog"||z){as("starting"),Xe(!ie),In(bt.connection);return}const ot=bt.auth.startUrl?.trim();if(!ot){as("starting"),Xe(!0),In(bt.connection);return}Xe(!0),yt({authorizationUrl:ot,handoff:bt.auth.handoff});return}lt(null),Dt(bt);const _e={};for(const ot of bt.actions.readOnly)_e[ot.catalogEntryId]=!0;for(const ot of bt.actions.canMakeChanges)_e[ot.catalogEntryId]=!0;ws(_e),to.mutate({result:bt,enabled:_e})},"onSuccess"),onError:r(bt=>{const _e=bt instanceof dn&&bt.body&&typeof bt.body=="object"?bt.body.details:null;if(os){as("error"),j?.("needs_retry"),en(_e?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":bt instanceof Error?bt.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!ie&&Ie){const ot=typeof _e?.code=="string"?_e.code:null,Nt=ase(ot,bt instanceof Error?bt.message:null);lt(Nt),Xe(!1),Nt.focus==="credentials"&&(Be(!0),He(!0));return}B({title:"Couldn’t connect",body:bt instanceof Error?bt.message:"Please check your key and try again.",tone:"error"})},"onError")}),vr=ya.mutate,Wi=(0,m.useCallback)(bt=>{const _e=bt??ie;(_e?Q2(_e,Cs||null):null)?.auth==="oauth"&&Jn(),vr(bt)},[Cs,ie,vr,Jn]);(0,m.useEffect)(()=>{if(!ae||At.isLoading||!At.data||X&&(!on.isFetchedAfterMount||!_n.isFetchedAfterMount))return;const bt=Iit({requestedAppKey:ae,galleryApps:At.data.apps,reconnectConnection:ss,applications:_n.data?.applications??[]}),_e=!!bt?.methods.some(ir=>ir.oauthStrategy==="paperclip_cloud_connector"||ir.oauthStrategy==="paperclip_id_connector");if(Cr&&!_e&&jr.isLoading)return;const ot=Aw(bt,i),Nt=v??(ss?.connectionPurpose==="ai"?FJ.safeParse(ss.config?.ai).data:void 0),us=ot.find(ir=>Nt?ir.ai?.provider===Nt.provider&&(!("mode"in Nt)||Nt.mode!=="responsible_user")&&ir.ai.method===Nt.method:ir.key===K)??(Cr&&!_e?mse(Ks):null)??vk(ot),Ls=ot.length===1?ot[0]:null,Na=i==="paperclip_vault"&&!!pse(bt),ta=Tit({credentialSource:i,available:At.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(X&&un)}),zr=ot.length===1&&Ls?.auth==="oauth"&&!rp(Ls)&&!nk(Ls),Sa=Rit({available:bt?.availability?.available,reconnectConnectionId:X,reconnectSourceMatches:un}),Ei=Eit({reconnectConnectionId:X,hasRequestedEntry:!!bt,supportedMethodCount:ot.length,unsupportedOAuth:zr,vercelUnavailable:ta,definitionUnavailable:Sa});if(Ei!=="ready"){if(ue(null),me("gallery"),Ei==="reconnect_unavailable"&&X){Er(X);return}C(G2(i==="vercel_connect"?G$():"/apps/connect",z),{replace:!0});return}if(Er(null),!!bt){if(ie?.slug!==bt.slug){ue(bt),be(bt.name),Ue(""),dt(""),Be(!1),vt(""),De({}),ye(""),We(""),zt(""),ze(us?.key??""),Is(iC(us)),ds(""),xe(null),Dt(null);const ir=he?.companyId===T?he:null;wt(Br??ir?.grantKind??J$(us,!!c)),Oe(new Set(ir?.agentIds??(c?[c]:[]))),Yt(ir?.installChoice??(c?"specific":"all")),me(lse({requestedAppKey:ae,routeStage:O,resumeConnectionId:H,hasPrefilledLink:!!ce.link,zapierSource:te}))}else Vr!==_e&&(ue(bt),ze(us?.key??""),Is(iC(us)));if(!(Na&&(!_n.isFetchedAfterMount||!on.isFetchedAfterMount))&&!(Na&&Ht.current)&&Na&&(_n.isError||on.isError)){as("error"),en("Paperclip couldn’t check for an existing connection. Try again."),me("key");return}}},[v,K,_n.isError,_n.isFetchedAfterMount,_n.data,on.isError,on.isFetchedAfterMount,jr.data?.configured,jr.isLoading,Cs,i,ie?.slug,Vr,At.data,At.isLoading,C,Br,ss,X,un,H,Ks,ae,c,he,O,te]),(0,m.useEffect)(()=>{Vs.current=null,is(null)},[H]),(0,m.useEffect)(()=>{const bt=Kn??ss;if(!bt||!ie||Vs.current===bt.id)return;const _e=e7(bt),ot=typeof _e.sourceTemplateKey=="string"?_e.sourceTemplateKey:null;if(ot&&ot!==ie.slug)return;const Nt=typeof _e.connectionMethodKey=="string"?_e.connectionMethodKey:null,us=Nt?Aw(ie,i).find(Na=>Na.key===Nt)??null:null;if(be(bt.name||ie.name),us){ze(us.key);const Na=_e.methodConfig&&typeof _e.methodConfig=="object"?_e.methodConfig:{};Is({...iC(us),...Object.fromEntries(Object.entries(Na).filter(ta=>typeof ta[1]=="string"||typeof ta[1]=="boolean"))})}const Ls=_e.oauth&&typeof _e.oauth=="object"?_e.oauth:null;Ls?.clientRegistrationSource==="manual"&&typeof Ls.clientId=="string"&&ye(Ls.clientId),Z==="failed"||Z==="denied"?(as("error"),en(ose(Z,se))):(as("entry"),en(null)),me("key"),Vs.current=bt.id,is(bt.id)},[i,ie,se,Z,Kn,ss]);const to=je({mutationFn:r(async bt=>{const{result:_e,enabled:ot}=bt,Nt=Object.entries(ot).filter(([,ta])=>ta).map(([ta])=>ta),us=jwe(_e,ta=>!!ot[ta]),Ls=Xt==="all"?"all_agents":{agentIds:Array.from(xt)},Na=await Zt.finishApp(T,_e.connectionId,{enabledCatalogEntryIds:Nt,askFirstCatalogEntryIds:us,...ar?{agentInstructions:ar}:{},access:Ls,...c?{preserveExistingAccess:!0}:{}});return await wr(_e.connectionId),Na},"mutationFn"),onSuccess:r(async(bt,_e)=>{await k.invalidateQueries({queryKey:["tools"]}),await k.invalidateQueries({queryKey:P.apps.attention(T)}),Vt("success"),x?.({connectionId:_e.result.connectionId})},"onSuccess"),onError:r(bt=>{Vt("key"),B({title:"Couldn’t finish setup",body:bt instanceof Error?bt.message:"Please try again.",tone:"error"})},"onError")});if(!T)return(0,t.jsx)("div",{className:"p-6 text-sm text-muted-foreground",children:"Select an organization to connect apps."});if((H||X)&&(on.isError||_n.isError))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t check the retained connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",onClick:r(async()=>{const[bt,_e]=await Promise.all([on.refetch(),_n.refetch()]);!bt.isError&&!_e.isError&&(en(null),as("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(H&&on.isFetchedAfterMount&&!Kn)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The saved connection no longer exists or is not available to this organization."}),(0,t.jsx)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if(X&&on.isFetchedAfterMount&&_n.isFetchedAfterMount&&(!ss||!un))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:ss?"This reconnect link does not match the retained connection's provider.":"The retained connection no longer exists or is not available to this organization."}),(0,t.jsx)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if((H||X)&&At.isError)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t load the provider details needed to restore this connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",onClick:r(()=>{At.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(X&&Dn===X)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip no longer has a supported setup method for this retained connection. The retained connection was not changed."}),(0,t.jsx)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if(H&&(!on.isFetchedAfterMount||At.isLoading||!ie||Lt!==Kn?.id))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading saved connection setup",children:[(0,t.jsx)(vn,{className:"h-8 w-48"}),(0,t.jsx)(vn,{className:"h-40 w-full rounded-xl"})]});if(X&&(!on.isFetchedAfterMount||!_n.isFetchedAfterMount||At.isLoading||ae&&!ie))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(vn,{className:"h-8 w-48"}),(0,t.jsx)(vn,{className:"h-40 w-full rounded-xl"})]});if(vs&&f)return(0,t.jsxs)("div",{className:"max-w-5xl","data-testid":"connection-existing-choice",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsxs)("h1",{className:"text-2xl font-bold tracking-tight",children:["Use an existing ",ae?"connection":"app connection"]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Reuse a connection without changing who already has access, or connect a new one."})]}),(0,t.jsx)(W9,{choices:h.map(bt=>({id:bt.id,name:bt.name,description:bt.status==="active"&&bt.enabled?"Ready to use":"Setup needs attention"})),pendingId:Hs,onSelect:r(async bt=>{zs(bt),ur(null);try{await f(bt)}catch(_e){ur(_e instanceof Error?_e.message:"Couldn’t use this connection."),zs(null)}},"onSelect")}),Us?(0,t.jsx)(ha,{tone:"danger",className:"mt-4",children:Us}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>Fs(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),N?(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:N,children:"Cancel"}):null]})]});const _o=Aw(ie,i),Vi=Pr?[Pr]:_o,Me=ie?Cs?Vi.find(bt=>bt.key===Cs)??null:Vi[0]??null:null,ys=ie?Me?.auth??"none":Le==="none"?"none":Le==="oauth"?"oauth":"api_key",cn=ge==="key"?((bt,_e)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(lCe,{extra:bt,forceOpen:_e,companyId:T,sentence:m6({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,lockedAgentId:c??null,preserveAgentAccess:!!(os&&(Se||ss))}),notice:[At.data?.capabilities?.canCreateOrganizationGrant===!1?At.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,At.data?.capabilities?.canSetCompanyInstall===!1?At.data.capabilities.companyInstallReason??"Only someone who can configure this connection can give every agent access.":null,c?"This task grants access only to the agent that asked for it.":null].filter(ot=>!!ot),authKind:ys,grantKinds:ln?[ln]:Me?.grantKinds,grantKind:wn,setGrantKind:wt,installChoice:Xt,setInstallChoice:Yt,installAgentIds:xt,setInstallAgentIds:Oe,lockedAgentId:c,capabilities:At.data?.capabilities,githubIdentity:ie?.slug==="github",identityLoading:!!os&&Kt,preserveAgentAccess:!!(os&&(Se||ss)),disabled:ya.isPending||qt.isPending},"connection-defaults"),ie&&an&&ar&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(K9,{provider:ie.name,template:an,value:ar,onChange:r(ot=>Ut({slug:ie.slug,value:ot}),"onChange"),disabled:ya.isPending||qt.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,aa=os&&Ea&&nk(Ea)?Ea:null,Wa=aa&&os?(0,t.jsx)(u6,{entry:os,method:aa,callbackUrl:tCe(),clientId:_t,onClientIdChange:ye,clientSecret:gt,onClientSecretChange:We,required:!1}):null,Za=cn?.()??null,Li=Wa?cn?.(Wa,Ts==="error"||_t.trim().length>0)??null:Za,Fa=!!(os&&ge==="key"&&(Re||Ts!=="entry")),Jo=!!(ge==="key"&&ie&&Cr&&!Vr&&jr.data?.configured===!0),ja=!!(ge==="key"&&ie&&Cr&&!Vr&&(jr.isLoading||jr.isError||jr.data?.configured!==!0));if(Fa&&os)return(0,t.jsx)(c6,{entry:os,resuming:!!H,phase:Ts,error:Zn,recoveryActions:se==="github_installation_required"?{installationUrl:ne,managementUrl:fe}:void 0,authorizationHost:nr,authorizationUrl:Pn,guidance:ie?.slug==="railway"&&Me?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:Me.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:Me.warnings?.map(bt=>(0,t.jsx)("li",{children:bt},bt))})]}):null,defaults:Li,settingsValid:n&&Mr,onOpenAuthorization:pn,onRetry:r(async()=>{const bt=!xn.current;xn.current=!0,en(null),as("starting");const _e=Qt?.connection??Se;if(_e&&Wa&&_t.trim()){qs.current=_e.id,Wi(os);return}if(_e){In(_e);return}if(bt&&!H&&!_n.isError&&!on.isError){Wi(os);return}Ht.current=!0;try{const[ot,Nt]=await Promise.all([_n.refetch(),on.refetch()]);if(ot.isError||Nt.isError){as("error"),en("Paperclip couldn’t check for an existing connection. Try again.");return}const us=(H?(Nt.data?.connections??[]).find(Ls=>Ls.id===H&&Ls.authKind==="oauth")??null:null)??fse(Y,ot.data?.applications??[],Nt.data?.connections??[],U?{applicationId:ce.applicationId,draftOnly:!0}:{});us&&!H&&wt(us.credentialPolicy==="per_user"?"user":us.credentialPolicy==="per_agent"?"agent":"organization"),us?In(us):ya.mutate(os)}finally{Ht.current=!1}},"onRetry"),onBack:r(()=>{mt.current?.abort(),as("entry"),en(null),Ze()},"onBack"),onCancel:r(()=>{mt.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});if(Ee&&!ie&&Ie&&ge==="key")return(0,t.jsx)(c6,{identity:{name:at.trim()||D1(Ie)||"this server",unverifiedHost:D1(Ie)},steps:{labels:dse,activeIndex:use.key},phase:Ts,error:Zn,authorizationHost:nr,authorizationUrl:Pn,defaults:Za,onOpenAuthorization:pn,onRetry:r(()=>{en(null);const bt=Qt?.connection;if(bt){as("starting"),In(bt);return}Xe(!1),as("entry")},"onRetry"),onBack:r(()=>{mt.current?.abort(),Xe(!1),as("entry"),en(null)},"onBack"),onCancel:r(()=>{mt.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});const Hi=Qt?.application.name??ie?.name??(at.trim()||Y$(Ie)||"this app"),Oo=oe?fs.filter(bt=>Aw(bt,i).length>0):fs,Xo=te?At.data?.apps.find(bt=>bt.slug==="zapier")??null:null,Fo=(ss?.connectionPurpose==="ai"?FJ.safeParse(ss.config?.ai).data:void 0)??ie?.methods.find(bt=>bt.key===Cs)?.ai??(!Cs&&ie?.methods.every(bt=>bt.ai)?ie.methods[0]?.ai:void 0),Gi=ie?w?.({app:ie,name:ke||ie.name,grantKind:wn,agentIds:[...xt],allAgents:Xt==="all",onBack:r(()=>Ze(),"onBack")})??(Fo&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(L5,{companyId:T,provider:Fo.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:ss?.connectionPurpose==="ai"?(ss.config?.ai).method:Fo.method,connectionId:ss?.connectionPurpose==="ai"?ss.id:void 0,name:ss?.connectionPurpose==="ai"?ss.name:ke||`My ${ie.name} ${Fo.method==="subscription"?"subscription":"API"}`,ownership:(ss?.connectionPurpose==="ai"?ss.credentialPolicy==="shared":wn==="organization")?"shared":"personal",agentIds:[...xt],allAgents:Xt==="all",onCancel:r(()=>N?N():C("/apps"),"onCancel"),onComplete:r(bt=>{x?.({connectionId:bt.connectionId}),x||C(`/apps/${bt.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,Zo=ss?.connectionPurpose==="ai"?["Reconnect account"]:Gi!==void 0?["Connect account"]:te?Mit:ie&&Vi.length>1?["Choose connection"]:ie&&Vi[0]?.auth==="oauth"?["Sign in"]:QC(ie,Cs)?["Share sheet"]:ie?["Add your key"]:dse,Fc=ss?.connectionPurpose==="ai"?0:(te||ie)&&ge!=="gallery"&&ge!=="success"?Pit[ge]:ge==="success"?Zo.length:use[ge];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[ge!=="success"&&!(a&&ge==="gallery")&&(0,t.jsx)(GM,{subtitle:ge==="gallery"?oe?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":Zo.length<=1?void 0:`Step ${Fc+1} of ${Zo.length}`,step:ge,activeIndex:Fc,labels:Zo,appIdentity:te?{name:"Zapier",logoUrl:Xo?.branding.logoUrl??null,darkLogoUrl:Xo?.branding.darkLogoUrl??null}:ie&&ge!=="gallery"?{name:ie.name,logoUrl:ie.branding.logoUrl,darkLogoUrl:ie.branding.darkLogoUrl??null}:void 0,unverifiedHost:!ie&&!te&&ge!=="gallery"?D1(Ie):null,onCancel:N??(()=>C("/apps"))}),ge==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),ge==="gallery"&&(0,t.jsx)(zit,{loading:At.isLoading,initialLink:Ie,apps:Oo,vercelConnect:oe,vercelConnectAvailability:At.data?.credentialSources?.vercelConnect??null,byo:le,byoOnly:a,source:E.get("source"),onPick:Zs,onUseLink:r(bt=>{const _e=w3(bt,fs);ue(null),be(""),Ue(bt),dt(_e?.name??Y$(bt)??""),Be(!1),vt(""),De({}),ds(""),xe(null),Oe(new Set(c?[c]:[])),Yt(c?"specific":"all"),wt(Br??(c?"user":"organization")),me("key")},"onUseLink")}),Jo&&ie?(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("h2",{className:"text-lg font-semibold text-foreground",children:[ie.name," sign-in is unavailable"]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This instance is connected to Paperclip, but ",ie.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),Ln?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>ze(Ln.key),"onClick"),children:["Use your own ",ie.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:Ze,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:At.isFetching,onClick:r(()=>{At.refetch()},"onClick"),children:[At.isFetching?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):ge==="key"&&ie&&ja?(0,t.jsx)("div",{className:"mx-auto max-w-xl",children:(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("div",{className:"rounded-lg bg-muted p-2 text-muted-foreground",children:(0,t.jsx)(Z0,{className:"h-5 w-5"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Connect with Paperclip"}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["You must connect this instance to Paperclip to connect to ",ie.name," (you only need to do this once)."]})]})]}),Ln?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>ze(Ln.key),"onClick"),children:["Use your own ",ie.name," OAuth app"]}):null,jr.isError||sr?(0,t.jsx)(ha,{tone:"danger",className:"mt-4",children:sr??"Paperclip couldn’t check Cloud registration. Try again."}):null,Ar?(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Finish authorization in the opened window."," ",(0,t.jsx)("a",{className:"underline",href:Ar,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,Za,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:Ze,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:jr.isLoading||mr.isPending,onClick:r(()=>{Ga(null),Jn(),Ds(),mr.mutate()},"onClick"),children:[mr.isPending?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}):null,jr.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):ge==="key"&&ie&&Gi!==void 0?Gi:ge==="key"&&ie?(0,t.jsx)(Kit,{settingsValid:n&&Mr,entry:ie,error:ya.isError?ya.error instanceof Error?ya.error.message:"Please check your key and try again.":null,values:Ae,onChange:De,oauthClientId:_t,onOAuthClientIdChange:ye,oauthClientSecret:gt,canReuseOAuthClientSecret:!!(Lr?.config?.oauth&&Lr.config.oauth.clientId===_t.trim()&&Lr.hasSavedOAuthClientSecret),onOAuthClientSecretChange:We,credentialSource:i,vercelConnector:Ot,onVercelConnectorChange:zt,vercelConnectAvailability:At.data?.credentialSources?.vercelConnect??null,methodKey:Cs,onMethodChange:r(bt=>{ze(bt?.key??""),!Br&&bt?.grantKinds&&!bt.grantKinds.includes(Bt)&&wt(J$(bt,!!c)),De({}),ye(""),We(""),zt(""),Is(iC(bt))},"onMethodChange"),configValues:Ns,onConfigChange:Is,googleSheetsLinks:Ct,googleSheetsError:$e,onGoogleSheetsLinksChange:r(bt=>{ds(bt),xe(null)},"onGoogleSheetsLinksChange"),submitting:ya.isPending,renderDefaults:cn??void 0,onBack:Ze,onConnect:r(()=>{if(QC(ie,Cs)){const ot=mq(Ct);if(ot.invalidCount>0){xe("That doesn't look like a Google Sheets link.");return}if(ot.ids.length===0){xe("Paste at least one Google Sheets link.");return}}const bt=Q2(ie,Cs||null),_e=!!(bt?.credentialFields?.length||bt?.tenantFields?.some(ot=>!ot.hidden)||bt?.extensionFields?.some(ot=>!ot.hidden));if(bt&&rp(bt)&&Se&&!_e&&!_t.trim()){xn.current=!0,en(null),as("starting"),In(Se);return}bt&&rp(bt)&&(xn.current=!0,en(null),as("starting")),Wi()},"onConnect")}):null,ge==="key"&&!ie&&!Ie&&!te&&ae&&(0,t.jsxs)("div",{className:"mx-auto max-w-xl","aria-busy":"true","aria-label":`Loading ${ae} setup`,children:[(0,t.jsx)(vn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(vn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(vn,{className:"mt-8 h-11 w-40 rounded-md"})]}),ge==="key"&&!ie&&Ie&&!te&&(0,t.jsx)(qit,{link:Ie,name:at,needsKey:de,keyValue:pt,onKeyChange:vt,authMode:Le,onAuthModeChange:r(bt=>{Qe(bt),lt(null),bt!=="auto"&&Be(!1),bt!=="bearer"&&bt!=="auto"&&vt("")},"onAuthModeChange"),headers:ut,onHeadersChange:r(bt=>{Ye(bt),lt(null)},"onHeadersChange"),oauthClientId:it,onOAuthClientIdChange:kt,oauthClientSecret:tt,onOAuthClientSecretChange:Pe,advancedOpen:Ce,onAdvancedOpenChange:He,guidance:Je,matchedEntry:rr,onUseMatchedEntry:rr?()=>Zs(rr):void 0,submitting:ya.isPending||Ee,defaults:Za,onBack:Ze,onConnect:r(()=>{lt(null),ya.mutate(void 0)},"onConnect")}),ge==="key"&&!ie&&te&&(0,t.jsx)(Bit,{link:Ie,onLinkChange:Ue,submitting:ya.isPending,defaults:Za,onBack:Ze,onConnect:r(()=>ya.mutate(void 0),"onConnect")}),ge==="success"&&(0,t.jsx)(Git,{appName:Hi,logoUrl:ie?.branding.logoUrl,darkLogoUrl:ie?.branding.darkLogoUrl,summary:Hit({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,enabledCount:Object.values(rs).filter(Boolean).length}),statedDefault:m6({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,lockedAgentId:c??null}),onDone:N??(()=>C("/apps"))})]})}r(Fit,"StandardConnectionSetupFlow");function c6({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:Dit,activeIndex:0},guidance:u,defaults:h,onRetry:p,settingsValid:f=!0,onOpenAuthorization:x,onBack:b,onCancel:v}){const j=e?.name??s?.name??"this server",N=e?null:s?.unverifiedHost??null,w=a==="entry"?{title:n?`Finish connecting ${j}`:`Connect ${j} to Paperclip`,body:n?`Your connection is saved. Continue in ${j} to approve access; its identity and agent access will stay the same.`:`Paperclip will open ${j} so you can choose a workspace and approve access.`}:a==="starting"?{title:"Preparing secure sign-in",body:`Paperclip is creating a secure ${j} connection.`}:a==="redirecting"?{title:`Opening ${j}`,body:l?`Continue at ${l} to choose a workspace and approve access. Only approve access if you recognize that address.`:`Continue in ${j} to choose a workspace and approve access.`}:{title:`${j} couldn’t connect`,body:i??"Paperclip couldn’t start secure sign-in. Try again."};return(0,t.jsxs)("div",{className:"max-w-5xl",children:[(0,t.jsx)(GM,{subtitle:"Secure MCP sign-in",step:"key",activeIndex:d.activeIndex,labels:d.labels,appIdentity:e?{name:e.name,logoUrl:e.branding.logoUrl,darkLogoUrl:e.branding.darkLogoUrl}:void 0,unverifiedHost:N,onCancel:v}),(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("span",{className:"mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background",children:a==="error"?(0,t.jsx)(vc,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(pd,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(rt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-xl font-bold tracking-tight",children:w.title}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:w.body}),N?(0,t.jsx)(HM,{host:N,className:"mt-2"}):null]})]}),a==="entry"&&u?(0,t.jsx)("div",{className:"mt-4",children:u}):null,a==="entry"||a==="error"?h:null,a==="error"&&o&&(o.installationUrl||o.managementUrl)?(0,t.jsxs)("div",{className:"mt-4 flex flex-wrap gap-2",children:[o.installationUrl?(0,t.jsx)(L,{type:"button",variant:"outline",asChild:!0,children:(0,t.jsxs)("a",{href:o.installationUrl,target:"_blank",rel:"noreferrer",children:["Install Paperclip on GitHub",(0,t.jsx)(eo,{className:"ml-1.5 h-3.5 w-3.5"})]})}):null,o.managementUrl?(0,t.jsx)(L,{type:"button",variant:"ghost",asChild:!0,children:(0,t.jsx)("a",{href:o.managementUrl,target:"_blank",rel:"noreferrer",children:"Manage repositories on GitHub"})}):null]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center gap-2",children:[a==="error"||a==="entry"?(0,t.jsxs)(L,{type:"button",onClick:p,disabled:!f,children:[a==="entry"?n?`Finish with ${j}`:`Continue to ${j}`:"Try again",a==="entry"?(0,t.jsx)(eo,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)(L,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${j}…`:"Preparing…"}),c?(0,t.jsx)(L,{variant:"outline",asChild:!0,children:(0,t.jsx)("a",{href:c,target:"_blank",rel:"noopener noreferrer",onClick:x,children:"Open sign-in in a new tab"})}):null,(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:b,children:"Back"})]})]})]})}r(c6,"OAuthConnectStateScreen");function Bit({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=d6(e),c=l?new URL(l).hostname:"",d=c==="zapier.com"||c.endsWith(".zapier.com");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Zapier MCP URL"}),(0,t.jsx)(ht,{type:"password",autoComplete:"off",spellCheck:!1,value:e,onChange:r(u=>s(u.target.value),"onChange"),onKeyDown:r(u=>{u.key==="Enter"&&d&&!n&&o()},"onKeyDown"),placeholder:"https://mcp.zapier.com/api/v1/connect?token=…",className:"mt-2 h-11",autoFocus:!0}),e.trim()&&!d&&(0,t.jsx)("p",{className:"mt-2 text-xs text-destructive",children:"Paste a valid Zapier URL to continue."})]}),a,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:i,disabled:n,children:"Back"}),(0,t.jsxs)(L,{onClick:o,disabled:n||!d,children:[n&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(Bit,"ZapierConnectStep");function zit({loading:e,initialLink:s="",apps:n,byo:a=!1,byoOnly:i=!1,vercelConnect:o=!1,vercelConnectAvailability:l=null,source:c=null,onPick:d,onUseLink:u}){const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(s),b=(0,m.useRef)(!1);(0,m.useEffect)(()=>{b.current||x(s)},[s]);const[v,j]=(0,m.useState)(null),N=(0,m.useRef)(null),w=(0,m.useRef)(null),k=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!a||e&&!i||k.current||(i||N.current?.scrollIntoView?.({block:"center"}),w.current?.focus(),w.current?.select(),k.current=!0)},[a,i,e]);const S=(0,m.useMemo)(()=>{const A=h.trim().toLowerCase();return n.filter(D=>!A||D.name.toLowerCase().includes(A))},[n,h]),C=d6(f),I=C?w3(C,n):null,R=c==="zapier",T=r(()=>{const A=d6(f);if(!A){j("Paste a full http or https link.");return}j(null),u(A)},"continueWithLink");return e&&!i?(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((A,D)=>(0,t.jsx)(vn,{className:"h-32 w-full rounded-xl"},D))}):(0,t.jsxs)("div",{className:"space-y-6",children:[o?(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-bold tracking-tight",children:"Connect through Vercel"}),(0,t.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Create and manage the provider connector in Vercel. Paperclip stores its reference and applies agent access, policy, approval, and audit controls here."})]}),l?(0,t.jsx)(L,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:(0,t.jsxs)("a",{href:l.manageUrl,target:"_blank",rel:"noreferrer",children:["Open Vercel Connect",(0,t.jsx)(eo,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(ha,{tone:"danger",compact:!0,className:"mt-4",children:l.reason??"Vercel Connect is unavailable on this instance."}):null]}):null,!i&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(oa,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ht,{value:h,onChange:r(A=>p(A.target.value),"onChange"),placeholder:"Search apps…",className:"h-11 pl-9"})]}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:S.map(A=>{const D=eCe(A.slug,A.description),M=pA(A),B=M.length===0||M.every(z=>z.auth==="oauth"&&!rp(z)&&!nk(z)),E=A.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:B||E,title:E?A.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(A),"onClick"),className:W("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",B||E?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(al,{name:A.name,logoUrl:A.branding.logoUrl,darkLogoUrl:A.branding.darkLogoUrl,size:36}),(0,t.jsx)("div",{className:"mt-3 text-sm font-bold text-foreground",children:A.name}),(0,t.jsx)("div",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:D.tagline}),(0,t.jsx)("div",{className:"mt-3 text-xs font-semibold text-foreground",children:E?(0,t.jsx)("span",{className:"text-muted-foreground",children:A.availability?.reason??l?.reason??"Unavailable on this instance."}):B?(0,t.jsx)("span",{className:"text-muted-foreground",children:"Unavailable"}):(0,t.jsx)("span",{children:"Connect →"})})]},A.slug)})}),S.length===0&&(0,t.jsxs)("div",{className:"py-10 text-center text-sm text-muted-foreground",children:["No apps match “",h,"”."]})]}),o?null:(0,t.jsxs)("div",{ref:N,className:W("grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",a&&"-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0"),children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)(vc,{className:"h-4 w-4 text-muted-foreground"}),R?"Connect Zapier":a?"Connect your own MCP server":"Connect with a link"]}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:R?"Paste the complete MCP URL Zapier gives you, including its token.":a?"Paste your MCP server’s URL and every discovered tool will be available immediately.":"Paste a setup link from an app that is not listed here."}),!R&&(0,t.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground",children:["Any remote tool URL works here — including a local MCP server like"," ",(0,t.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:"http://127.0.0.1:8848/mcp"}),"."]}),I&&(0,t.jsxs)("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(al,{name:I.name,logoUrl:I.branding.logoUrl,darkLogoUrl:I.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["This looks like ",I.name,"."]})]}),(0,t.jsx)(L,{type:"button",size:"sm",variant:"outline",disabled:I.availability?.available===!1,onClick:r(()=>{if(j(null),I.slug==="zapier"){T();return}d(I)},"onClick"),children:I.availability?.available===!1?"Not available":I.slug==="zapier"?"Continue":`Use ${I.name}`})]})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2 sm:min-w-(--sz-360px)",children:[(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(ht,{ref:w,type:R||I?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(A=>{b.current=!0,x(A.target.value),j(null)},"onChange"),onKeyDown:r(A=>{A.key==="Enter"&&T()},"onKeyDown"),placeholder:R?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:T,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(zit,"GalleryStep");function d6(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(d6,"normalizeAppLink");function qit({link:e,name:s,needsKey:n,keyValue:a,onKeyChange:i,authMode:o,onAuthModeChange:l,headers:c,onHeadersChange:d,oauthClientId:u,onOAuthClientIdChange:h,oauthClientSecret:p,onOAuthClientSecretChange:f,advancedOpen:x,onAdvancedOpenChange:b,guidance:v,matchedEntry:j,onUseMatchedEntry:N,submitting:w,defaults:k,onBack:S,onConnect:C}){const I=D1(e),R=o==="custom_headers"?sCe(c):null,T=wit({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),A=o==="auto"&&n||o==="bearer",D=j?.slug==="zapier"?Fpe(e):e,M=r((B,E)=>{d(c.map(z=>z.id===B?{...z,...E}:z))},"updateHeader");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)("p",{className:"min-w-0 truncate font-mono text-sm text-muted-foreground",title:D,children:D}),(0,t.jsx)(HM,{host:I})]}),j&&N?(0,t.jsxs)("div",{className:"mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(al,{name:j.name,logoUrl:j.branding.logoUrl,darkLogoUrl:j.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["Paperclip has a guided setup for ",j.name,"."]})]}),(0,t.jsxs)(L,{type:"button",size:"sm",variant:"outline",onClick:N,children:["Use ",j.name]})]}):null,v?(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(ha,{tone:"warning",title:v.title,children:v.body})}):null,(0,t.jsxs)("div",{className:"mt-6 space-y-6",children:[A?(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-key",children:"App key"}),(0,t.jsx)(ht,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r(B=>i(B.target.value),"onChange"),placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Grant this key read and write access to the resources your agents need. Paperclip cannot increase its permissions."})]})}):null,(0,t.jsxs)(gl,{open:x,onOpenChange:b,children:[(0,t.jsxs)(ec,{className:"flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40",children:["Advanced authentication",(0,t.jsx)(nn,{className:W("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(xl,{className:"space-y-5 pt-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Only needed when the server's docs are specific about how to authenticate."}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:xse.map(B=>(0,t.jsx)(Uit,{label:B.label,selected:o===B.mode,onClick:r(()=>l(B.mode),"onClick")},B.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:xse.find(B=>B.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map(B=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(ht,{value:B.name,onChange:r(E=>M(B.id,{name:E.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(ht,{type:"password",autoComplete:"off",value:B.value,onChange:r(E=>M(B.id,{value:E.target.value}),"onChange"),placeholder:"Value","aria-label":B.name.trim()?`Value for ${B.name.trim()}`:"Header value",className:"h-10 font-mono"}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-10 shrink-0",onClick:r(()=>d(c.filter(E=>E.id!==B.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},B.id)),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,l6()]),"onClick"),children:"Add another header"}),R?(0,t.jsx)("p",{className:"text-xs text-destructive",children:R}):null]}):null,o==="oauth"?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the server's docs tell you to register Paperclip yourself first."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-id",children:"Client ID"}),(0,t.jsx)(ht,{id:"generic-mcp-client-id",value:u,onChange:r(B=>h(B.target.value),"onChange"),autoComplete:"off",placeholder:"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-secret",children:"Client secret"}),(0,t.jsx)(ht,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r(B=>f(B.target.value),"onChange"),placeholder:"Optional",className:"mt-2 h-11 font-mono"})]})]}):null]})]})]}),k,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:S,disabled:w,children:"Back"}),(0,t.jsxs)(L,{onClick:C,disabled:w||!T||!!R,children:[w&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(qit,"LinkConnectStep");var xse=[{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 Uit({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(Uit,"SegmentedOption");function Kit({settingsValid:e=!0,entry:s,error:n,values:a,onChange:i,oauthClientId:o,onOAuthClientIdChange:l,oauthClientSecret:c,canReuseOAuthClientSecret:d,onOAuthClientSecretChange:u,credentialSource:h,vercelConnector:p,onVercelConnectorChange:f,vercelConnectAvailability:x,methodKey:b,onMethodChange:v,configValues:j,onConfigChange:N,googleSheetsLinks:w,googleSheetsError:k,onGoogleSheetsLinksChange:S,submitting:C,renderDefaults:I,onBack:R,onConnect:T}){const A=(0,m.useMemo)(()=>Aw(s,h),[h,s]),D=b?A.find(Le=>Le.key===b)??null:vk(A),M=(0,m.useMemo)(()=>A.some(Le=>Le.capabilityProfile)?Array.from(A.reduce((Le,Qe)=>{const ut=Qe.capabilityProfile.key,Ye=Le.get(ut);return Ye?Ye.methods.push(Qe):Le.set(ut,{key:ut,label:Qe.capabilityProfile?.label??Qe.label??Qe.key,description:Qe.capabilityProfile?.description??Qe.whenToUse,methods:[Qe]}),Le},new Map)).map(([,Le])=>Le):[],[A]),B=D?.capabilityProfile?.key??D?.key??"",E=M.map(Le=>Le.key).join("|"),[z,$]=(0,m.useState)(B||vk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""));(0,m.useEffect)(()=>{if(B){$(B);return}$(Le=>M.some(Qe=>Qe.key===Le)?Le:vk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""))},[E,M,A,B]);const q=M.length>1?M.find(Le=>Le.key===z)?.methods??[]:A,U=(D?.credentialFields??[]).map(Le=>({...Le,configPath:Qpe(Le,D),helpUrl:D?.consoleLinks?.keys??D?.consoleLinks?.docs??""})),O=D?.credentialSources?.vercelConnect??null,K=h==="vercel_connect",H=K||U.every(Le=>Le.required===!1||(a[Le.configPath]?.trim().length??0)>0),Z=nk(D),se=Z&&!rp(D),ne=K||!se||o.trim().length>0&&(!D?.oauthClientSecretRequired||d||c.trim().length>0),fe=!K||p.trim().length>0,X=D?.auth==="oauth"&&Z?tCe():null,re=[...D?.tenantFields??[],...D?.extensionFields??[]],oe=re.filter(Le=>!Le.hidden),G=oe.filter(Le=>Le.advanced!==!0),Y=oe.filter(Le=>Le.advanced===!0),Q=re.every(Le=>{if(!Le.required)return!0;const Qe=j[Le.key];return typeof Qe=="boolean"||typeof Qe=="string"&&Qe.trim().length>0}),te=D?.configRequirements?.atLeastOneOf??[],ae=te.length===0||te.some(Le=>{const Qe=j[Le];return typeof Qe=="string"&&Qe.trim().length>0}),le=(M.length<=1||!!z)&&(q.length<=1?!!D:!!b),he=s.availability?.robotEmail??null,ce=s.availability?.available===!1,ge=!K&&Z&&!se,me=M.length>1||q.length>1,ie=M.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"What should Paperclip be able to do?"}),(0,t.jsx)(wm,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:z,onValueChange:r(Le=>{const Qe=M.find(ut=>ut.key===Le);Qe&&($(Le),v(i7(Qe.methods)))},"onValueChange"),options:M.map(Le=>({value:Le.key,title:Le.label,description:Le.description}))}),!z&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,ue=q.find(Le=>Le.oauthStrategy==="paperclip_cloud_connector"),ke=ue&&q.find(Le=>nk(Le)&&!rp(Le)),be=D?.key===ke?.key,Ie=(0,m.useId)(),Ue=ue&&ke&&q.length===2?(0,t.jsx)(L,{type:"button",variant:"link",className:"h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground","aria-expanded":be,"aria-controls":Ie,disabled:C,onClick:r(()=>v(be?ue:ke),"onClick"),children:be?"Use Paperclip instead":`Use your own ${NLe(ue.connectorProfile??"")?"Google":s.name} OAuth app`}):q.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"How do you want to connect?"}),(0,t.jsx)(wm,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:b,onValueChange:r(Le=>{const Qe=q.find(ut=>ut.key===Le);Qe&&v(Qe)},"onValueChange"),options:q.map(Le=>({value:Le.key,title:Le.label??(Le.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!D&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,at=Y.length>0||ge||me,dt=be||!le,de=at?(0,t.jsxs)("div",{className:"space-y-6",children:[ie,Ue,Y.map(Le=>(0,t.jsx)(gse,{field:Le,value:j[Le.key],onChange:r(Qe=>N({...j,[Le.key]:Qe}),"onChange")},Le.key)),ge?(0,t.jsx)(u6,{entry:s,method:D,callbackUrl:X,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!1}):null]}):null,Be=I?.(de,dt)??null;if(QC(s,D)){const Le=mq(w),Qe=e&&!ce&&!!he&&w.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[ie,he?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Share each sheet with this email"}),(0,t.jsxs)("div",{className:"mt-2 flex min-w-0 flex-col gap-2 sm:flex-row",children:[(0,t.jsx)("div",{title:he,className:"min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all",children:he}),(0,t.jsx)(oCe,{value:he,ariaLabel:"Copy sharing email"})]}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below."})]}):(0,t.jsx)("div",{className:"rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground",children:"Google Sheets is not available on this instance yet."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paste links to the sheets you shared"}),(0,t.jsx)(Cn,{value:w,onChange:r(ut=>S(ut.target.value),"onChange"),placeholder:"https://docs.google.com/spreadsheets/d/...",className:"mt-2 min-h-28"}),(0,t.jsx)("div",{className:"mt-2 text-xs text-muted-foreground",children:Le.ids.length>0?`${Le.ids.length} ${Le.ids.length===1?"sheet":"sheets"} ready to connect.`:"Paste one link per line. Both .../edit and .../edit#gid=... links work."}),k&&(0,t.jsx)("div",{className:"mt-2 text-xs text-destructive",children:k})]})]}),Be,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:R,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:T,disabled:C||!Qe,children:[C&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":"Connect"]})]})]})}const pt=D?.connectorProfile==="asana.mcp",vt=pt?null:D?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[vt?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:vt,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground",children:["Review requirements",(0,t.jsx)(eo,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[pt?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Sign in with Asana to choose your workspace and connect it to Paperclip."}):null,D?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[D.capabilityProfile.label,": ",D.capabilityProfile.description]}),K&&O&&x?(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Create or attach the connector in Vercel"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Paperclip does not copy Vercel’s setup forms. Finish connector setup there, then paste its UID below."}),(0,t.jsxs)("a",{href:x.manageUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open Vercel Connect",(0,t.jsx)(eo,{className:"h-3 w-3"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"vercel-connect-connector",children:"Connector UID or ID"}),(0,t.jsx)(ht,{id:"vercel-connect-connector",value:p,onChange:r(Le=>f(Le.target.value),"onChange"),autoComplete:"off",placeholder:"service/my-connector or scl_…",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Paperclip validates the connector and stores only its reference and redacted verification metadata."})]})]}):null,n?(0,t.jsx)("div",{role:"alert",children:(0,t.jsx)(ha,{tone:"danger",children:n})}):null,G.map(Le=>(0,t.jsx)(gse,{field:Le,value:j[Le.key],onChange:r(Qe=>N({...j,[Le.key]:Qe}),"onChange")},Le.key)),!K&&D?.auth==="oauth"&&se?(0,t.jsx)("div",{id:Ie,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(u6,{entry:s,method:D,callbackUrl:X,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!0})}):null,K||!D||U.length===0?null:U.map(Le=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:tse(s.name,Le.label,U.length)}),(0,t.jsx)(ht,{type:Le.type==="text"&&Le.secret===!1?"text":"password","aria-label":tse(s.name,Le.label,U.length),autoComplete:"off",value:a[Le.configPath]??"",onChange:r(Qe=>i({...a,[Le.configPath]:Qe.target.value}),"onChange"),placeholder:Le.type==="text"&&Le.secret===!1?Le.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),Le.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:Le.helperMd}),Le.helpUrl&&(0,t.jsxs)("a",{href:Le.helpUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Where do I find this?",(0,t.jsx)(eo,{className:"h-3 w-3"})]})]},Le.configPath))]}),Be,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:R,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:T,disabled:C||!e||!le||!H||!ne||!fe||!Q||!ae,children:[C&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":K?D?.auth==="oauth"?"Validate and continue":"Validate and connect":D?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(Kit,"KeyStep");function oCe({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=Cp();return(0,t.jsxs)(L,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(gs,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(Ir,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(oCe,"CopyValueButton");function u6({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)(eo,{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)(oCe,{value:n,ariaLabel:"Copy callback URL"})]}),(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:["Add this exact URL to ",e.name," before continuing. It must match the authorization request."]})]}):null,(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-id",children:"Client ID"}),(0,t.jsx)(ht,{id:"curated-oauth-client-id",value:a,onChange:r(d=>i(d.target.value),"onChange"),autoComplete:"off",placeholder:c?"Required":"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-secret",children:"Client secret"}),(0,t.jsx)(ht,{id:"curated-oauth-client-secret",type:"password",value:o,onChange:r(d=>l(d.target.value),"onChange"),autoComplete:"off",placeholder:s.oauthClientSecretRequired?"Required":"Optional for public clients",className:"mt-2 h-11 font-mono"})]})]})}r(u6,"OAuthClientFields");function gse({field:e,value:s,onChange:n}){return e.type==="checkbox"?(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:e.label}),e.helperMd&&(0,t.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:e.helperMd})]}),(0,t.jsx)(ci,{checked:s===!0,onCheckedChange:n})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:e.label}),e.type==="textarea"?(0,t.jsx)(Cn,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,className:"mt-2 min-h-24"}):e.type==="select"?(0,t.jsxs)("select",{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),className:"mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",children:[(0,t.jsx)("option",{value:"",disabled:!0,children:"Select an option"}),(e.options??[]).map(a=>(0,t.jsx)("option",{value:a.value,children:a.label},a.value))]}):(0,t.jsx)(ht,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,"aria-label":e.label,maxLength:e.validation?.maxLength,className:"mt-2 h-11"}),e.required&&(typeof s!="string"||!s.trim())&&(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.label," is required."]}),e.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:e.helperMd})]})}r(gse,"MethodConfigField");function Wit({companyId:e,...s}){const n=ee({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn")});return(0,t.jsx)(HW,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(Wit,"AccessStep");function HW({agents:e,agentsLoading:s=!1,authKind:n,grantKinds:a,grantKind:i,setGrantKind:o,installChoice:l,setInstallChoice:c,installAgentIds:d,setInstallAgentIds:u,lockedAgentId:h,capabilities:p,githubIdentity:f=!1,submitLabel:x,continuesToProvider:b=!1,identityLoading:v=!1,preserveAgentAccess:j=!1,pending:N=!1,hideFooter:w=!1,bare:k=!1,onBack:S,onContinue:C}){const I=p?.editableAgentIds,R=I?e.filter(U=>I.includes(U.id)):e,T=p?.canSetCompanyInstall??!0,A=p?.canCreateOrganizationGrant??!0,D=n!=="none",M=a??["user","organization"],B=(!D||i==="user"||i==="agent"||A)&&(j?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?T:d.size>0),E=h?e.find(U=>U.id===h)?.name??"the requesting agent":null,z=f?"Connect GitHub as":"Which humans can use this credential?",$=i==="agent"?"Which agent owns this GitHub account?":f&&i==="user"?"Which agents may use your GitHub when you’re responsible?":f?"Which agents may use the shared GitHub account?":"Which agents can use this connection?",q=f?$:"Which agents can use this connection?";return(0,t.jsxs)("div",{className:k?"":"mx-auto max-w-2xl",children:[(0,t.jsx)("div",{className:"overflow-hidden rounded-xl border border-border bg-background",children:(0,t.jsxs)("div",{className:"divide-y divide-border",children:[(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:z}),f&&i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This agent uses this GitHub account for everyone’s work, instead of the person giving instructions."}):null,v?(0,t.jsxs)("div",{className:"mt-4 grid gap-2 sm:grid-cols-2","aria-label":"Loading connection identity",children:[(0,t.jsx)(vn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(vn,{className:"h-20 w-full rounded-md"})]}):D&&M.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[M[0]==="user"?(0,t.jsx)(Ph,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):M[0]==="agent"?(0,t.jsx)(no,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(ck,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:M[0]==="user"?f?"My GitHub account":"Just me":M[0]==="agent"?"A dedicated account for an agent":f?"Shared organization GitHub account (advanced)":"Any human in the organization"}),f?(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:M[0]==="user"?"Agents use it only for runs where you are the responsible person.":M[0]==="agent"?"That agent always uses this account, regardless of who starts the run.":"Eligible agents use one shared credential, regardless of who starts the run."}):null]})]}):D?(0,t.jsx)(wm,{ariaLabel:f?z:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(U=>{const O=U;o(O),O==="agent"&&(c("specific"),d.size>1&&u(new Set([[...d][0]])))},"onValueChange"),options:[{value:"user",title:f?"My GitHub account":"Just me",description:f?"Agents use it only for runs where you are the responsible person.":void 0,icon:(0,t.jsx)(Ph,{className:"h-4 w-4","aria-hidden":"true"})},{value:"agent",title:"A dedicated account for an agent",description:f?"That agent always uses this account, regardless of who starts the run.":void 0,icon:(0,t.jsx)(no,{className:"h-4 w-4","aria-hidden":"true"})},{value:"organization",title:f?"Shared organization GitHub account (advanced)":"Any human in the organization",description:f?"Eligible agents use one shared credential, regardless of who starts the run.":void 0,icon:(0,t.jsx)(ck,{className:"h-4 w-4","aria-hidden":"true"}),accessibleLabel:A?f?"Shared organization GitHub account (advanced)":"Any human in the organization":`${f?"Shared organization GitHub account (advanced)":"Any human in the organization"}. Unavailable: ${p?.organizationGrantReason??"Only a connection manager can share this credential with the organization."}`,tooltip:A?void 0:p?.organizationGrantReason??"Only a connection manager can share this credential with the organization.",disabled:!A}].filter(U=>M.includes(U.value))}):(0,t.jsx)("p",{className:"mt-4 text-sm text-muted-foreground",children:"No identity required"})]}),(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:$}),j?(0,t.jsxs)("div",{className:"mt-4 flex items-start gap-3 rounded-md border border-border bg-muted/40 p-4",children:[(0,t.jsx)(ck,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Existing agent access stays the same"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Reconnecting replaces the credential without changing which agents can use it."})]})]}):h?(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This task grants access only to ",(0,t.jsx)("span",{className:"font-medium text-foreground",children:E}),". Existing connection access is left unchanged."]}):i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Choose exactly one agent. This identity cannot be shared with other agents."}):(0,t.jsx)(wm,{ariaLabel:q,className:"mt-4 sm:grid-cols-2",value:l,onValueChange:r(U=>c(U),"onValueChange"),options:[{value:"specific",title:f?"Only agents I choose":"Just agents I pick",description:f?i==="user"?"Only selected agents may use your GitHub when you’re responsible.":"Only selected agents may use the shared account.":void 0,icon:(0,t.jsx)(no,{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)(Vit,{}),accessibleLabel:T?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:T?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!T}]}),!j&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Zy,{agents:R,selectedAgentIds:d,onChange:r(U=>u(i==="agent"&&U.size>1?new Set([[...U].at(-1)]):U),"onChange"),loading:s,emptyMessage:"You cannot edit any agents yet.",showSelectionPreview:!1})}):null]})]})}),w?null:(0,t.jsxs)("div",{className:"mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,t.jsx)(L,{variant:"ghost",className:"w-full sm:w-auto",onClick:S,disabled:N,children:"Back"}),(0,t.jsxs)(L,{className:"w-full sm:w-auto",onClick:C,disabled:!B||v||N,children:[N?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!N&&b?(0,t.jsx)(eo,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r(HW,"AccessStepContent");function m6(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(m6,"connectionDefaultSummarySentence");function lCe({companyId:e,agents:s,sentence:n,notice:a,extra:i,forceOpen:o=!1,disabled:l=!1,...c}){const[d,u]=(0,m.useState)(!1);return(0,t.jsxs)(gl,{open:d||o,onOpenChange:u,className:"mt-6 rounded-lg border border-border bg-muted/30 px-4 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n}),(0,t.jsx)(ec,{asChild:!0,children:(0,t.jsx)(L,{type:"button",variant:"link",className:"h-auto p-0 text-xs font-semibold underline underline-offset-2",disabled:l,children:"Change"})})]}),(a??[]).map(h=>(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:h},h)),(0,t.jsx)(xl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(HW,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(Wit,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(lCe,"ConnectionAccessDefaults");function Vit(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(no,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(no,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(Vit,"BotGroupIcon");function Hit(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(Hit,"accessSummaryLines");function Git({appName:e,logoUrl:s,darkLogoUrl:n,summary:a,statedDefault:i,onDone:o}){return(0,t.jsxs)("div",{className:"mx-auto max-w-md py-10 text-center",children:[(0,t.jsx)("div",{className:"mx-auto flex h-20 w-20 items-center justify-center rounded-full border-2 border-emerald-500 bg-emerald-500/10",children:(0,t.jsx)(gs,{className:"h-9 w-9 text-emerald-600 dark:text-emerald-400"})}),(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-center gap-2",children:[(0,t.jsx)(al,{name:e,logoUrl:s,darkLogoUrl:n,size:28}),(0,t.jsxs)("h2",{className:"text-2xl font-bold tracking-tight",children:[e," is ready."]})]}),i?(0,t.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:i}):null,(0,t.jsx)("dl",{className:"mx-auto mt-6 max-w-xs space-y-1 text-left",children:a.map(l=>(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-4",children:[(0,t.jsx)("dt",{className:"text-xs font-medium text-muted-foreground",children:l.label}),(0,t.jsx)("dd",{className:"text-sm text-foreground",children:l.value})]},l.label))}),(0,t.jsx)("div",{className:"mt-8",children:(0,t.jsx)(L,{size:"lg",className:"px-10",onClick:o,children:"View connection"})})]})}r(Git,"ConnectionSetupCompletionScreen");function cCe(){const{newProjectOpen:e,closeNewProject:s}=BI(),{selectedCompanyId:n}=ps();return n&&e?(0,t.jsx)(Qit,{companyId:n,onClose:s},n):null}r(cCe,"NewProjectDialog");function Qit({companyId:e,onClose:s}){const n=Pt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>k3[Math.floor(Math.random()*k3.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=je({mutationFn:r(()=>pa.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{J0(f.id,e),n.invalidateQueries({queryKey:P.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(Ys,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Js,{showCloseButton:!1,"aria-describedby":void 0,className:"flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 shadow-sm sm:max-w-lg",onOpenAutoFocus:r(f=>{f.preventDefault(),h.current?.focus()},"onOpenAutoFocus"),children:d?(0,t.jsxs)("div",{className:"min-h-0 overflow-y-auto p-5",children:[(0,t.jsx)(Xs,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(m4,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:U9(e)}),u(!1)},"onComplete")})]}):(0,t.jsxs)("form",{className:"flex min-h-0 flex-col overflow-hidden",onSubmit:r(f=>{f.preventDefault(),a.trim()&&!p.isPending&&p.mutate()},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-5 pb-4 pt-5",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)(Xs,{className:"text-lg font-semibold",children:"Create project"}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",disabled:p.isPending,"aria-label":"Close new project",onClick:s,children:(0,t.jsx)(Fn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-input px-3 focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",children:[(0,t.jsx)(Em,{color:o,size:"sm"}),(0,t.jsx)("input",{ref:h,"aria-label":"Project name",value:a,disabled:p.isPending,onChange:r(f=>i(f.target.value),"onChange"),placeholder:"Project name",required:!0,className:"h-10 w-full min-w-0 border-0 bg-transparent text-base outline-none placeholder:text-muted-foreground md:text-sm"})]})]}),(0,t.jsx)("div",{role:"region","aria-label":"Source repositories",tabIndex:0,className:"min-h-0 overflow-y-auto overscroll-contain px-5 pb-1 outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",children:(0,t.jsx)(ywe,{companyId:e,selected:l,onChange:c,onConnect:r(()=>u(!0),"onConnect"),disabled:p.isPending})}),p.isError&&(0,t.jsx)("p",{role:"alert",className:"px-5 pt-3 text-sm text-destructive",children:p.error.message}),(0,t.jsxs)("div",{className:"flex shrink-0 justify-end gap-2 px-5 py-5",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",disabled:p.isPending,onClick:s,children:"Cancel"}),(0,t.jsx)(L,{type:"submit",disabled:!a.trim()||p.isPending,children:p.isPending?"Creating…":"Create project"})]})]})})})}r(Qit,"NewProjectForm");var rg={list:r(e=>Te.get(`/companies/${e}/goals`),"list"),get:r(e=>Te.get(`/goals/${e}`),"get"),create:r((e,s)=>Te.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>Te.patch(`/goals/${e}`,s),"update"),remove:r(e=>Te.delete(`/goals/${e}`),"remove")};function dCe(e){return{"--sc":`var(${e})`}}r(dCe,"scStyle");function Yit(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(Yit,"sentenceCaseStatus");function ri({status:e,label:s}){return(0,t.jsx)("span",{className:W("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",Iz[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(ri,"StatusBadge$5");function uCe({status:e}){const s=cBe[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:dCe(s),children:n.replace(/_/g," ")})}r(uCe,"AgentStatusBadge");function sp({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=aBe[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:dCe(a),children:[(0,t.jsx)(FI,{status:n,size:"sm"}),Yit(n)]})}r(sp,"IssueStatusBadge");var bse={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function mCe(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=BI(),{selectedCompanyId:a,selectedCompany:i}=ps(),o=Pt(),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)("planned"),[f,x]=(0,m.useState)("task"),[b,v]=(0,m.useState)(""),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[I,R]=(0,m.useState)(!1),T=(0,m.useRef)(null),A=b||s.parentId||"",{data:D}=ee({queryKey:P.goals.list(a),queryFn:r(()=>rg.list(a),"queryFn"),enabled:!!a&&e}),M=je({mutationFn:r(U=>rg.create(a,U),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:P.goals.list(a)}),E(),n()},"onSuccess")}),B=je({mutationFn:r(async U=>{if(!a)throw new Error("No organization selected");return vb.uploadImage(a,U,"goals/drafts")},"mutationFn")});function E(){c(""),u(""),p("planned"),x("task"),v(""),N(!1)}r(E,"reset");function z(){!a||!l.trim()||M.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...A?{parentId:A}:{}})}r(z,"handleSubmit");function $(U){U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&(U.preventDefault(),z())}r($,"handleKeyDown");const q=(D??[]).find(U=>U.id===A);return(0,t.jsx)(Ys,{open:e,onOpenChange:r(U=>{U||(E(),n())},"onOpenChange"),children:(0,t.jsxs)(Js,{showCloseButton:!1,className:W("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:$,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[i&&(0,t.jsx)("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:i.issuePrefix}),(0,t.jsx)("span",{className:"text-muted-foreground/60",children:"›"}),(0,t.jsx)("span",{children:s.parentId?"New sub-goal":"New goal"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>N(!j),"onClick"),children:j?(0,t.jsx)(gbe,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Gy,{className:"h-3.5 w-3.5"})}),(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{E(),n()},"onClick"),children:(0,t.jsx)("span",{className:"text-lg leading-none",children:"×"})})]})]}),(0,t.jsx)("div",{className:"px-4 pt-4 pb-2 shrink-0",children:(0,t.jsx)("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:l,onChange:r(U=>c(U.target.value),"onChange"),onKeyDown:r(U=>{U.key==="Tab"&&!U.shiftKey&&(U.preventDefault(),T.current?.focus())},"onKeyDown"),autoFocus:!0})}),(0,t.jsx)("div",{className:"px-4 pb-2 overflow-y-auto max-h-(--sz-50vh)",children:(0,t.jsx)(fd,{ref:T,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:W("text-sm text-muted-foreground",j?"min-h-(--sz-220px)":"min-h-(--sz-120px)"),imageUploadHandler:r(async U=>(await B.mutateAsync(U)).contentPath,"imageUploadHandler")})}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[(0,t.jsxs)(br,{open:w,onOpenChange:k,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsx)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:(0,t.jsx)(ri,{status:h})})}),(0,t.jsx)(dr,{className:"w-40 p-1",align:"start",children:efe.map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",U===h&&"bg-accent"),onClick:r(()=>{p(U),k(!1)},"onClick"),children:U},U))})]}),(0,t.jsxs)(br,{open:S,onOpenChange:C,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(zl,{className:"h-3 w-3 text-muted-foreground"}),bse[f]??f]})}),(0,t.jsx)(dr,{className:"w-40 p-1",align:"start",children:gfe.map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",U===f&&"bg-accent"),onClick:r(()=>{x(U),C(!1)},"onClick"),children:bse[U]??U},U))})]}),(0,t.jsxs)(br,{open:I,onOpenChange:R,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(vp,{className:"h-3 w-3 text-muted-foreground"}),q?q.title:"Parent goal"]})}),(0,t.jsxs)(dr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!A&&"bg-accent"),onClick:r(()=>{v(""),R(!1)},"onClick"),children:"No parent"}),(D??[]).map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",U.id===A&&"bg-accent"),onClick:r(()=>{v(U.id),R(!1)},"onClick"),children:U.title},U.id))]})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:(0,t.jsx)(L,{size:"sm",disabled:!l.trim()||M.isPending,onClick:z,children:M.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(mCe,"NewGoalDialog");function Jit(e){const s=Xit(e),n=Zit(e);return`You're invited to join a Paperclip company as an agent.
|
|
306
|
+
`;function lrt(){const e=new Blob([ort],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(lrt,"createSandboxedWorker");var Yq=new Map,P5=new Map,xE=new Set,gE=new Map,xSe=null;function crt(e){xSe=e}r(crt,"setDynamicParserResultNotifier");function gSe(e,s){e.worker.postMessage(s)}r(gSe,"sendToWorker");function drt(e){return e.nextId++}r(drt,"nextRequestId");function urt(e,s){return`${s}\0${e}`}r(urt,"lineCacheKey");function mrt(){xSe?.()}r(mrt,"notifyResultReady");function hrt(e,s,n){return new Promise(a=>{const i=drt(e);e.pendingResolves.set(i,a),gSe(e,{type:"parse",id:i,line:s,ts:n})})}r(hrt,"parseLineAsync");function HC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(HC,"drainPendingRequests");function prt(e){return new Promise((s,n)=>{const a=lrt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{HC(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"&&HC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),HC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),HC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},gSe(i,{type:"init",source:e})})}r(prt,"initSandboxedWorker");function frt(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=urt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),hrt(e,i,o).then(d=>{n.delete(l),s.set(l,d),mrt()})),[])},"parseStdoutLine")}}r(frt,"buildParserModule");async function Jq(e){const s=P5.get(e);if(s)return s;if(xE.has(e))return null;const n=gE.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 xE.add(e),null;const o=await prt(await i.text());Yq.set(e,o);const l=frt(o);return P5.set(e,l),l}catch{return xE.add(e),null}finally{gE.delete(e)}})();return gE.set(e,a),a}r(Jq,"loadDynamicParser");function Xq(e){const s=P5.has(e);P5.delete(e),xE.delete(e),gE.delete(e);const n=Yq.get(e);return n&&(HC(n),n.worker.terminate(),Yq.delete(e)),s}r(Xq,"invalidateDynamicParser");var bE=[],c4=new Map,Zq=new Set,bSe=new Map,F$=new Set,W2=new Map,e6=new Set;function vSe(e){return e6.add(e),()=>e6.delete(e)}r(vSe,"onAdapterChange");function ySe(){for(const e of e6)e()}r(ySe,"notifyAdapterChange");crt(ySe);function xrt(){for(const e of[ttt,ptt,Ptt,Ftt,lst,jst,Pst,qst,Zst,cnt,Pnt,Cnt,Xtt,Qnt,E5,irt])Zq.add(e.type),bSe.set(e.type,e),wv(e)}r(xrt,"registerBuiltInUIAdapters");function wv(e){const s=bE.findIndex(n=>n.type===e.type);s>=0?bE.splice(s,1,e):bE.push(e),c4.set(e.type,e),ySe()}r(wv,"registerUIAdapter");function jSe(e){return c4.get(e)??null}r(jSe,"findUIAdapter");xrt();function iS(e){const s=c4.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Jq(e).then(o=>{o&&wv({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:yy,buildAdapterConfig:aN})})),E5.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:yy,buildAdapterConfig:aN}}return s}r(iS,"getUIAdapter");function grt(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 Zq){const i=bSe.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=F$.has(a);if(o&&l&&!c){F$.add(a);const d=(W2.get(a)??0)+1;W2.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;wv({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Jq(a).then(b=>{b&&W2.get(a)===d&&wv({type:a,label:p,parseStdoutLine:b.parseStdoutLine,createStdoutParser:b.createStdoutParser,ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})})),h(f,x)),"parseStdoutLine"),ConfigFields:i.ConfigFields,buildAdapterConfig:i.buildAdapterConfig})}else(!o||!l)&&c&&(F$.delete(a),W2.delete(a),Xq(a),wv(i))}for(const{type:a,label:i}of e){if(Zq.has(a))continue;const o=c4.get(a);if(o&&o!==E5)continue;let l=!1;const c=o?.parseStdoutLine??E5.parseStdoutLine;wv({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Jq(a).then(h=>{h&&wv({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??yy,buildAdapterConfig:o?.buildAdapterConfig??aN})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??yy,buildAdapterConfig:o?.buildAdapterConfig??aN})}}r(grt,"syncExternalAdapters");function MW(){return[...bE]}r(MW,"listUIAdapters");function t6(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(t6,"resolveStdoutParser");function wSe(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(wSe,"appendTranscriptEntry");function brt(e,s){for(const n of s)wSe(e,n)}r(brt,"appendTranscriptEntries");function vrt(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(vrt,"truncateTranscriptLine");function yrt(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(yrt,"formatTranscriptParserError");function jrt(e,s,n,a){const i=yrt(n)||"unknown parser error",o=vrt(e);return{kind:"result",ts:s,text:bm(`Chat transcript error: ${i}. Falling back for line: ${o}`,a),inputTokens:0,outputTokens:0,cachedTokens:0,costUsd:0,subtype:"transcript_parse_error",isError:!0,errors:[]}}r(jrt,"createTranscriptParseErrorEntry");function DW(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{brt(s,i(n,a).map(c=>yZe(c,l)))}catch(c){o?.(),wSe(s,jrt(n,a,c,l))}}r(DW,"appendParsedTranscriptLine");function kSe(e){const{entries:s,chunks:n,from:a,parseLine:i,reset:o,redactionOptions:l}=e;let c=e.stdoutBuffer;for(let d=a;d<n.length;d+=1){const u=n[d];if(u.stream==="stderr"){s.push({kind:"stderr",ts:u.ts,text:bm(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:bm(u.chunk,l)});continue}const h=(c+u.chunk).split(/\r?\n/);c=h.pop()??"";for(const p of h){const f=p.trim();f&&DW({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(kSe,"foldTranscriptChunks");function NSe(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=t6(s),c=kSe({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&DW({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(NSe,"buildTranscript");var Lte=[];function wrt(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=t6(e),o=[],l="",c=Lte,d=[];const u=r(()=>{i=t6(e),o=[],l="",c=Lte},"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 NSe(f,e,s);const b=o.slice(),v=b.length-1;return v>=0&&(b[v]={...b[v]}),x&&DW({entries:b,line:x,ts:f.length>0?f[f.length-1].ts:new Date().toISOString(),parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),b},"publish");return{update(f){return f===c||(h(f)||u(),l=kSe({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(wrt,"createIncrementalTranscript");function krt({agents:e,value:s,onChange:n,disabled:a=!1,excludeAgentIds:i=[],disabledEmptyLabel:o="Reports to: N/A (CEO)",chooseLabel:l="Reports to..."}){const[c,d]=(0,m.useState)(!1),u=new Set(i),h=e.filter(b=>b.status!=="terminated"&&!u.has(b.id)),p=s?e.find(b=>b.id===s):null,f=p?.status==="terminated",x=!!(s&&!p);return(0,t.jsxs)(br,{open:c,onOpenChange:d,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsx)("button",{type:"button",className:W("inline-flex max-w-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",f&&"border-amber-600/45 bg-amber-500/5",a&&"opacity-60 cursor-not-allowed"),disabled:a,children:x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Qc,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-muted-foreground",children:"Unknown manager (stale ID)"})]}):p?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(gr,{agent:p,size:16,className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:W("min-w-0 truncate",f&&"text-amber-900 dark:text-amber-200"),children:`Reports to ${p.name}${f?" (terminated)":""}`})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Qc,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:a?o:l})]})})}),(0,t.jsxs)(dr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",s===null&&"bg-accent"),onClick:r(()=>{n(null),d(!1)},"onClick"),children:"No manager"}),f&&(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 overflow-hidden px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:[(0,t.jsx)(gr,{agent:p,size:16,className:"shrink-0 h-3 w-3"}),(0,t.jsxs)("span",{className:"min-w-0 truncate",children:["Current: ",p.name," (terminated)"]})]}),x&&(0,t.jsx)("div",{className:"px-2 py-1.5 text-xs text-muted-foreground border-b border-border mb-0.5",children:"Saved manager is missing from this organization. Choose a new manager or clear."}),h.map(b=>(0,t.jsxs)("button",{type:"button",className:W("flex items-center gap-2 w-full min-w-0 px-2 py-1.5 text-xs rounded hover:bg-accent/50 overflow-hidden",b.id===s&&"bg-accent"),onClick:r(()=>{n(b.id),d(!1)},"onClick"),children:[(0,t.jsx)(gr,{agent:b,size:16,className:"shrink-0 h-3 w-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:b.name}),(0,t.jsx)("span",{className:"text-muted-foreground ml-auto shrink-0",children:AW[b.role]??b.role})]},b.id))]})]})}r(krt,"ReportsToPicker");var Nrt="__secret_folder__:";function Srt(e){return!e||e==="active"?null:(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(Srt,"statusBadge");function SSe(e){return e.split("/").filter(s=>s.length>0)}r(SSe,"splitSecretPath$1");function vE(e){return e.join("/")}r(vE,"pathKey$1");function tC(e){return e.length>0?`/${e.join("/")}`:"/"}r(tC,"pathLabel");function Crt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(Crt,"pathStartsWith");function $te(e){return`${Nrt}${vE(e)}`}r($te,"folderValue");function _rt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=SSe(c.name);if(Crt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=vE(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=tC(u);i.set(h,{key:`folder-${h||"root"}`,value:$te(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-${vE(s)}`,value:$te(c),label:"Up one folder",title:tC(c),searchText:tC(c),kind:"back",folderPath:vE(c),pathHint:tC(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?tC(s):"Browse secrets",options:l}}r(_rt,"buildFolderGroup");function LW({secretId:e,secrets:s,recentlyUsedSecrets:n,disabled:a,onSelect:i,onCreateNew:o,triggerClassName:l,disablePortal:c}){const[d,u]=(0,m.useState)(""),h=(0,m.useMemo)(()=>s.find(j=>j.id===e)??null,[s,e]),p=!!e&&!h,f=(0,m.useMemo)(()=>d?d.split("/"):[],[d]),x=(0,m.useMemo)(()=>s.some(j=>SSe(j.name).length>1),[s]),b=(0,m.useMemo)(()=>{const j=[];p&&j.push({id:"current-missing",label:"Current",options:[{key:`missing-${e}`,value:e,label:`Missing secret (${e.slice(0,8)}…)`,title:`Missing secret (${e})`,missing:!0,disabled:!0}]});const N=(n??[]).filter(w=>w.status==="active"&&w.id!==e);return N.length>0&&j.push({id:"recently-used",label:"Recently used",options:N.map(w=>({key:`recent-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret"}))}),j.push({id:"all-secrets",label:N.length>0?"All secrets":void 0,options:s.map(w=>({key:`all-${w.id}`,value:w.id,label:w.name,title:w.name,searchText:`${w.key} ${w.name}`,secret:w,status:w.status,kind:"secret",disabled:w.status!=="active"&&w.id!==e}))}),j},[p,n,e,s]),v=(0,m.useCallback)((j,N)=>{if(!x||QFe(j))return N;const w=_rt(s,f,e),k=N.filter(S=>S.id==="current-missing"||S.id==="recently-used");return w.options.length>0?[...k,w]:k},[f,x,e,s]);return(0,t.jsx)(Ky,{value:e||"",groups:b,onValueChange:r((j,N)=>{if(N.folderPath!==void 0)return u(N.folderPath),!1;u(""),i(j)},"onValueChange"),deriveGroups:v,disabled:a,disablePortal:c,placeholder:"Select secret…",searchPlaceholder:"Search secrets…",emptyMessage:"No matching secrets",triggerClassName:W("h-(--sz-34px) min-h-(--sz-34px) font-mono text-sm",p&&"border-destructive text-destructive",h&&h.status!=="active"&&"border-amber-500/60",l),renderValue:r(j=>{if(!j)return(0,t.jsx)("span",{className:"text-muted-foreground",children:"Select secret…"});if(j.missing)return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5 text-destructive",children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0"}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:j.label})]});const N=j.status&&j.status!=="active";return(0,t.jsxs)("span",{className:"flex w-full min-w-0 items-center gap-1.5",title:j.title,children:[(0,t.jsx)(Si,{className:W("size-3.5 shrink-0",N?"text-amber-600":"text-muted-foreground")}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:j.label}),N?(0,t.jsxs)("span",{className:"text-amber-600",children:["(",j.status,")"]}):null]})},"renderValue"),renderOption:r((j,{selected:N})=>{if(j.kind==="folder"||j.kind==="back"){const w=j.kind==="back"?uqe:Jl;return(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",title:j.title??j.label,children:[(0,t.jsx)(w,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("truncate text-sm",N&&"font-medium"),children:j.label}),j.pathHint?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:j.pathHint}):null]})]})}return(0,t.jsxs)("span",{className:W("flex min-w-0 flex-1 items-center gap-1.5",j.disabled&&"opacity-60"),title:j.title??j.label,children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,t.jsx)("span",{className:W("min-w-0 truncate font-mono text-sm",N&&"font-medium"),children:j.label}),j.pathHint&&j.pathHint!==j.label?(0,t.jsx)("span",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground",children:j.pathHint}):null]}),Srt(j.status)]})},"renderOption"),createItem:o?{render:r(j=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(yn,{className:"size-3.5 shrink-0"}),j.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",j.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(j=>o(j),"onSelect")}:void 0})}r(LW,"SecretPicker");var Irt=/^[a-z][a-z0-9_]*$/,Ote="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 CSe({mode:e,initialName:s,initialValue:n,existingSecretNames:a,onCancel:i,onSubmit:o}){const[l,c]=(0,m.useState)(s),[d,u]=(0,m.useState)(n),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(!1),[b,v]=(0,m.useState)(null),[j,N]=(0,m.useState)(!1),w=l.trim(),k=w?Irt.test(w)?a?.some(T=>T.toLowerCase()===w)?"A secret with this name already exists":null:"Use lowercase letters, digits and _":j?"Name is required":null,S=d.length===0&&j?"Value is required":null,C=!f&&w.length>0&&d.length>0&&!k;async function I(){if(N(!0),!!C){x(!0),v(null);try{await o(w,d)}catch(T){v(T instanceof Error?T.message:"Failed to create secret"),x(!1)}}}r(I,"handleSubmit");const R=e==="create"?"Create & bind":"Store & bind";return(0,t.jsxs)("div",{className:"w-72 space-y-3",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(XFe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(ZFe,{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(Ote,k&&"border-destructive focus-visible:ring-destructive/40"),value:l,autoFocus:!0,spellCheck:!1,placeholder:"secret_name","aria-label":"Secret name","aria-invalid":k?!0:void 0,onChange:r(T=>c(T.target.value),"onChange"),onBlur:r(()=>N(!0),"onBlur"),onKeyDown:r(T=>{T.key==="Enter"&&(T.preventDefault(),I())},"onKeyDown")}),k?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:k}):null]}),(0,t.jsxs)("label",{className:"block space-y-1",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium text-muted-foreground",children:"Value"}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)("input",{className:W(Ote,"pr-8",S&&"border-destructive focus-visible:ring-destructive/40"),type:h?"text":"password",value:d,readOnly:e==="store",spellCheck:!1,placeholder:e==="create"?"value":void 0,"aria-label":"Secret value","aria-invalid":S?!0:void 0,onChange:e==="create"?T=>u(T.target.value):void 0}),(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground hover:text-foreground","aria-label":h?"Hide value":"Show value",onClick:r(()=>p(T=>!T),"onClick"),children:h?(0,t.jsx)(Mm,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Ed,{className:"h-3.5 w-3.5"})})]}),S?(0,t.jsx)("span",{className:"block text-(length:--text-micro) text-destructive",children:S}):null]}),b?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-destructive",children:b}):null,(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 pt-0.5",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",onClick:i,disabled:f,children:"Cancel"}),(0,t.jsxs)(L,{type:"button",size:"sm",onClick:r(()=>{I()},"onClick"),disabled:!C,children:[f?(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}):null,R]})]})]})}r(CSe,"SecretPopoverForm");function _Se(e){return(0,t.jsx)(CSe,{mode:"create",...e})}r(_Se,"CreateSecretPopover");function Art(e){return(0,t.jsx)(CSe,{mode:"store",...e})}r(Art,"ConvertToSecretPopover");var Trt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,Rrt=[/^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 Ert(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(Ert,"looksHighEntropy");function Prt(e,s){return s?Trt.test(e)||Rrt.some(n=>n.test(s))?!0:Ert(s):!1}r(Prt,"isSensitiveEnv");var Fte=0;function Mrt(){return Fte+=1,`env-row-${Fte}`}r(Mrt,"nextRowId");function Bx(e="text"){return{id:Mrt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Bx,"emptyRow");function Drt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(Drt,"isSecretRef");function Lrt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(Lrt,"isPlainObj");function $rt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r($rt,"isUserSecretRef");function B$(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Bx(),name:s,textValue:n};if(Drt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Bx(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if($rt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Bx(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return Lrt(n)?{...Bx(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Bx(),name:s}})}r(B$,"rowsFromValue");function yE(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(yE,"valueFromRows");var Bte="CLAUDE_CODE_OAUTH_TOKEN";function Vw(){return yE([{...Bx("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(Vw,"buildFixedClaudeOAuthBinding");var Ort=/^[A-Za-z_][A-Za-z0-9_]*$/;function Frt(e,s,n){const a=e.trim();if(!a)return null;if(!Ort.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(Frt,"validateName");function Brt(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(Brt,"computeDuplicateNames");function zrt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:M5(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(zrt,"planSourceSwitch");function ISe(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(ISe,"computeRowHealth");function ASe(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(ASe,"computeUserSecretRowHealth");function M5(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(M5,"secretNameFromKey");function M1(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(M1,"envKeyFromSecretName");var qrt="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",zte="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function Urt({row:e,isLast:s,secrets:n,userSecretDefinitions:a,recentlyUsedSecrets:i,disabled:o,nameIssue:l,showNameIssue:c,dirtyFields:d,onPatch:u,onRemove:h,onNameBlur:p,onNamePaste:f,onEnterInValueLast:x,onCreateSecret:b,onToast:v,focusRequest:j,onFocusConsumed:N}){const w=(0,m.useRef)(null),k=(0,m.useRef)(null),S=(0,m.useRef)(null),[C,I]=(0,m.useState)(null),[R,T]=(0,m.useState)(!1),[A,D]=(0,m.useState)(null),M=ISe(e,n)??ASe(e,a),B=e.source==="secret"?n.find(X=>X.id===e.secretId)??null:null,E=(a?.length??0)>0,z=e.source==="text"&&!e.sensitiveDismissed&&Prt(e.name,e.textValue);(0,m.useEffect)(()=>{j&&(j==="name"?w.current?.focus():e.source==="text"?k.current?.focus():e.source==="secret"?S.current?.querySelector("[role=combobox]")?.focus():S.current?.querySelector("select,input")?.focus(),N())},[j,N,e.source]),(0,m.useEffect)(()=>{if(!A)return;const X=window.setTimeout(()=>D(null),5e3);return()=>window.clearTimeout(X)},[A]);function $(X){if(X==="user_secret"){if(e.source==="user_secret")return;u({source:"user_secret",secretId:"",version:"latest"}),window.setTimeout(()=>S.current?.querySelector("select,input")?.focus(),0);return}const re=zrt(e,X);switch(re.kind){case"noop":return;case"open-store":{const{name:oe,value:G}=re;window.setTimeout(()=>I({mode:"store",name:oe,value:G}),0);return}case"to-secret":u({source:"secret",userSecretKey:"",required:!0}),window.setTimeout(()=>{S.current?.querySelector("[role=combobox]")?.focus()},0);return;case"to-text":re.undoFrom&&D(re.undoFrom),u({source:"text",secretId:"",userSecretKey:"",required:!0,version:"latest"}),window.setTimeout(()=>k.current?.focus(),0);return}}r($,"switchSource");async function q(X,re){const oe=await b(X,re);u({source:"secret",secretId:oe.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${oe.name} created`),I(null)}r(q,"submitSecretPopover");function U(){const X=M5(e.name)||"secret",{textValue:re}=e;window.setTimeout(()=>I({mode:"store",name:X,value:re}),0)}r(U,"openStoreAsSecret");const O=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",K=`${e.id}-name-error`,H=`${e.id}-health`,Z=d.name||d.value,se=B?Math.max(0,B.latestVersion):0,ne=e.version==="latest"?"latest":`v${e.version}`,fe=e.version!=="latest";return(0,t.jsxs)("div",{className:W("group/row grid grid-cols-(--gtc-13) items-start gap-x-1.5 gap-y-1 rounded-md px-1 py-1","@[40rem]/env:grid-cols-(--gtc-14) @[40rem]/env:items-center",Z&&"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(qrt,d.name&&"border-amber-500/70 bg-amber-500/10 focus-visible:ring-amber-500/40",c&&l?.level==="error"&&"border-destructive focus-visible:ring-destructive/40",c&&l?.level==="warn"&&"border-amber-500 focus-visible:ring-amber-500/40"),placeholder:"KEY",value:e.name,spellCheck:!1,disabled:o,"aria-label":"Variable name","aria-invalid":c&&l?.level==="error"?!0:void 0,"aria-describedby":c&&l?K:void 0,onChange:r(X=>u({name:X.target.value}),"onChange"),onBlur:p,onPaste:r(X=>{e.name||f(X.clipboardData.getData("text"))&&X.preventDefault()},"onPaste"),onKeyDown:r(X=>{X.key==="Enter"&&(X.preventDefault(),e.source==="text"?k.current?.focus():S.current?.querySelector("[role=combobox],select,input")?.focus())},"onKeyDown")})}),(0,t.jsxs)("div",{className:"col-span-2 col-start-1 row-start-2 min-w-0 @[40rem]/env:col-span-1 @[40rem]/env:col-start-2 @[40rem]/env:row-start-1",children:[(0,t.jsxs)(br,{open:C!==null,onOpenChange:r(X=>{X||I(null)},"onOpenChange"),children:[(0,t.jsx)(_z,{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)(Zr,{children:[(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)(Xr,{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)(Vqe,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(Si,{className:"size-3.5"}):(0,t.jsx)(Ph,{className:"size-3.5"}),(0,t.jsx)(nn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(Un,{side:"top",children:O})]}),(0,t.jsxs)(ea,{align:"start",className:"w-56",children:[(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("text"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"Text value"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Store the value inline as plain text."})]}),(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"Organization secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve a stored organization secret at run start."})]}),(0,t.jsxs)(ls,{className:"flex-col items-start gap-0.5",onSelect:r(()=>$("user_secret"),"onSelect"),children:[(0,t.jsx)("span",{className:"text-sm",children:"User secret"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"Resolve the responsible user's own value at run start."})]})]})]}),e.source==="text"?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("input",{ref:k,className:zte,placeholder:"value",value:e.textValue,type:z?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(X=>u({textValue:X.target.value}),"onChange"),onKeyDown:r(X=>{X.key==="Enter"&&s&&(X.preventDefault(),x())},"onKeyDown")}),z?(0,t.jsxs)("div",{className:"flex shrink-0 items-stretch border-l border-border",children:[(0,t.jsxs)("button",{type:"button",onClick:U,disabled:o,className:"flex items-center gap-1 px-2 text-(length:--text-micro) text-amber-700 hover:bg-amber-500/10 dark:text-amber-400",title:"This value looks sensitive — store it as a secret",children:[(0,t.jsx)(bc,{className:"size-3.5"}),(0,t.jsx)("span",{className:"hidden @[30rem]/env:inline",children:"Store as secret"})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>u({sensitiveDismissed:!0}),"onClick"),disabled:o,"aria-label":"Dismiss sensitive-value suggestion",title:"Dismiss — keep this value as plain text",className:"flex items-center px-1.5 text-amber-700/60 hover:bg-amber-500/10 hover:text-amber-700 dark:text-amber-400/60 dark:hover:text-amber-400",children:(0,t.jsx)(Fn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(LW,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(X=>u({secretId:X,version:"latest"}),"onSelect"),onCreateNew:r(X=>I({mode:"create",name:M5(X)||X.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",B&&B.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),B&&B.status==="active"?(0,t.jsxs)(br,{open:R,onOpenChange:T,children:[(0,t.jsx)(_z,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(X=>{X.preventDefault(),X.stopPropagation(),T(re=>!re)},"onClick"),"aria-label":"Version",className:W("absolute right-8 top-1/2 z-10 -translate-y-1/2 rounded px-1.5 py-0.5 text-(length:--text-nano) font-medium",fe?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:ne})}),(0,t.jsxs)(dr,{align:"end",className:"w-44 p-1",role:"radiogroup","aria-label":"Secret version",children:[(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version==="latest",onClick:r(()=>{u({version:"latest"}),T(!1)},"onClick"),className:W("flex w-full items-center justify-between rounded px-2 py-1.5 text-sm hover:bg-accent",e.version==="latest"&&"font-medium"),children:["latest ",(0,t.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:"(recommended)"})]}),Array.from({length:se},(X,re)=>se-re).filter(X=>X>0).map(X=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===X,onClick:r(()=>{u({version:X}),T(!1)},"onClick"),className:W("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===X&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",X]},X))]})]}):null]}):(0,t.jsxs)("div",{className:"grid min-w-0 flex-1 grid-cols-(--gtc-13)",children:[E?(0,t.jsxs)("select",{"aria-label":"User secret",value:e.userSecretKey,disabled:o,onChange:r(X=>{const re=X.target.value,oe=a?.find(G=>G.key===re);u({userSecretKey:re,...oe&&!e.name.trim()?{name:oe.key.toUpperCase()}:{}})},"onChange"),className:"min-w-0 bg-transparent px-2 py-1.5 text-sm font-mono outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"",children:"Select user secret..."}),e.userSecretKey&&!a?.some(X=>X.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(X=>(0,t.jsxs)("option",{value:X.key,children:[X.name,X.status!=="active"?` (${X.status})`:""]},X.id))]}):(0,t.jsx)("input",{className:zte,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(X=>u({userSecretKey:X.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(X=>u({required:X.target.value==="required"}),"onChange"),className:"border-l border-border bg-transparent px-2 py-1.5 text-xs font-medium text-muted-foreground outline-none disabled:pointer-events-none",children:[(0,t.jsx)("option",{value:"required",children:"Required"}),(0,t.jsx)("option",{value:"optional",children:"Optional"})]})]})]})}),(0,t.jsx)(dr,{align:"start",className:"w-auto p-3",onInteractOutside:r(X=>{const re=X.detail.originalEvent.target;re&&S.current?.contains(re)&&X.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(Art,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):C?.mode==="create"?(0,t.jsx)(_Se,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(X=>X.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):null})]}),M?(0,t.jsx)("p",{id:H,role:"status",className:W("mt-0.5 text-(length:--text-micro)",M.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:M.message}):null,A?(0,t.jsxs)("p",{className:"mt-0.5 inline-flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:["Reverted to text —"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2 hover:text-primary",onClick:r(()=>{u({source:"secret",secretId:A.secretId,version:A.version,textValue:""}),D(null)},"onClick"),children:"Undo"})]}):null]}),c&&l?(0,t.jsx)("p",{id:K,className:W("col-span-2 col-start-1 row-start-3 min-w-0 text-(length:--text-micro) @[40rem]/env:col-span-2 @[40rem]/env:row-start-2",l.level==="error"?"text-destructive":"text-amber-600 dark:text-amber-400"),children:l.message}):null,(0,t.jsxs)("div",{className:"col-start-2 row-start-1 flex items-center justify-end gap-0.5 self-start @[40rem]/env:col-start-3 @[40rem]/env:self-center",children:[e.source==="text"&&!z&&(e.name.trim()||e.textValue)?(0,t.jsxs)(Zr,{children:[(0,t.jsx)(Xr,{asChild:!0,disabled:o,children:(0,t.jsx)("button",{type:"button","aria-label":"More actions",className:"rounded p-1 text-muted-foreground opacity-100 hover:bg-accent hover:text-foreground @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100",children:(0,t.jsx)(Ri,{className:"size-4"})})}),(0,t.jsx)(ea,{align:"end",children:(0,t.jsx)(ls,{onSelect:r(()=>{window.setTimeout(U,0)},"onSelect"),children:"Store as secret…"})})]}):null,(0,t.jsx)("button",{type:"button",onClick:h,disabled:o,"aria-label":`Remove ${e.name.trim()||"variable"}`,className:"rounded p-1 text-muted-foreground opacity-100 hover:bg-destructive/10 hover:text-destructive @[40rem]/env:opacity-0 @[40rem]/env:group-hover/row:opacity-100 @[40rem]/env:group-focus-within/row:opacity-100",children:(0,t.jsx)(Fn,{className:"size-4"})})]})]})}r(Urt,"EnvironmentVariableRow");var Krt=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function Wrt(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(Wrt,"stripInlineComment");function Vrt(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 Wrt(s).trim()}r(Vrt,"unquote");function Hrt(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=Krt.exec(a);if(!i)continue;const o=i[1],l=Vrt(i[2]);s.push({key:o,value:l})}return s}r(Hrt,"parseDotenv");var Grt=["PAPERCLIP_"],Qrt="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 s6(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(s6,"normalizedEnvEntries");function sC(e){return JSON.stringify(s6(e))}r(sC,"normalizedEnvKey");var z$=3;function q$(e){const s=e.slice(0,z$).join(", ");return e.length>z$?`${s} +${e.length-z$} more`:s}r(q$,"formatChangedNames");function qte(e){return e.map(s=>({...s}))}r(qte,"cloneRows");function Yrt(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(Yrt,"rowDirtyFields");var jy=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=Grt,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=Xc(),b=(0,m.useRef)(null),[v,j]=(0,m.useState)(()=>B$(s)),N=(0,m.useRef)(v),[w,k]=(0,m.useState)(()=>qte(v)),S=(0,m.useMemo)(()=>sC(s),[]),C=(0,m.useRef)(S),I=(0,m.useRef)(S),R=(0,m.useRef)(null),[T,A]=(0,m.useState)(S),[D,M]=(0,m.useState)(()=>new Set(B$(s).map(ie=>ie.name.trim()).filter(Boolean))),[B,E]=(0,m.useState)(null);(0,m.useEffect)(()=>{N.current=v},[v]);function z(ie,ue=N.current){C.current=ie,A(ie),k(qte(ue))}r(z,"markCommitted");function $(ie){M(ue=>{const ke=new Set(ue);for(const be of ie){const Ie=be.name.trim();Ie&&ke.add(Ie)}return ke})}r($,"touchCommittedNames");function q(ie){const ue=B$(ie);return j(ue),$(ue),ue}r(q,"adoptExternalValue"),(0,m.useEffect)(()=>{const ie=sC(s);if(ie===I.current)return;I.current=ie;const ue=sC(yE(N.current)),ke=ue!==C.current,be=R.current===ie;if(be&&(R.current=null),!ke){z(ie,q(s));return}(be||ue===ie)&&($(N.current),z(ie))},[s]);const U=(0,m.useMemo)(()=>yE(v),[v]),O=(0,m.useMemo)(()=>sC(U),[U]),K=O!==T;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const H=(0,m.useMemo)(()=>{const ie=new Map(s6(yE(w)).map(([Ie,Ue])=>[Ie,JSON.stringify(Ue)])),ue=new Map(s6(U).map(([Ie,Ue])=>[Ie,JSON.stringify(Ue)])),ke=[],be=[];for(const[Ie,Ue]of ue)ie.has(Ie)?ie.get(Ie)!==Ue&&be.push(Ie):ke.push(Ie);return{added:ke,changed:be,removed:[...ie.keys()].filter(Ie=>!ue.has(Ie))}},[w,U]),Z=(0,m.useMemo)(()=>{const ie=[];return H.added.length>0&&ie.push(`New: ${q$(H.added)}`),H.changed.length>0&&ie.push(`Edited: ${q$(H.changed)}`),H.removed.length>0&&ie.push(`Removed: ${q$(H.removed)}`),ie.join(" · ")},[H]);(0,m.useEffect)(()=>{if(c||!K)return;function ie(ue){ue.preventDefault(),ue.returnValue=""}return r(ie,"handleBeforeUnload"),window.addEventListener("beforeunload",ie),()=>window.removeEventListener("beforeunload",ie)},[c,K]);const se=(0,m.useCallback)(()=>c||!K?null:(R.current=O,(0,hp.flushSync)(()=>{n(U)}),U??{}),[c,U,O,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:se}),[se]),(0,m.useEffect)(()=>{const ie=b.current?.closest("form");if(!ie)return;function ue(){se()}return r(ue,"handleSubmit"),ie.addEventListener("submit",ue,!0),()=>ie.removeEventListener("submit",ue,!0)},[se]),(0,m.useEffect)(()=>{const ie=b.current;if(!ie)return;const ue=ie;function ke(be){const Ie=be.target;if(!(Ie instanceof Element)||ue.contains(Ie))return;const Ue=Ie.closest("button");if(!Ue||Ue.disabled)return;const at=`${Ue.getAttribute("aria-label")??""} ${Ue.textContent??""}`;(Ue.type==="submit"||/\b(save|create|update|test|import)\b/i.test(at))&&se()}return r(ke,"handleDocumentClick"),document.addEventListener("click",ke,!0),()=>document.removeEventListener("click",ke,!0)},[se]);function ne(ie){j(ie)}r(ne,"updateDraft");function fe(ie,ue){ne(v.map(ke=>ke.id===ie?{...ke,...ue}:ke))}r(fe,"patchRow");function X(ie){ne(v.filter(ue=>ue.id!==ie))}r(X,"removeRow");function re(){const ie=Bx();j([...v,ie]),E({rowId:ie.id,field:"name"})}r(re,"addRow");function oe(ie){const ue=v.find(ke=>ke.id===ie)?.name.trim();ue&&M(ke=>{if(ke.has(ue))return ke;const be=new Set(ke);return be.add(ue),be})}r(oe,"markTouched");function G(ie,ue){const ke=Hrt(ie);if(ke.length===0)return!1;const be=v.filter(Ie=>Ie.id!==ue).map(Ie=>({...Ie}));for(const{key:Ie,value:Ue}of ke){const at=be.find(dt=>dt.name.trim()===Ie);at?(at.name=Ie,at.source="text",at.textValue=Ue,at.secretId="",at.sensitiveDismissed=!1,at.userSecretKey="",at.required=!0):be.push({...Bx(),name:Ie,textValue:Ue})}return ne(be),x?.pushToast({title:`Imported ${ke.length} variable${ke.length===1?"":"s"}`,tone:"success"}),!0}r(G,"bulkImport");function Y(ie){const ue=v.map(Ie=>({...Ie})),ke=ue[ue.length-1];let be;ke&&!ke.name&&!ke.textValue&&!ke.secretId&&!ke.userSecretKey?be=ke:(be=Bx(),ue.push(be)),be.source="secret",be.secretId=ie.id,be.version="latest",be.name||(be.name=M1(ie.name)),ne(ue)}r(Y,"bindRecentSecret");function Q(){K&&(R.current=O,n(U))}r(Q,"saveDraft");function te(){R.current=null,I.current=sC(s);const ie=q(s);z(I.current,ie)}r(te,"revertDraft");const ae=(0,m.useMemo)(()=>Brt(v),[v]),le=(0,m.useMemo)(()=>v.reduce((ie,ue)=>ISe(ue,a)||ASe(ue,i)?ie+1:ie,0),[v,a,i]),he=(0,m.useMemo)(()=>{const ie=new Set(v.filter(ue=>ue.source==="secret"&&ue.secretId).map(ue=>ue.secretId));return(l??[]).filter(ue=>ue.status==="active"&&!ie.has(ue.id)).slice(0,8)},[l,v]),ce=v.length>0,ge=u===void 0?Qrt:u,me=(0,m.useMemo)(()=>new Map(w.map(ie=>[ie.id,ie])),[w]);return(0,t.jsx)(Pd,{children:(0,t.jsxs)("div",{ref:b,className:"@container/env space-y-2",children:[le>1?(0,t.jsxs)("p",{className:"inline-flex items-center gap-1.5 text-(length:--text-micro) font-medium text-amber-700 dark:text-amber-400",children:[(0,t.jsx)(Zi,{className:"size-3.5"}),le," bindings need attention"]}):null,ce?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-(--gtc-14)",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Value"}),(0,t.jsx)("span",{})]}),v.map((ie,ue)=>{const ke=Frt(ie.name,ae,d),be=D.has(ie.name.trim());return(0,t.jsx)(Urt,{row:ie,isLast:ue===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:ke,showNameIssue:be,dirtyFields:Yrt(ie,me.get(ie.id)),onPatch:r(Ie=>fe(ie.id,Ie),"onPatch"),onRemove:r(()=>X(ie.id),"onRemove"),onNameBlur:r(()=>oe(ie.id),"onNameBlur"),onNamePaste:r(Ie=>G(Ie,ie.id),"onNamePaste"),onEnterInValueLast:re,onCreateSecret:o,onToast:r(Ie=>x?.pushToast({title:Ie,tone:"success"}),"onToast"),focusRequest:B?.rowId===ie.id?B.field:null,onFocusConsumed:r(()=>E(null),"onFocusConsumed")},ie.id)})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No environment variables"}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[(0,t.jsxs)("button",{type:"button",onClick:re,disabled:c,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(yn,{className:"size-3.5"}),"Add variable"]}),he.length>0&&!c?(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5",children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Si,{className:"size-3"}),"Recently used:"]}),he.map(ie=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>Y(ie),"onClick"),className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",title:`Bind ${ie.name}`,children:["+ ",ie.name]},ie.id))]}):null]}),K&&!c&&!p?(0,t.jsxs)("div",{role:"status",className:"mt-3 flex w-full flex-col gap-3 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-3 text-amber-950 shadow-sm dark:bg-amber-500/15 dark:text-amber-100 @[34rem]/env:flex-row @[34rem]/env:items-center @[34rem]/env:justify-between",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)("span",{className:"size-2 rounded-full bg-amber-500 shadow-(--shadow-extract-13)"}),(0,t.jsx)("span",{children:"Unsaved changes"})]}),Z?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:Z,children:Z}):null]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",onClick:te,className:"inline-flex h-9 items-center gap-1.5 rounded-md border border-amber-500/30 bg-background px-3 text-sm font-medium text-foreground transition-colors hover:bg-amber-500/10 dark:bg-background/80",children:[(0,t.jsx)(Ci,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Q,className:"inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90",children:[(0,t.jsx)(Cf,{className:"size-4"}),"Save"]})]})]}):null,ge?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ge}):null,v.some(ie=>ie.source==="user_secret"&&ie.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Ph,{className:"mt-0.5 size-3 shrink-0"}),(0,t.jsx)("span",{children:"User secrets resolve from the user responsible for the run. Required bindings fail until that user sets their value under Secrets → My secrets."})]}):null]})})},"EnvironmentVariablesEditor")),Jrt="env.",hA="access.",n6=/^[A-Za-z_][A-Za-z0-9_]*$/;function TSe(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(TSe,"deliveryModeForConfigPath");function RSe(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(RSe,"deliveryModeLabel");function Xrt(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(Xrt,"deliveryModeDescription");function ESe(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(ESe,"aliasFromConfigPath");function Zrt(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(Zrt,"consumerTypeLabel");var eat={numeric:!0,sensitivity:"base"};function GC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(GC,"getSecretPathRowName");function cN(e){return e.split("/").filter(s=>s.length>0)}r(cN,"splitSecretPath");function U$(e){return cN(e).join("/")}r(U$,"normalizeSecretPath");function Ute(e,s){return s.every((n,a)=>e[a]===n)}r(Ute,"startsWithSegments");function Kte(e,s){return e.localeCompare(s,void 0,eat)}r(Kte,"compareNames");function tat(e,s){const n=cN(s),a=e.map(c=>({row:c,name:GC(c),segments:cN(GC(c))})),i=new Set,o=[];for(const c of a){if(!Ute(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(!Ute(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)=>Kte(c.name,d.name)),o.sort((c,d)=>Kte(GC(c),GC(d))),{folders:l,secrets:o}}r(tat,"buildSecretPathListing");function sat(e){const s=cN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(sat,"buildSecretPathBreadcrumbs");function nat(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(nat,"validateSecretFolderSegment");function O_({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(O_,"SecretPathName");function rat(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(rat,"fingerprintLabel");function PSe({fingerprint:e,length:s,className:n}){const{pushToast:a}=da(),i=rat(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(Oz,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{fa(o).then(()=>a({title:"Fingerprint copied",tone:"success"})).catch(()=>a({title:"Couldn’t copy fingerprint",tone:"error"}))},"onClick"),title:`Copy full digest — ${o}`,className:W("inline-flex items-center gap-1 font-mono hover:text-foreground",n),children:[(0,t.jsx)(Oz,{className:"size-3 shrink-0"}),i,(0,t.jsx)(Ir,{className:"size-3 shrink-0 opacity-60"})]})}r(PSe,"FingerprintChip");function $W({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($W,"ProposalJustification");function F_({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)(gr,{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(F_,"AgentRefChip");function OW({configPath:e}){const s=TSe(e),n=s==="env",a=s==="api";return(0,t.jsxs)(ct,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal",n&&"border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",a&&"border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",!n&&!a&&"border-border bg-muted/40 text-muted-foreground"),children:[n?(0,t.jsx)(Qve,{className:"size-3"}):a?(0,t.jsx)(TM,{className:"size-3"}):null,RSe(s)]})}r(OW,"DeliveryBadge$1");function FW({className:e}){return(0,t.jsxs)(ct,{variant:"outline",className:W("h-5 gap-1 px-1.5 text-(length:--text-nano) font-medium","border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",e),children:[(0,t.jsx)(bc,{className:"size-3"})," Proposed"]})}r(FW,"ProposedBadge");function d4(e){return ESe(e.configPath)}r(d4,"bindingEnvKey");function BW(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(BW,"bindingSecretLabel");function Wte(e){return e instanceof dn?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Wte,"readableError");function MSe(e,s=[]){const n=Pt(),{pushToast:a}=da(),[i,o]=(0,m.useState)(null),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(null),f=(0,m.useCallback)(()=>{e&&(n.invalidateQueries({queryKey:["secret-proposals",e]}),n.invalidateQueries({queryKey:P.secrets.list(e)}))},[e,n]),x=je({mutationFn:r(w=>{const{proposal:k}=w;if(k.kind==="secret"){const S=w.folder.trim()?`${w.folder.trim().replace(/\/+$/,"")}/${w.leaf.trim()}`:w.leaf.trim();return yr.approveProposal(e,k.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return yr.approveProposal(e,k.id,{cascade:w.cascade||void 0})},"mutationFn"),onSuccess:r(w=>{a({title:w.kind==="secret"?"Secret approved":"Binding approved",body:w.kind==="secret"?w.proposedName??"Secret created":`${w.target?.name??"Agent"} · ${d4(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Wte(w)),"onError")}),b=je({mutationFn:r(({proposal:w,reason:k})=>yr.rejectProposal(e,w.id,{reason:k.trim()}),"mutationFn"),onSuccess:r(w=>{a({title:"Proposal rejected",body:w.kind==="secret"?w.proposedName??void 0:void 0,tone:"info"}),c(null),u(""),p(null),f()},"onSuccess"),onError:r(w=>p(Wte(w)),"onError")}),v=(0,m.useCallback)(w=>{p(null);const k=(w.proposedName??"").split("/"),S=k.pop()??"";o({proposal:w,folder:k.join("/"),leaf:S,description:w.proposedDescription??"",providerConfigId:s.find(C=>C.provider==="local_encrypted"&&C.isDefault)?.id??"",cascade:!!w.secretProposalId})},[s]),j=(0,m.useCallback)(w=>{p(null),u(""),c(w)},[]),N=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(aat,{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)(oat,{proposal:l,reason:d,error:h,pending:b.isPending,onReasonChange:u,onCancel:r(()=>{c(null),u(""),p(null)},"onCancel"),onConfirm:r(()=>l&&b.mutate({proposal:l,reason:d}),"onConfirm")})]});return{requestApprove:v,requestReject:j,isBusy:x.isPending||b.isPending,dialogs:N}}r(MSe,"useProposalReview");function aat({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)(Ys,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Js,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(jn,{children:c?"The value is created as the proposing agent recorded it. Re-folder or rename it before it lands.":"Grant the target agent access to this secret. This runs with your permissions."})]}),(0,t.jsxs)("div",{className:"space-y-1.5 rounded-md border border-border bg-muted/30 p-2.5 text-xs",children:[(0,t.jsxs)("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[(0,t.jsx)("span",{children:"Proposed by"}),(0,t.jsx)(F_,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)($W,{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)(Qs,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(ht,{id:"approve-folder",value:e.folder,onChange:r(p=>i({...e,folder:p.target.value}),"onChange"),placeholder:"dev/github",className:"font-mono text-xs"})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Qs,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(ht,{id:"approve-name",value:e.leaf,onChange:r(p=>i({...e,leaf:p.target.value}),"onChange"),placeholder:"client-secret",autoFocus:!0,"aria-invalid":!e.leaf.trim(),className:"font-mono text-xs"})]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground",children:["Lands as"," ",d?(0,t.jsx)(O_,{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)(Qs,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(ht,{id:"approve-description",value:e.description,onChange:r(p=>i({...e,description:p.target.value}),"onChange"),placeholder:"Optional"})]}),u.length>0?(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Qs,{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)(PSe,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(iat,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"ghost",onClick:o,disabled:n,children:"Cancel"}),(0,t.jsx)(L,{onClick:l,disabled:n||!h,children:n?"Approving…":c?"Approve & create":e.cascade?"Approve secret & bind":"Approve binding"})]})]}):null})})}r(aat,"ApproveDialog");function iat({draft:e,onChange:s}){const{proposal:n}=e,a=BW(n),i=d4(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)(F_,{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)(OW,{configPath:n.configPath}),(0,t.jsx)("code",{className:"font-mono text-xs",children:i||n.configPath})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Secret"}),(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,t.jsx)(Si,{className:"size-3.5 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:a.name}),a.pending?(0,t.jsx)(FW,{}):null]})]})]}),n.secretProposalId?(0,t.jsxs)("label",{className:"flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 p-2.5 text-xs",children:[(0,t.jsx)(pi,{checked:e.cascade,onCheckedChange:r(o=>s({...e,cascade:o===!0}),"onCheckedChange"),className:"mt-0.5","aria-label":"Also approve the proposed secret"}),(0,t.jsxs)("span",{className:"text-foreground/90",children:["Also approve the proposed secret"," ",(0,t.jsx)("span",{className:"font-medium",children:a.name})," and create it in the same step. The binding can’t land without it."]})]}):null]})}r(iat,"BindingApproveBody");function oat({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(Ys,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Js,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Reject proposal"}),(0,t.jsxs)(jn,{children:["The reason is sent back to"," ",(0,t.jsx)(F_,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Qs,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Cn,{id:"reject-reason",value:s,onChange:r(d=>i(d.target.value),"onChange"),rows:3,autoFocus:!0,placeholder:"Why is this being rejected?"})]}),n?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:n}):null,(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"ghost",onClick:o,disabled:a,children:"Cancel"}),(0,t.jsx)(L,{variant:"destructive",onClick:l,disabled:a||!c,children:a?"Rejecting…":"Reject"})]})]}):null})})}r(oat,"RejectDialog");function DSe({proposal:e,onApprove:s,onReject:n,disabled:a,size:i="sm"}){const o=!e.viewerCanApprove,l=i==="xs"?"h-7 px-2 text-xs":"",c=(0,t.jsx)(L,{size:"sm",className:l,disabled:a||o,onClick:r(()=>s(e),"onClick"),children:"Approve"});return(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[o?(0,t.jsx)(Pd,{children:(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)(Un,{className:"max-w-72",children:e.approveBlockReason??"You don’t have permission to approve this."})]})}):c,(0,t.jsx)(L,{size:"sm",variant:"outline",className:l,disabled:a,onClick:r(()=>n(e),"onClick"),children:"Reject"})]})}r(DSe,"ProposalActions");function LSe(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(LSe,"asRecord$16");function $Se(e){const s=LSe(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($Se,"readSecretRef");function lat(e){const s=LSe(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=$Se(i);o&&n.push({name:a,...o})}return n}r(lat,"parseEnvSecretRefs");function cat(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=$Se(a);i&&s.push({name:n.slice(hA.length),...i})}return s}r(cat,"parseAccessGrants");function dat(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(dat,"summarizeAgentBindings");var Vte=0;function OSe(){return Vte+=1,`access-row-${Vte}`}r(OSe,"nextAccessRowId");function K$(e){return e.map(s=>({id:OSe(),alias:s.name,secretId:s.secretId,version:s.version}))}r(K$,"entriesToRows");function Hte(e){const s={};for(const n of e){const a=n.alias.trim();!a||!n6.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(Hte,"rowsToAccessMap");function Gte(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(Gte,"normalizeAccessMapKey");function Qte({mode:e}){return e==="env"?(0,t.jsxs)(ct,{variant:"outline",className:"h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300",children:[(0,t.jsx)(Qve,{className:"size-3"})," Env var"]}):(0,t.jsxs)(ct,{variant:"outline",className:"h-5 gap-1 px-1.5 text-(length:--text-nano) font-normal border-violet-500/30 bg-violet-500/10 text-violet-700 dark:text-violet-300",children:[(0,t.jsx)(TM,{className:"size-3"})," API access"]})}r(Qte,"DeliveryBadge");function uat({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter(B=>B.kind==="binding"),[o]),u=(0,m.useMemo)(()=>lat(e),[e]),h=(0,m.useMemo)(()=>cat(e),[e]),p=(0,m.useMemo)(()=>dat(u,h),[u,h]),f=(0,m.useMemo)(()=>Hte(K$(h)),[h]),x=(0,m.useMemo)(()=>Gte(f),[f]),[b,v]=(0,m.useState)(()=>K$(h)),[j,N]=(0,m.useState)(null),w=(0,m.useRef)(new Map),k=(0,m.useRef)(x),S=(0,m.useRef)(x);(0,m.useEffect)(()=>{x!==S.current&&(S.current=x,x!==k.current&&v(K$(h)))},[x,h]);const C=r(B=>s.find(E=>E.id===B)?.name??`${B.slice(0,8)}…`,"secretName");function I(B){v(B);const E=Hte(B);k.current=Gte(E),n(E)}r(I,"emit");function R(B,E){I(b.map(z=>z.id===B?{...z,...E}:z))}r(R,"patchRow");function T(B){I(b.filter(E=>E.id!==B))}r(T,"removeRow");function A(){v(B=>[...B,{id:OSe(),alias:"",secretId:"",version:"latest"}])}r(A,"addRow");const D=(0,m.useMemo)(()=>{const B=new Map;for(const E of b){const z=E.alias.trim();z&&B.set(z,(B.get(z)??0)+1)}return B},[b]),M=p.length>0;return(0,t.jsxs)("div",{className:"space-y-3",children:[M?(0,t.jsx)("div",{className:"space-y-1.5",children:p.map(B=>(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs",children:[(0,t.jsx)(Si,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:C(B.secretId)}),B.envKeys.length>0?(0,t.jsx)(Qte,{mode:"env"}):null,B.apiAliases.length>0?(0,t.jsx)(Qte,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...B.envKeys.map(E=>`${Jrt}${E}`),...B.apiAliases.map(E=>`${hA}${E}`)].join(" · ")})]},B.secretId))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No secrets are bound to this agent yet."}),d.length>0&&l&&c?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Proposed access"}),d.map(B=>{const E=BW(B),z=d4(B);return(0,t.jsxs)("div",{className:"flex flex-col gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 text-xs sm:flex-row sm:items-center",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[(0,t.jsx)(OW,{configPath:B.configPath}),(0,t.jsx)("code",{className:"font-mono",children:z||B.configPath}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"→"}),(0,t.jsx)(Si,{className:"size-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:E.name}),E.pending?(0,t.jsx)(FW,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",B.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",B.justification,"”"]})]})]}),(0,t.jsx)(DSe,{proposal:B,onApprove:l,onReject:c,disabled:i,size:"xs"})]},B.id)})]}):null,(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"API access (no env var)"}),b.length>0?(0,t.jsx)("div",{className:"space-y-2",children:b.map(B=>{const E=B.alias.trim(),z=!!E&&!n6.test(E),$=!!E&&(D.get(E)??0)>1,q=s.find(U=>U.id===B.secretId)??null;return(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"grid grid-cols-(--gtc-65) items-start gap-1.5",children:[(0,t.jsx)("div",{children:(0,t.jsx)(ht,{value:B.alias,onChange:r(U=>R(B.id,{alias:U.target.value}),"onChange"),onBlur:r(U=>{const O=U.target.value.trim();if(O&&!n6.test(O)){const K=M1(O);K&&K!==O&&R(B.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(z||$)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(br,{open:j?.rowId===B.id,onOpenChange:r(U=>{!U&&j?.rowId===B.id&&N(null)},"onOpenChange"),children:[(0,t.jsx)(_z,{asChild:!0,children:(0,t.jsx)("div",{ref:r(U=>{U?w.current.set(B.id,U):w.current.delete(B.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(LW,{secretId:B.secretId,secrets:s,onSelect:r(U=>R(B.id,{secretId:U,version:"latest",alias:!B.alias.trim()&&U?M1(C(U)):B.alias}),"onSelect"),onCreateNew:a?U=>{window.setTimeout(()=>{N({rowId:B.id,name:M5(U)||U.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(dr,{align:"start",className:"w-auto p-3",onInteractOutside:r(U=>{const O=U.detail.originalEvent.target;O&&w.current.get(B.id)?.contains(O)&&U.preventDefault()},"onInteractOutside"),children:j?.rowId===B.id&&a?(0,t.jsx)(_Se,{initialName:j.name,initialValue:"",existingSecretNames:s.map(U=>U.name),onCancel:r(()=>N(null),"onCancel"),onSubmit:r(async(U,O)=>{const K=await a(U,O);R(B.id,{secretId:K.id,version:"latest",alias:B.alias.trim()||M1(K.name)}),N(null)},"onSubmit")}):null})]}),(0,t.jsxs)("select",{className:"h-9 shrink-0 rounded-md border border-border bg-background px-2 text-xs outline-none disabled:cursor-not-allowed disabled:opacity-60",value:B.version===void 0?"latest":String(B.version),onChange:r(U=>{const O=U.target.value;R(B.id,{version:O==="latest"?"latest":Number.parseInt(O,10)})},"onChange"),disabled:i||!q,"aria-label":"Version",children:[(0,t.jsx)("option",{value:"latest",children:"latest"}),q?Array.from({length:Math.max(0,q.latestVersion)},(U,O)=>{const K=q.latestVersion-O;return K<=0?null:(0,t.jsxs)("option",{value:K,children:["v",K]},K)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>T(B.id),"onClick"),disabled:i,"aria-label":"Remove API access",className:"mt-1 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:(0,t.jsx)(la,{className:"size-3.5"})})]}),z?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):$?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},B.id)})}):null,(0,t.jsxs)("button",{type:"button",onClick:A,disabled:i,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",children:[(0,t.jsx)(yn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[Xrt("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(uat,"AgentSecretAccessEditor");function mat(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(mat,"asNonEmptyString$3");function hat(e){return mat(e)!==null}r(hat,"hasLegacyWorkingDirectory");function pat(e){return e.isCreate?!1:hat(e.adapterConfig?.cwd)}r(pat,"shouldShowLegacyWorkingDirectoryField");var FSe=new Set;function fat(e){return FSe.has(e)}r(fat,"isAdapterTypeHidden");function xat(e){FSe=new Set(e)}r(xat,"setDisabledAdapterTypes");function gat(e){return!Ch(e).hideFromVisualSelection}r(gat,"isVisualAdapterChoice");function BSe(e,s=MW()){const n=e??Bf;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Ch(a.type).comingSoon,hidden:fat(a.type),experimental:!!Ch(a.type).experimental}))}r(BSe,"listAdapterOptions");function zSe(e={}){const s=e.enabled??!0,{data:n}=ee({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&grt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&xat(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(zSe,"useDisabledAdaptersSync");function bat(e={}){const s=e.enabled??!0,{data:n}=ee({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(bat,"useAdapterRegistryLoaded");function D5(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(D5,"omitUndefinedEntries");function V2(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=D5(s.adapterType!==void 0?{...Object.fromEntries(l$e.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=D5({...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(V2,"buildAgentUpdatePatch");var vat="kubernetes";function yat(e){return e.driver!=="sandbox"?!1:e.config?.provider===vat}r(yat,"isKubernetesSandboxEnvironment");function zW(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>yat(n))??null}}r(zW,"resolveForcedKubernetesEnvironment");var W$={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},nC={};function jat(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(jat,"supportsAdapterModelRefresh");function wat(e,s){return DNe(e,s).model}r(wat,"resolvePaperclipRunnerTransitionModel");function Yte(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(Yte,"isOverlayDirty");function r6(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)=>r6(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&&r6(o,a[i]))}return!1}r(r6,"overlayValuesEqual");function kat(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!r6(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(kat,"subtractPersistedOverlay");var Zm="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function Nat(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(Nat,"parseCommaArgs");function Sat(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(Sat,"formatArgList");var Cat=[{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"}],_at=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],Iat=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],Aat=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],Tat=2,Jte=10,Rat=1,qSe=300;function jE(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(jE,"clampInteger");function Eat(e){return jE(e,0,qSe)*1e3}r(Eat,"clampDelayMsFromSeconds");function Pat({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(Pat,"ConfigSections");function USe(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=Pt(),b=(0,m.useRef)(null),v=zSe(),{data:j=[]}=ee({queryKey:f?P.secrets.list(f):["secrets","none"],queryFn:r(()=>yr.list(f),"queryFn"),enabled:!!f}),{data:N=[]}=ee({queryKey:f?P.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>yr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:k=[]}=ee({queryKey:f?P.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>yr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>k.filter(Ze=>Ze.kind==="binding"&&Ze.target?.id===w),[k,w]),C=MSe(f,[]),{data:I}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),retry:!1}),R=(0,m.useMemo)(()=>{const Ze=new Set(v);return I?.enableNativeRunner!==!0&&Ze.add("paperclip_runner"),Ze},[v,I?.enableNativeRunner]),T=I?.enableEnvironments===!0,A=I?.enableManagedSandboxOnly===!0,D=I===void 0||A,{data:M}=ee({queryKey:P.instance.generalSettings,queryFn:r(()=>Nr.getGeneral(),"queryFn"),retry:!1}),{data:B}=ee({queryKey:P.instance.settings,queryFn:r(()=>Nr.get(),"queryFn"),retry:!1}),{data:E=[]}=ee({queryKey:f?P.environments.list(f):["environments","none"],queryFn:r(()=>Pi.list(f),"queryFn"),enabled:!!f&&(T||M?.executionMode==="kubernetes")}),{forced:z,kubernetesEnvironment:$}=(0,m.useMemo)(()=>zW(M?.executionMode,E),[M?.executionMode,E]),q=je({mutationFn:r(Ze=>{if(!f)throw new Error("Select an organization to create secrets");return yr.create(f,Ze)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.list(f)})},"onSuccess")}),U=je({mutationFn:r(async({file:Ze,namespace:At})=>{if(!f)throw new Error("Select an organization to upload images");return vb.uploadImage(f,Ze,At)},"mutationFn")}),[O,K]=(0,m.useState)(W$),[H,Z]=(0,m.useState)(!1),[se,ne]=(0,m.useState)(0),fe=(0,m.useRef)(null),X=(0,m.useRef)(null),re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(fe.current!==null&&e.agent!==fe.current&&!re.current){const Ze=X.current;X.current=null,K(At=>Ze?kat(At,Ze):{...W$})}fe.current=e.agent}},[a,a?void 0:e.agent]);const oe=!a&&(Yte(O)||H);function G(Ze,At,fs){const Ks=O[Ze];return At in Ks?Ks[At]:fs}r(G,"eff");function Y(Ze,At,fs){K(Ks=>({...Ks,[Ze]:{...Ks[Ze],[At]:fs}}))}r(Y,"mark");function Q(){return b.current?.flushPendingDraft()??null}r(Q,"flushEnvironmentDraft");const te=(0,m.useCallback)(Ze=>{a||K(At=>{const fs={...e.agent.adapterConfig??{},...At.adapterConfig},Ks={...At.adapterConfig};for(const[Ln,Cr]of Object.entries(Ze))Ks[`${hA}${Ln}`]=Cr;for(const Ln of Object.keys(fs))Ln.startsWith("access.")&&(Ln.slice(7)in Ze||(Ks[Ln]=void 0));return{...At,adapterConfig:Ks}})},[a,a?void 0:e.agent]),ae=(0,m.useCallback)(()=>{K({...W$}),Z(!1),ne(Ze=>Ze+1)},[]),le=(0,m.useCallback)(async()=>{if(a)return;const Ze=Q(),At=Ze?{...O,adapterConfig:{...O.adapterConfig,env:Ze}}:O;Yte(At)&&await e.onSave(V2(e.agent,At))},[a,oe,O,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(oe),e.onSaveActionChange?.(le),e.onCancelActionChange?.(ae))},[a,oe,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,le,ae]),(0,m.useEffect)(()=>{if(!a)return()=>{e.onSaveActionChange?.(null),e.onCancelActionChange?.(null),e.onDirtyChange?.(!1)}},[a,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const he=a?{}:e.agent.adapterConfig??{},ce=a?{}:e.agent.runtimeConfig??{},ge=a?{}:ce.heartbeat??{},me=a?{}:ce.debug??{},ie=a?e.values.adapterType:O.adapterType??e.agent.adapterType,ue=Wy(),ke=ue(ie),be=ke.supportsInstructionsBundle||ke.supportsSkills||ke.supportsLocalAgentJwt,Ie=be&&!D&&pat({isCreate:a,adapterConfig:he}),Ue=(0,m.useMemo)(()=>iS(ie),[ie]),at=(0,m.useMemo)(()=>new Set(Nze(ie)),[ie]),dt=a?e.values:null,de=a?Ze=>e.onChange(Ze):null;a&&dt.claudeStoredSessionId;const Be=r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),pt=r(Ze=>{if(!a||!de)return;const At=dt.envBindings??{};de({envBindings:{...At,...Vw()},claudeStoredSessionId:Ze}),Be()},"handleClaudeLoginStored"),vt=r(async()=>{if(a)return;const Ze={...Q()??G("adapterConfig","env",he.env??nC),...Vw()},At={...O,adapterConfig:{...O.adapterConfig,env:Ze}};K(At),await e.onSave({...V2(e.agent,At),applyStoredClaudeLogin:!0}),Be()},"handleClaudeLoginStoredEdit"),Le=r(async Ze=>{if(a||!Ze.companyIdentityDiffers)return;const At={...Q()??G("adapterConfig","env",he.env??nC),CODEX_HOME:{type:"secret_ref",secretId:Ze.secretId,version:"latest"}},fs={...O,adapterConfig:{...O.adapterConfig,env:At}};K(fs),X.current=fs,re.current=!0;try{await e.onSave(V2(e.agent,fs))}catch(Ks){throw X.current=null,Ks}finally{re.current=!1}Be()},"handleCodexAccountBindingEdit"),Qe=r(()=>{if(!a||!de)return;const Ze=dt.envBindings??{};de({envBindings:{...Ze,...Vw()},claudeApplyStoredLogin:!0}),Be()},"handleApplyStoredClaudeLogin"),ut=r(async()=>{if(a)return;const Ze={...Q()??G("adapterConfig","env",he.env??nC),...Vw()},At={...O,adapterConfig:{...O.adapterConfig,env:Ze}};K(At),await e.onSave({...V2(e.agent,At),applyStoredClaudeLogin:!0}),Be()},"handleApplyStoredClaudeLoginEdit"),Ye=a?dt.defaultEnvironmentId??"":G("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),it=(0,m.useMemo)(()=>Ye?(E.find(Ze=>Ze.id===Ye)??null)?.driver==="local"?"":Ye:"",[E,Ye]),kt=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===it)??null,[it,E]),tt=(0,m.useMemo)(()=>{const Ze=B?.defaultEnvironmentId??null;return Ze?(E.find(At=>At.id===Ze)??null)?.driver==="local"?"":Ze:""},[E,B?.defaultEnvironmentId]),Pe=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===tt)??null,[E,tt]),Ce=(0,m.useMemo)(()=>{try{return iN({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:B?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(E),managedSandboxOnly:I?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:oN(E),visibleEnvironmentIds:E.map(Ze=>Ze.id)})}catch{return null}},[Ye,B?.defaultEnvironmentId,E,I?.enableManagedSandboxOnly]),He=(0,m.useMemo)(()=>E.find(Ze=>Ze.id===Ce)??null,[E,Ce]),{data:Je}=ee({queryKey:f?P.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>Pi.capabilities(f),"queryFn"),enabled:!!f&&ke.login!=null});(0,m.useEffect)(()=>{!a||!de||!z||!$||it!==$.id&&de({defaultEnvironmentId:$.id})},[a,de,z,$,it]);const lt=(0,m.useMemo)(()=>E.filter(Ze=>{if(!at.has(Ze.driver)||Ze.driver==="local")return!1;if(Ze.driver!=="sandbox")return!0;const At=typeof Ze.config?.provider=="string"?Ze.config.provider:null;return At!==null&&At!=="fake"}),[E,at]),Ee=(0,m.useMemo)(()=>!kt||lt.some(Ze=>Ze.id===kt.id)?lt:[...lt,kt],[kt,lt]),Xe=T&&(z||it.length>0||lt.length>=1),Ae=Pe?Yv(Pe):A?"Paperclip Computer":"Local",De=ie==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":G("adapterConfig","provider",he.provider==="acpx"&&he.acpxAgent==="codex"?"codex":he.provider??"codex")):void 0,_t=ie==="opencode_local"&&Zpe.safeParse(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection).data?.provider==="openrouter"?"openrouter":De,ye=f?P.agents.adapterModels(f,ie,it||null,_t):["agents","none","adapter-models",ie],{data:gt,error:We}=ee({queryKey:ye,queryFn:r(()=>$t.adapterModels(f,ie,{environmentId:it||null,provider:_t}),"queryFn"),enabled:!!f}),[Ot,zt]=(0,m.useState)(null),[Cs,ze]=(0,m.useState)(!1),ft=gt??n??[],Ut="command",{data:Ns,refetch:Is}=ee({queryKey:f?P.agents.detectModel(f,ie):["agents","none","detect-model",ie],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return $t.detectModel(f,ie)},"queryFn"),enabled:!!(f&&be&&ie!=="opencode_local"&&ie!=="paperclip_runner")}),Ct=Ns?.model??null;Ns?.candidates;const{data:ds=[]}=ee({queryKey:f?P.agents.list(f):["agents","none","list"],queryFn:r(()=>$t.list(f),"queryFn"),enabled:!!(!a&&f)}),$e={mode:s,isCreate:a,adapterType:ie,values:a?e.values:null,set:a?Ze=>e.onChange(Ze):null,config:he,eff:G,mark:Y,models:ft,hideInstructionsFile:h||D,managedSandboxOnly:D},[xe,Qt]=(0,m.useState)(!1),[Dt,rs]=(0,m.useState)(!1),ws=HNe(ie),Bs=r(Ze=>(0,t.jsxs)(t.Fragment,{children:[ie==="claude_local"&&(0,t.jsx)(ett,{...$e,section:Ze}),(0,t.jsx)(Ue.ConfigFields,{...$e,section:Ze,hideModel:be})]}),"renderAdapterFields"),[er,Fe]=(0,m.useState)(!1),[st,xt]=(0,m.useState)(!1);function Oe(Ze){if(a){const fs=Ue.buildAdapterConfig(dt);return Ze&&Object.assign(fs,Ze),D5(fs)}const At={...he,...O.adapterConfig};return Ze&&Object.assign(At,Ze),D5(At)}r(Oe,"buildAdapterConfigForTest");const Bt=je({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const Ze=Q(),At=Ze?{env:Ze}:void 0;let fs=B,Ks=E,Ln=I?.enableManagedSandboxOnly===!0;if(!Ye)try{const[_r,jr,sr]=await Promise.all([x.ensureQueryData({queryKey:P.instance.settings,queryFn:r(()=>Nr.get(),"queryFn")}),x.ensureQueryData({queryKey:P.environments.list(f),queryFn:r(()=>Pi.list(f),"queryFn")}),x.ensureQueryData({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")})]);fs=_r,Ks=jr,Ln=sr?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Cr=iN({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:fs?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(Ks),managedSandboxOnly:Ln,managedSandboxEnvironmentId:oN(Ks),visibleEnvironmentIds:Ks.map(_r=>_r.id)}),Vr=Oe(At),Pr=a?void 0:e.agent.id,Ar=a?void 0:CJ.safeParse(O.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const _r=ie==="paperclip_runner"?Vr.provider==="codex"?"codex_local":Vr.provider==="acpx"&&Vr.acpxAgent==="grok"?"grok_local":Vr.provider==="acpx"&&Vr.acpxAgent==="claude"?"claude_local":ie:ie;return TNe({companyId:f,adapterType:ie,providerAdapter:_r,adapterConfig:Vr,agentId:Pr,aiConnection:Ar,environmentId:Cr})}return $t.testEnvironment(f,ie,{adapterConfig:Vr,agentId:Pr,aiConnection:Ar,environmentId:Cr})},"mutationFn")}),[wt,Xt]=(0,m.useState)(!1),[Yt,hs]=(0,m.useState)(null),Ts="Test",as=!a&&!!e.isSaving,Zn=wt||as||!f,en=(0,m.useRef)(Bt.reset);en.current=Bt.reset;const nr=(0,m.useRef)(()=>{});nr.current=()=>{if(!a||!de)return;const Ze=dt.envBindings??{},At=dt.claudeStoredSessionId!=null||dt.claudeApplyStoredLogin===!0,fs=Bte in Ze;if(!At&&!fs)return;const Ks={...Ze};delete Ks[Bte],de({envBindings:Ks,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{en.current(),hs(null),nr.current()},[ie,Ce]);const tn=ke.login!=null,xn=Bt.data,Ht=xn!=null&&ue(xn.adapterType).login!=null,qs=xn&&Ht?xn.checks.find(Ze=>Ze.code==="adapter_auth_missing")??null:null,Vs=typeof He?.config?.provider=="string"?He.config.provider:null,Lt=Vs!=null&&Je?.sandboxProviders?.[Vs]?.supportsLoginPty===!0,is=ke.login!=null,Ms=(a||!(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection))&&tn&&He?.driver==="sandbox"&&!!Ce&&!!f&&!!qs&&(!is||Lt),bs=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");Xt(!0),hs(null),Bt.reset();try{return await Bt.mutateAsync()}catch(Ze){throw hs(Ze instanceof Error?Ze.message:"Environment test failed"),Ze}finally{Xt(!1)}},[f,Bt]),gn=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{gn.current=()=>{Zn||bs().catch(()=>{})}},[bs,Zn]);const Pn=(0,m.useCallback)(()=>{gn.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Pn),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Pn]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Zn,pending:wt}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Zn,wt]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Yt??(Bt.error instanceof Error?Bt.error.message:Bt.error?"Environment test failed":null),result:Bt.data??null,login:Ms&&f&&Ce?{companyId:f,adapterType:ie,environmentId:Ce}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Yt,Bt.data,Bt.error,Ms,f,ie,Ce]);const $r=a?dt.model??"":G("adapterConfig","model",String(he.model??"")),mt=typeof $r=="string"?$r:"";async function vs(){if(f){ze(!0),zt(null);try{const Ze=await $t.adapterModels(f,ie,{refresh:!0,environmentId:it||null,provider:_t});x.setQueryData(ye,Ze)}catch(Ze){zt(Ze instanceof Error?Ze.message:"Failed to refresh adapter models.")}finally{ze(!1)}}}r(vs,"handleRefreshModels");const Fs=ie==="codex_local"?"modelReasoningEffort":ie==="cursor"?"mode":ie==="opencode_local"?"variant":ie==="grok_local"?"reasoningEffort":ie==="pi_local"?"thinking":"effort",Hs=ie==="codex_local"?_W(mt,"Auto").map(Ze=>({id:Ze.value,label:Ze.label})):ie==="cursor"?_at:ie==="opencode_local"?Cat:ie==="kimi_local"?Aat:ie==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(Ze=>({id:Ze,label:Ze}))]:ie==="claude_local"||ie==="grok_local"?[{id:"",label:"Auto"},...I5(ie,mt).map(Ze=>({id:Ze,label:Ze==="xhigh"?"X-High":Ze[0].toUpperCase()+Ze.slice(1)}))]:Iat,zs=a?dt.thinkingEffort:ie==="codex_local"?G("adapterConfig","modelReasoningEffort",String(he.modelReasoningEffort??he.reasoningEffort??"")):ie==="cursor"?G("adapterConfig","mode",String(he.mode??"")):ie==="opencode_local"?G("adapterConfig","variant",String(he.variant??"")):G("adapterConfig",Fs,String(he[Fs]??"")),Us=ie!=="gemini_local"&&ie!=="cursor_cloud"&&ie!=="paperclip_runner",ur=ie==="codex_local"?a?!!dt.search:G("adapterConfig","search",!!he.search):!1,Dn=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:dt.heartbeatEnabled,intervalSec:dt.intervalSec}};const Ze={...ce.heartbeat&&typeof ce.heartbeat=="object"?ce.heartbeat:{},...O.heartbeat};return{...ce,heartbeat:Ze}},[a,O.heartbeat,ce,dt]),Er=PJ(Dn.heartbeat),Jn=PJ(Er.maxTurnContinuation),tr=R$e(Jn.enabled,!0),pn=jE(qJ(Jn.maxAttempts,Tat),0,Jte),yt=jE(qJ(Jn.delayMs,Rat*1e3)/1e3,0,qSe);function Ps(Ze){Y("heartbeat","maxTurnContinuation",{...Jn,...Ze})}r(Ps,"updateMaxTurnContinuation");const Zs=(0,t.jsx)(jy,{ref:b,onDirtyChange:Z,hideDraftActions:!a&&e.hideInlineSave,value:a?dt.envBindings??nC:G("adapterConfig","env",he.env??nC),secrets:j,userSecretDefinitions:N,onCreateSecret:r(async(Ze,At)=>await q.mutateAsync({name:Ze,value:At}),"onCreateSecret"),onChange:r(Ze=>a?de({envBindings:Ze??{},envVars:""}):Y("adapterConfig","env",Ze),"onChange")},se);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end border-b border-primary/20 bg-background/90 px-4 py-2 backdrop-blur-sm",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)(L,{size:"sm",onClick:le,disabled:e.isSaving,children:e.isSaving?"Saving...":"Save"})]})}),e.environmentVariablesPlacement==="secrets"&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"rounded-lg border border-border p-4":"px-4 pb-3"),children:Zs})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Secret access"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Secret access"}),(0,t.jsxs)("div",{className:W(i?"space-y-3 rounded-lg border border-border p-4":"space-y-3 px-4 pb-3"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:Ni.secretAccess}),(0,t.jsx)(uat,{config:{...he,...O.adapterConfig},secrets:j,onChange:te,onCreateSecret:r((Ze,At)=>q.mutateAsync({name:Ze,value:At}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(Pat,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[oe&&!e.hideInlineSave&&(0,t.jsx)("div",{className:"sticky top-0 z-10 flex items-center justify-end px-4 py-2 bg-background/90 backdrop-blur-sm border-b border-primary/20",children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Unsaved changes"}),(0,t.jsx)(L,{size:"sm",onClick:le,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(Ss,{label:"Name",hint:Ni.name,children:(0,t.jsx)(Ka,{value:G("identity","name",e.agent.name),onCommit:r(Ze=>Y("identity","name",Ze),"onCommit"),immediate:!0,className:Zm,placeholder:"Agent name"})}),(0,t.jsx)(Ss,{label:"Title",hint:Ni.title,children:(0,t.jsx)(Ka,{value:G("identity","title",e.agent.title??""),onCommit:r(Ze=>Y("identity","title",Ze||null),"onCommit"),immediate:!0,className:Zm,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(Ss,{label:"Reports to",hint:Ni.reportsTo,children:(0,t.jsx)(krt,{agents:ds,value:G("identity","reportsTo",e.agent.reportsTo??null),onChange:r(Ze=>Y("identity","reportsTo",Ze),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),be&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Prompt Template",hint:Ni.promptTemplate,children:(0,t.jsx)(fd,{value:G("adapterConfig","promptTemplate",String(he.promptTemplate??"")),onChange:r(Ze=>Y("adapterConfig","promptTemplate",Ze??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async Ze=>{const At=`agents/${e.agent.id}/prompt-template`;return(await U.mutateAsync({file:Ze,namespace:At})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-900 dark:text-amber-100",children:"Prompt template is replayed on every heartbeat. Keep it compact and dynamic to avoid recurring token cost and cache churn."})]})]})]}),z?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Default environment",hint:"This instance runs all agents in the Kubernetes sandbox. Local execution is disabled.",children:$?(0,t.jsxs)("div",{className:W(Zm,"flex items-center text-muted-foreground"),children:[$.name," · Kubernetes sandbox"]}):(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"This instance requires the Kubernetes sandbox, but no managed Kubernetes environment is available for this organization yet. Configure one before creating agents; execution will not fall back to local."})})})]}):Xe?(0,t.jsxs)("div",{"data-config-section":"environment",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(Ss,{label:"Environment override",children:(0,t.jsx)("div",{className:"space-y-2",children:(0,t.jsxs)("select",{className:Zm,value:it,onChange:r(Ze=>{const At=Ze.target.value;if(a){de({defaultEnvironmentId:At});return}Y("identity","defaultEnvironmentId",At||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Ae]}),Ee.map(Ze=>(0,t.jsx)("option",{value:Ze.id,children:Yv(Ze)},Ze.id))]})})})})]}):null,(0,t.jsxs)("div",{"data-config-section":"adapter",className:W(!i&&(a?"border-t border-border":"border-b border-border")),children:[(0,t.jsxs)("div",{className:W(i?"flex items-center justify-between mb-3":"px-4 py-2 flex items-center justify-between gap-2"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium",children:e.sectionTitles?.adapter??"Adapter"}):(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:"Adapter"}),c&&(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",onClick:Pn,disabled:Zn,children:wt?`${Ts}...`:Ts})]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(Ss,{label:"Adapter type",hint:Ni.adapterType,children:(0,t.jsx)(WSe,{value:ie,disabledTypes:R,onChange:r(Ze=>{if(a){const{adapterType:At,...fs}=ab,Ks={...fs,adapterType:Ze};Ze==="codex_local"?Ks.dangerouslyBypassSandbox=!0:Ze==="gemini_local"?Ks.model="auto":Ze==="kimi_local"?Ks.model="kimi-code/kimi-for-coding":Ze==="cursor"?Ks.model="auto":Ze==="opencode_local"?Ks.model="openai/gpt-5.2-codex":Ze==="paperclip_runner"&&(Ks.model=nN),de(Ks)}else K(At=>({...At,adapterType:Ze,adapterConfig:{model:Ze==="gemini_local"?"auto":Ze==="kimi_local"?"kimi-code/kimi-for-coding":Ze==="opencode_local"?"openai/gpt-5.2-codex":Ze==="cursor"?"auto":Ze==="paperclip_runner"?wat(ie,he.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...Ze==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:Ze==="paperclip_runner"?{...DNe(ie,G("adapterConfig","model",he.model))}:{}}}))},"onChange")})}),!a&&f&&(0,t.jsx)(ANe,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:ie==="paperclip_runner"?G("adapterConfig","provider",he.provider)==="codex"?"codex_local":G("adapterConfig","provider",he.provider)==="opencode"?"opencode_local":G("adapterConfig","provider",he.provider)==="acpx"&&G("adapterConfig","acpxAgent",he.acpxAgent)==="grok"?"grok_local":G("adapterConfig","provider",he.provider)==="acpx"&&G("adapterConfig","acpxAgent",he.acpxAgent)==="claude"?"claude_local":ie:ie,routerAdapterType:ie,value:CJ.safeParse(O.runtime.runtimeConfig?.aiConnection??ce.aiConnection).data,model:String(G("adapterConfig","model",he.model)??""),environmentId:it||void 0,legacy:!0,onChange:r(Ze=>Y("runtime","runtimeConfig",{...ce,aiConnection:Ze}),"onChange")}),d&&!e.compactTestFeedback&&(Yt||Bt.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Yt??(Bt.error instanceof Error?Bt.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&Bt.data&&(0,t.jsx)(Bat,{result:Bt.data}),d&&Ms&&(0,t.jsx)(qW,{companyId:f,adapterType:ie,environmentId:Ce,onStored:a?pt:vt,onApplyStored:a?Qe:ut,onAccountBinding:a?void 0:Le},`${ie}:${Ce}`),Ie&&(0,t.jsx)(Ss,{label:"Working directory (deprecated)",hint:Ni.cwd,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[(0,t.jsx)(Go,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(Ka,{value:a?dt.cwd:G("adapterConfig","cwd",String(he.cwd??"")),onCommit:r(Ze=>a?de({cwd:Ze}):Y("adapterConfig","cwd",Ze||void 0),"onCommit"),immediate:!0,className:"w-full bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40",placeholder:"/path/to/project"}),(0,t.jsx)(Dd,{})]})}),Bs("adapter"),be&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(UW,{models:ft,value:mt,onChange:r(Ze=>{const At=I5(ie,Ze),fs=["codex_local","claude_local","grok_local"].includes(ie)&&!!zs&&!At.includes(String(zs));if(a){de({model:Ze,...fs?{thinkingEffort:""}:{}});return}Y("adapterConfig","model",Ze||void 0),fs&&(Y("adapterConfig",Fs,void 0),Y("adapterConfig","reasoningEffort",void 0))},"onChange"),open:er,onOpenChange:Fe,defaultLabel:ie==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:ie!=="opencode_local"&&ie!=="pi_local"&&ie!=="paperclip_runner",required:ie==="opencode_local"||ie==="pi_local",groupByProvider:ie==="opencode_local"||ie==="pi_local",preserveOrder:PW(ie),creatable:!0,detectedModel:Ct,detectedModelCandidates:[],onDetectModel:ie==="opencode_local"||ie==="paperclip_runner"?void 0:async()=>(await Is()).data?.model??null,onRefreshModels:jat(ie)?vs:void 0,refreshingModels:Cs,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Ot||We)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Ot??(We instanceof Error?We.message:"Failed to load adapter models.")}),ie==="opencode_local"&&kt&&kt.driver!=="local"&&(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Live OpenCode model discovery only runs for Local environments. Using the curated list and manual entry for ",kt.name,"."]}),Us&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(zat,{value:zs,options:Hs,onChange:r(Ze=>a?de({thinkingEffort:Ze}):Y("adapterConfig",Fs,Ze||void 0),"onChange"),open:st,onOpenChange:xt}),ie==="codex_local"&&ur&&zs==="minimal"&&(0,t.jsx)("p",{className:"text-xs text-amber-400",children:"Codex may reject `minimal` thinking when search is enabled."})]})]})]})]}),(0,t.jsxs)("div",{"data-config-section":"configuration",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Configuration"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Configuration"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[!a&&typeof he.bootstrapPromptTemplate=="string"&&he.bootstrapPromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Bootstrap prompt (legacy)",hint:Ni.bootstrapPrompt,children:(0,t.jsx)(fd,{value:G("adapterConfig","bootstrapPromptTemplate",String(he.bootstrapPromptTemplate??"")),onChange:r(Ze=>Y("adapterConfig","bootstrapPromptTemplate",Ze||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async Ze=>{const At=`agents/${e.agent.id}/bootstrap-prompt`;return(await U.mutateAsync({file:Ze,namespace:At})).contentPath},"imageUploadHandler")})}),(0,t.jsx)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200",children:"Bootstrap prompt is legacy and will be removed in a future release. Consider moving this content into the agent's prompt template or instructions file instead."})]}),Bs("configuration"),(be||ie==="process"||ws?.fields.some(Ze=>zq(Ze.key)==="advanced"))&&(0,t.jsx)(pE,{title:"Advanced",open:Dt,onToggle:r(()=>rs(!Dt),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[be&&(0,t.jsxs)(t.Fragment,{children:[" ",!D&&(0,t.jsx)(Ss,{label:"Command",hint:Ni.localCommand,children:(0,t.jsx)(Ka,{value:a?dt.command:G("adapterConfig",Ut,String(he.command??"")),onCommit:r(Ze=>a?de({command:Ze}):Y("adapterConfig",Ut,Ze||null),"onCommit"),immediate:!0,className:Zm,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[ie]??ie.replace(/_local$/,"")})}),(0,t.jsx)(Ss,{label:"Extra args (comma-separated)",hint:Ni.extraArgs,children:(0,t.jsx)(Ka,{value:a?dt.extraArgs:G("adapterConfig","extraArgs",Sat(he.extraArgs)),onCommit:r(Ze=>a?de({extraArgs:Ze}):Y("adapterConfig","extraArgs",Ze?.trim()?Nat(Ze):null),"onCommit"),className:Zm,placeholder:"e.g. --verbose, --foo=bar"})})]}),Bs("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(be||ws?.fields.some(Ze=>zq(Ze.key)==="environment"))&&(0,t.jsxs)("div",{"data-config-section":"environment-variables",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Environment variables"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Environment variables"}),(0,t.jsx)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:be?Zs:Bs("environment")})]}),a&&u?(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(FC,{className:"h-3 w-3"})," Run Policy"]}):(0,t.jsxs)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[(0,t.jsx)(FC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(hte,{label:"Heartbeat on interval",hint:Ni.heartbeatInterval,checked:dt.heartbeatEnabled,onCheckedChange:r(Ze=>de({heartbeatEnabled:Ze}),"onCheckedChange"),number:dt.intervalSec,onNumberChange:r(Ze=>de({intervalSec:Ze}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Ni.intervalSec,showNumber:dt.heartbeatEnabled}),(0,t.jsx)(pE,{title:"Advanced Run Policy",open:xe,onToggle:r(()=>Qt(!xe),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Bs("runPolicy")})})]})]}):a?null:(0,t.jsxs)("div",{"data-config-section":"run-policy",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"text-sm font-medium flex items-center gap-2 mb-3",children:[(0,t.jsx)(FC,{className:"h-3 w-3"})," Run Policy"]}):(0,t.jsxs)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground flex items-center gap-2",children:[(0,t.jsx)(FC,{className:"h-3 w-3"})," Run Policy"]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg overflow-hidden":""),children:[(0,t.jsx)("div",{className:W(i?"p-4 space-y-3":"px-4 pb-3 space-y-3"),children:(0,t.jsx)(hte,{label:"Heartbeat on interval",hint:Ni.heartbeatInterval,checked:G("heartbeat","enabled",ge.enabled===!0),onCheckedChange:r(Ze=>Y("heartbeat","enabled",Ze),"onCheckedChange"),number:G("heartbeat","intervalSec",Number(ge.intervalSec??300)),onNumberChange:r(Ze=>Y("heartbeat","intervalSec",Ze),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:Ni.intervalSec,showNumber:G("heartbeat","enabled",ge.enabled===!0)})}),(0,t.jsx)(pE,{title:"Advanced Run Policy",bordered:i,open:xe,onToggle:r(()=>Qt(!xe),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Bs("runPolicy"),be&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!ws?.fields.some(Ze=>Ze.key==="timeoutSec")&&(0,t.jsx)(Ss,{label:"Timeout (sec)",hint:Ni.timeoutSec,children:(0,t.jsx)(Rc,{value:G("adapterConfig","timeoutSec",Number(he.timeoutSec??0)),onCommit:r(Ze=>Y("adapterConfig","timeoutSec",Ze),"onCommit"),immediate:!0,className:Zm})}),!ws?.fields.some(Ze=>Ze.key==="graceSec")&&(0,t.jsx)(Ss,{label:"Interrupt grace period (sec)",hint:Ni.graceSec,children:(0,t.jsx)(Rc,{value:G("adapterConfig","graceSec",Number(he.graceSec??15)),onCommit:r(Ze=>Y("adapterConfig","graceSec",Ze),"onCommit"),immediate:!0,className:Zm})})]})}),(0,t.jsx)(Cd,{label:"Wake on demand",hint:Ni.wakeOnDemand,checked:G("heartbeat","wakeOnDemand",ge.wakeOnDemand!==!1),onChange:r(Ze=>Y("heartbeat","wakeOnDemand",Ze),"onChange")}),(0,t.jsx)(Ss,{label:"Cooldown (sec)",hint:Ni.cooldownSec,children:(0,t.jsx)(Rc,{value:G("heartbeat","cooldownSec",Number(ge.cooldownSec??10)),onCommit:r(Ze=>Y("heartbeat","cooldownSec",Ze),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsx)(Ss,{label:"Max concurrent runs",hint:Ni.maxConcurrentRuns,children:(0,t.jsx)(Rc,{value:G("heartbeat","maxConcurrentRuns",Number(ge.maxConcurrentRuns??20)),onCommit:r(Ze=>Y("heartbeat","maxConcurrentRuns",Ze),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsxs)("div",{className:"rounded-md border border-border/70 px-3 py-2",children:[(0,t.jsx)(Cd,{label:"Continue after max-turn stop",hint:Ni.maxTurnContinuationEnabled,checked:tr,onChange:r(Ze=>Ps({enabled:Ze}),"onChange")}),tr?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Continuation attempts",hint:Ni.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Rc,{value:pn,onCommit:r(Ze=>Ps({maxAttempts:jE(Ze,0,Jte)}),"onCommit"),immediate:!0,className:Zm})}),(0,t.jsx)(Ss,{label:"Continuation delay (sec)",hint:Ni.maxTurnContinuationDelaySec,children:(0,t.jsx)(Rc,{value:yt,onCommit:r(Ze=>Ps({delayMs:Eat(Ze)}),"onCommit"),immediate:!0,className:Zm})})]}):null]})]})})]})]}),!a&&p?(0,t.jsxs)("div",{className:W(!i&&"border-b border-border"),children:[i?(0,t.jsxs)("h3",{className:"mb-3 flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)(Kv,{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)(Kv,{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)(Cd,{label:"Capture raw provider traces",hint:"Stores exact provider traffic for every future run until disabled. Traces may contain sensitive prompts and tool arguments, are administrator-only, and expire after 24 hours.",checked:G("debug","providerTrace",me.providerTrace)==="raw",onChange:r(Ze=>Y("debug","providerTrace",Ze?"raw":void 0),"onChange")}),G("debug","providerTrace",me.providerTrace)==="raw"?(0,t.jsxs)("div",{className:"mt-3 flex items-start gap-2 rounded-md border border-border bg-background/60 px-3 py-2 text-xs text-foreground",children:[(0,t.jsx)(Kv,{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)(qNe,{state:wt?"running":Yt||Bt.error?"fail":xn?.status??"idle",result:xn??null,error:Yt??(Bt.error instanceof Error?Bt.error.message:null),onTest:Pn,disabled:Zn})]})}r(USe,"AgentConfigForm");var a6=new Set(["authenticated","failed","timed_out","cancelled"]),i6=2e3;function o6({value:e,label:s}){const[n,a]=(0,m.useState)(!1),i=(0,m.useRef)(null);return(0,m.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-xs","aria-label":s,title:s,className:"text-muted-foreground hover:text-foreground",onClick:r(async()=>{try{await fa(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(gs,{className:"size-3"}):(0,t.jsx)(Ir,{className:"size-3"})})}r(o6,"AdapterLoginCopyButton");function Mat({status:e,message:s}){return e==="authenticated"?(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}):(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsxs)("span",{children:[e==="timed_out"?"Login timed out":e==="cancelled"?"Login cancelled":"Login failed",s?`: ${s}`:"."]})]})}r(Mat,"AdapterLoginTerminalState");var Dat={claude_local:"Anthropic",codex_local:"OpenAI"};function KSe(e){const s=Dat[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(KSe,"adapterLoginTitle");function qW(e){return Wy()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(Fat,{...e}):(0,t.jsx)(Lat,{...e})}r(qW,"AdapterLoginPanel");var V$=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 Lat({companyId:e,adapterType:s,environmentId:n,autoStart:a,onConnected:i,onAccountBinding:o,chrome:l="panel",aiConnection:c,onPromptReady:d}){const[u,h]=(0,m.useState)(null),[p,f]=(0,m.useState)(null),[x,b]=(0,m.useState)(null),[v,j]=(0,m.useState)("idle"),N=(0,m.useRef)(!1),w=je({mutationFn:r(()=>$t.startAdapterAuthLogin(e,s,{environmentId:n,aiConnection:c}),"mutationFn"),onSuccess:r(re=>{N.current=!1,f(null),b(null),j("idle"),h(re.sessionId)},"onSuccess"),onError:r(re=>{f(re instanceof Error?re.message:"Could not start the login.")},"onError")}),k=(0,m.useCallback)(()=>{N.current=!1,h(null),b(null),f(null)},[]),S=je({mutationFn:r(()=>$t.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:k,onError:r(re=>{f(re instanceof Error?re.message:"Could not cancel the login.")},"onError")}),C=ee({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 V$(re.sessionId);return re}catch(re){if(re instanceof dn&&re.status===404)return null;throw re}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[I,R]=(0,m.useState)(!1),T=ee({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>$t.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!I,retry:r((re,oe)=>oe instanceof dn&&oe.status===404?!1:re<3,"retry"),refetchInterval:r(re=>{const oe=re.state.data?.status;return oe&&a6.has(oe)?!1:i6},"refetchInterval")});(0,m.useEffect)(()=>{const re=T.data?.prompt??null;re&&b(re)},[T.data]);const A=T.data??w.data??null,D=A?.status??null,M=x,B=D?a6.has(D):!1,E=!!u&&!B,z=w.isPending||E||v==="saving",$=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if($.current||!C.isFetched)return;$.current=!0;const re=C.data;re&&(N.current=!0,f(null),b(re.prompt??null),h(re.sessionId))},[C.isFetched,C.data]),(0,m.useEffect)(()=>{const re=T.error;if(!(re instanceof dn&&re.status===404)||!N.current||I)return;R(!0);const oe=u;(async()=>(oe&&await $t.cancelAdapterAuthLogin(e,s,oe).catch(()=>{}),R(!1),k()))()},[T.error,I,u,e,s,k]);const q=(0,m.useRef)(!1),U=je({mutationFn:r(async()=>{const re=C.error;re instanceof V$&&await $t.cancelAdapterAuthLogin(e,s,re.sessionId)},"mutationFn"),onSuccess:r(async()=>{q.current=!1,$.current=!1,f(null),await C.refetch()},"onSuccess"),onError:r(()=>f("Could not cancel the previous sign-in. Retry before starting a new one."),"onError")}),O=(0,m.useRef)(w.mutate);O.current=w.mutate,(0,m.useEffect)(()=>{if(!(!a||q.current)){if(C.isError){q.current=!0,f(C.error instanceof Error?C.error.message:"Could not check for an active login.");return}C.isSuccess&&(q.current=!0,!C.data&&O.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),H=(0,m.useRef)(i);H.current=i,(0,m.useEffect)(()=>{D!=="authenticated"||K.current||(K.current=!0,H.current?.(u??void 0))},[D]);const Z=(0,m.useRef)(null),se=(0,m.useRef)(o);se.current=o;const ne=T.data?.codexAccountBinding??null,fe=(0,m.useCallback)(async re=>{const oe=se.current;if(oe){j("saving");try{await oe(re),j("bound")}catch{j("failed")}}},[]);(0,m.useEffect)(()=>{D!=="authenticated"||!u||Z.current!==u&&(!ne||!ne.companyIdentityDiffers||!se.current||(Z.current=u,fe(ne)))},[D,u,ne,fe]);const X=(0,m.useRef)(d);if(X.current=d,(0,m.useEffect)(()=>{X.current?.(M?.url??null)},[M]),l==="onboarding"){const re=B&&D&&D!=="authenticated";return(0,t.jsx)(XNe,{loading:!M&&!p&&!re,providerName:YNe(s),authorizationUrl:M?.url,mode:"displayed_code",children:p?(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:p}),C.error instanceof V$&&(0,t.jsx)(L,{type:"button",variant:"outline",disabled:U.isPending,onClick:r(()=>U.mutate(),"onClick"),children:"Cancel previous sign-in and retry"})]}):re?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D==="timed_out"?"The login timed out. Start it again.":D==="cancelled"?"The login was cancelled.":"The login did not finish. Start it again."}):(0,t.jsx)(Pet,{code:M?.code??"",autoCopy:!0})})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:KSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[E&&(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:S.isPending,onClick:r(()=>S.mutate(),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:z,onClick:r(()=>w.mutate(),"onClick"),children:"Sign in"})]})]}),p&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:p}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[E&&!M&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),E&&M&&(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Copy the code, then open the authentication page."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Code"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:M.code})]}),(0,t.jsx)(o6,{value:M.code,label:"Copy code"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Authentication URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:M.url})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(o6,{value:M.url,label:"Copy URL"}),(0,t.jsx)(L,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authentication page",title:"Open the authentication page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:M.url,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Vn,{className:"size-3"})})})]})]})]}),B&&D&&(0,t.jsx)(Mat,{status:D,message:A?.failure?.message??null}),D==="authenticated"&&v==="saving"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Binding this agent to the signed-in account..."})]}),D==="authenticated"&&v==="bound"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Agent bound to the signed-in account."})]}),D==="authenticated"&&v==="failed"&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro)",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 text-destructive"}),(0,t.jsx)("span",{className:"text-destructive",children:"Could not bind this agent to the signed-in account."}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-6 px-2 text-xs",onClick:r(()=>{ne&&fe(ne)},"onClick"),children:"Retry"})]})]})]})}r(Lat,"DisplayedCodeLoginPanel");var $at=new Set(["failed","timed_out","cancelled"]),Xte="The login did not finish. Start the login again.",Oat=9e5,Zte="The login timed out. Start the login again.";function Fat({companyId:e,adapterType:s,environmentId:n,onStored:a,onApplyStored:i,autoStart:o,onConnected:l,onCodeSubmitted:c,onSubmitFailed:d,chrome:u="panel",aiConnection:h,onPromptReady:p}){const[f,x]=(0,m.useState)(null),[b,v]=(0,m.useState)(null),[j,N]=(0,m.useState)(null),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(""),[I,R]=(0,m.useState)(null),[T,A]=(0,m.useState)(!1),[D,M]=(0,m.useState)(!1),[B,E]=(0,m.useState)(!1),[z,$]=(0,m.useState)(!1),q=(0,m.useRef)(!1),[U,O]=(0,m.useState)(!1),K=(0,m.useRef)(!1),H=r(()=>{v(null),N(null),k(!1),C(""),R(null),A(!1),M(!1),$(!1),E(!1),q.current=!1},"resetLocalState"),Z=ee({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await $t.getClaudeOAuthTokenStatus(e)}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),retry:r((tt,Pe)=>Pe instanceof dn&&Pe.status===404?!1:tt<2,"retry")}).data??null,se=je({mutationFn:r(()=>$t.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...Z&&!h?{overwrite:{expectedSecretId:Z.secretId,expectedLatestVersion:Z.latestVersion}}:{}}),"mutationFn"),onSuccess:r(tt=>{K.current=!1,H(),x(tt.sessionId)},"onSuccess"),onError:r(tt=>{v(tt instanceof Error?tt.message:"Could not start the login.")},"onError")}),ne=r(()=>{K.current=!1,x(null),H()},"clearActiveSession"),fe=je({mutationFn:r(()=>$t.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{ne()},"onSuccess"),onError:r(tt=>{if(tt instanceof dn&&tt.status===404){ne();return}v(tt instanceof Error?tt.message:"Could not cancel the login.")},"onError")}),X=(0,m.useCallback)(tt=>{$t.cancelClaudeSetupTokenLogin(e,tt).catch(()=>{})},[e]),re=ee({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const tt=await $t.getActiveClaudeSetupTokenLoginSession(e);if(!tt)return null;if(h&&tt.environmentId!==n||!!tt.aiConnection!=!!h||h&&(tt.aiConnection?.provider!==h.provider||tt.aiConnection?.method!==h.method||tt.aiConnection?.connectionId!==h.connectionId||tt.aiConnection?.ownership!==h.ownership||tt.aiConnection?.allAgents!==h.allAgents||JSON.stringify(tt.aiConnection?.agentIds)!==JSON.stringify(h.agentIds)))throw new Error("Another sign-in attempt is active. Finish or cancel it in its original account setup before starting this one.");return tt}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[oe,G]=(0,m.useState)(!1),Y=!!f&&!D&&!z&&!oe,Q=ee({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>$t.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:Y,retry:r((tt,Pe)=>Pe instanceof dn&&Pe.status===404?!1:tt<3,"retry"),refetchInterval:r(tt=>{if(D||z)return!1;const Pe=tt.state.data?.status;return Pe&&a6.has(Pe)?!1:i6},"refetchInterval")});(0,m.useEffect)(()=>{const tt=Q.error;if(tt instanceof dn&&tt.status===404){if(K.current){if(oe)return;G(!0);const Pe=f;(async()=>(Pe&&await $t.cancelClaudeSetupTokenLogin(e,Pe).catch(()=>{}),G(!1),ne()))();return}$(!0)}},[Q.error,oe,f,e]);const te=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(te.current||!re.isFetched)return;te.current=!0;const tt=re.data;tt&&(K.current=!0,H(),x(tt.sessionId),tt.prompt&&(N(tt.prompt.authorizationUrl),tt.prompt.transportAdvisory&&k(!0)))},[re.isFetched,re.data]);const ae=ee({queryKey:["claude-setup-token-prompt",e,f],enabled:Y&&!j,queryFn:r(async()=>{try{return await $t.getClaudeSetupTokenLoginPrompt(e,f)}catch(tt){if(tt instanceof dn&&tt.status===404)return null;throw tt}},"queryFn"),refetchInterval:r(tt=>D||tt.state.data?.authorizationUrl?!1:i6,"refetchInterval")});(0,m.useEffect)(()=>{const tt=ae.data?.authorizationUrl??null;tt&&N(tt),ae.data?.transportAdvisory&&k(!0)},[ae.data]);const le=je({mutationFn:r(tt=>$t.submitClaudeSetupTokenBrowserCode(e,f,tt),"mutationFn"),onError:r(tt=>{v(tt instanceof Error?tt.message:"Could not submit the browser code.")},"onError")}),he=je({mutationFn:r(()=>$t.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(tt=>{R(tt.storedSessionId),a?.(tt.storedSessionId)},"onSuccess"),onError:r(()=>{A(!0)},"onError")}),ce=Q.data?.status??se.data?.status??null,ge=Q.data?.expiresAt??se.data?.expiresAt??null,me=(0,m.useRef)(he.mutate);me.current=he.mutate,(0,m.useEffect)(()=>{ce==="authenticated"&&!q.current&&(q.current=!0,me.current())},[ce]);const ie=I!==null,ue=T||z||!!(ce&&$at.has(ce)),ke=ce==="authenticated"&&!ie&&!T,be=!!f&&!ie&&!ue&&!D,Ie=se.isPending||be;(0,m.useEffect)(()=>{if(!be)return;const tt=ge!==null?new Date(ge).getTime():NaN,Pe=Number.isFinite(tt)?Math.max(0,tt-Date.now()):Oat,Ce=setTimeout(()=>{f&&X(f),M(!0)},Pe);return()=>clearTimeout(Ce)},[be,ge,f,X]);const Ue=S.trim(),at=be&&!!j&&!ke&&ELe(Ue)&&!le.isPending&&!B,dt=(0,m.useRef)(c);dt.current=c;const de=(0,m.useRef)(d);de.current=d;const Be=r(()=>{at&&(v(null),le.mutate(Ue),E(!0),dt.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),pt=(0,m.useRef)(!1),vt=(0,m.useRef)(se.mutate);vt.current=se.mutate,(0,m.useEffect)(()=>{if(!(!o||pt.current)){if(re.isError){pt.current=!0,v(re.error instanceof Error?re.error.message:"Could not check for an active login.");return}re.isSuccess&&(pt.current=!0,!re.data&&vt.current())}},[o,re.isSuccess,re.isError,re.data,re.error]);const Le=(0,m.useRef)(Be);Le.current=Be;const Qe=u==="onboarding",ut=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Qe||!ut.current||(ut.current=!1,at&&Le.current())},[Qe,at,S]);const Ye=(0,m.useRef)(!1),it=(0,m.useRef)(l);it.current=l,(0,m.useEffect)(()=>{!ie||Ye.current||(Ye.current=!0,it.current?.(f??void 0))},[ie]),(0,m.useEffect)(()=>{B&&(!b&&!ue&&!D||(E(!1),de.current?.()))},[B,b,ue,D]);const kt=(0,m.useRef)(p);if(kt.current=p,(0,m.useEffect)(()=>{kt.current?.(j)},[j]),u==="onboarding"){const tt=ue||D;return(0,t.jsxs)(XNe,{loading:!j&&!b&&!tt,providerName:YNe(s),authorizationUrl:j??void 0,mode:"submitted_code",children:[w&&(0,t.jsxs)("p",{className:"flex items-start gap-2 pl-2 text-xs text-amber-700 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"mt-0.5 size-3 shrink-0"}),"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."]}),b?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:b}):tt?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D&&!ue?Zte:Xte}):(0,t.jsx)(i4,{value:S,onChange:C,onSubmit:Be,onPaste:r(()=>{ut.current=!0},"onPaste"),masked:!0,disabled:le.isPending||ke||B})]})}return(0,t.jsxs)("div",{className:"rounded-md border border-border bg-muted/40 px-3 py-2 flex flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-foreground",children:KSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[be&&(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2.5 text-xs text-muted-foreground hover:text-foreground",disabled:fe.isPending,onClick:r(()=>fe.mutate(),"onClick"),children:"Cancel"}),i&&Z&&!be&&!ie&&!U&&(0,t.jsx)(L,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),O(!0)},"onClick"),children:"Use saved login"}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:Ie,onClick:r(()=>se.mutate(),"onClick"),children:Z&&!be&&!ie?"Sign in to replace":"Sign in"})]})]}),Z&&!be&&!ie&&!U&&(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"You have a saved Claude login. Use it to bind this agent, or log in again to replace the stored token."}),U&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"The saved Claude login is bound to this agent now."})]}),b&&(0,t.jsx)("div",{role:"alert",className:"text-(length:--text-micro) text-destructive",children:b}),(0,t.jsxs)("div",{role:"status","aria-live":"polite",className:"space-y-2 empty:hidden",children:[be&&!j&&!ke&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),be&&j&&!ke&&(0,t.jsxs)("div",{className:"space-y-2",children:[w&&(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-200",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0 mt-0.5"}),(0,t.jsx)("span",{children:"This connection is not encrypted. The login code travels in clear text on this network. Continue only on a network you trust."})]}),(0,t.jsx)("div",{className:"text-(length:--text-micro) text-muted-foreground",children:"Open the authorization page, then enter the browser code it shows."}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"1. Authorization URL"}),(0,t.jsx)("span",{className:"font-mono text-xs text-foreground break-all",children:j})]}),(0,t.jsxs)("div",{className:"flex items-center",children:[(0,t.jsx)(o6,{value:j,label:"Copy URL"}),(0,t.jsx)(L,{asChild:!0,type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open the authorization page",title:"Open the authorization page",className:"text-muted-foreground hover:text-foreground",children:(0,t.jsx)("a",{href:j,target:"_blank",rel:"noreferrer noopener",children:(0,t.jsx)(Vn,{className:"size-3"})})})]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-wide text-muted-foreground",children:"2. Browser code"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{"aria-label":"Browser code",type:"text",autoComplete:"off",spellCheck:!1,value:S,onChange:r(tt=>C(tt.target.value),"onChange"),onKeyDown:r(tt=>{tt.key==="Enter"&&(tt.preventDefault(),Be())},"onKeyDown"),className:"flex-1 min-w-0 rounded-md border border-border bg-background px-2 py-1 font-mono text-xs text-foreground"}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2.5 text-xs",disabled:!at,onClick:Be,children:"Submit"})]})]})]}),ke&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(rt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),ie&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(gs,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:"Authenticated. The environment has credentials now."})]}),ue&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Xte})]}),D&&!ue&&!ie&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Es,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Zte})]})]})]})}r(Fat,"SubmittedBrowserCodeLoginPanel");function Bat({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(Bat,"AdapterEnvironmentResult$1");function WSe({value:e,onChange:s,disabledTypes:n}){const[a,i]=(0,m.useState)(!1),o=Ch(e),l=(0,m.useMemo)(()=>BSe(c=>rN[c]??Bf(c)).filter(c=>!n.has(c.value)),[n]);return(0,t.jsxs)(br,{open:a,onOpenChange:i,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[e==="opencode_local"?(0,t.jsx)(qq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{className:"truncate",children:rN[e]??Bf(e)}),o.experimental&&(0,t.jsx)(ese,{})]}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:l.map(c=>(0,t.jsxs)("button",{disabled:c.comingSoon,className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded",c.comingSoon?"opacity-40 cursor-not-allowed":"hover:bg-accent/50",c.value===e&&!c.comingSoon&&"bg-accent"),onClick:r(()=>{c.comingSoon||(s(c.value),i(!1))},"onClick"),children:[(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[c.value==="opencode_local"?(0,t.jsx)(qq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{children:c.label}),c.experimental&&(0,t.jsx)(ese,{})]}),c.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},c.value))})]})}r(WSe,"AdapterTypeDropdown");function ese(){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(ese,"ExperimentalBadge$1");function UW({models:e,value:s,onChange:n,open:a,onOpenChange:i,allowDefault:o,required:l,groupByProvider:c,preserveOrder:d,creatable:u,detectedModel:h,detectedModelCandidates:p,onDetectModel:f,onRefreshModels:x,refreshingModels:b,detectModelLabel:v,emptyDetectHint:j,defaultLabel:N}){const[w,k]=(0,m.useState)(""),[S,C]=(0,m.useState)(!1),I=e.find(E=>E.id===s),R=w.trim(),T=!!(u&&R&&!e.some(E=>E.id.toLowerCase()===R.toLowerCase())),A=(0,m.useMemo)(()=>{const E=new Set;h&&E.add(h);for(const z of p??[])z&&E.add(z);return E},[h,p]),D=(0,m.useMemo)(()=>e.filter(E=>{if(A.has(E.id))return!1;if(!w.trim())return!0;const z=w.toLowerCase(),$=Kq(E.id)??"";return E.id.toLowerCase().includes(z)||E.label.toLowerCase().includes(z)||$.toLowerCase().includes(z)}),[e,w,A]),M=(0,m.useMemo)(()=>{if(!c)return[{provider:"models",entries:d?D:[...D].sort((z,$)=>z.id.localeCompare($.id))}];const E=new Map;for(const z of D){const $=Kq(z.id)??"other",q=E.get($)??[];q.push(z),E.set($,q)}return Array.from(E.entries()).sort(([z],[$])=>z.localeCompare($)).map(([z,$])=>({provider:z,entries:[...$].sort((q,U)=>q.id.localeCompare(U.id))}))},[D,c,d]);async function B(){if(f){C(!0);try{const E=await f();E&&(n(E),i(!1),k(""))}finally{C(!1)}}}return r(B,"handleDetectModel"),(0,t.jsx)(Ss,{label:"Model",hint:Ni.model,children:(0,t.jsxs)(br,{open:a,onOpenChange:r(E=>{i(E),E||k("")},"onOpenChange"),children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!s&&"text-muted-foreground"),children:I?I.label:s||(o?N??"Default":l?"Select model (required)":"Select model")}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsxs)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:[(0,t.jsxs)("div",{className:"relative mb-1",children:[(0,t.jsx)("input",{className:"w-full px-2 py-1.5 pr-6 text-xs bg-transparent outline-none border-b border-border placeholder:text-muted-foreground/50",placeholder:u?"Search models... (type to create)":"Search models...",value:w,onChange:r(E=>k(E.target.value),"onChange"),autoFocus:!0}),w&&(0,t.jsx)("button",{type:"button",className:"absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:r(()=>k(""),"onClick"),children:(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,t.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),f&&!w.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{B()},"onClick"),disabled:S,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,t.jsx)("path",{d:"M3 3v5h5"})]}),S?"Detecting...":h?v?.replace(/^Detect\b/,"Re-detect")??"Re-detect from config":v??"Detect from config"]}),x&&!w.trim()&&(0,t.jsxs)("button",{type:"button",className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground",onClick:r(()=>{x()},"onClick"),disabled:b,children:[(0,t.jsxs)("svg",{"aria-hidden":"true",focusable:"false",className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,t.jsx)("path",{d:"M3 12a9 9 0 0 1 15.28-6.36L21 8"}),(0,t.jsx)("path",{d:"M21 3v5h-5"}),(0,t.jsx)("path",{d:"M21 12a9 9 0 0 1-15.28 6.36L3 16"}),(0,t.jsx)("path",{d:"M8 16H3v5"})]}),b?"Refreshing...":"Refresh models"]}),s&&(!e.some(E=>E.id===s)||A.has(s))&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded bg-accent/50"),onClick:r(()=>{i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:s,children:e.find(E=>E.id===s)?.label??s}),(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-green-500/15 text-green-400 border-green-500/20",children:"current"})]}),h&&h!==s&&(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(h),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:h,children:e.find(E=>E.id===h)?.label??h}),(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-blue-500/15 text-blue-400 border-blue-500/20",children:"detected"})]}),p?.filter(E=>E&&E!==h&&E!==s).map(E=>{const z=e.find($=>$.id===E);return(0,t.jsxs)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50"),onClick:r(()=>{n(E),i(!1)},"onClick"),children:[(0,t.jsx)("span",{className:"block w-full text-left truncate font-mono text-xs",title:E,children:z?.label??E}),(0,t.jsx)(ct,{variant:"outline",className:"ml-auto text-(length:--text-nano) px-1.5 bg-sky-500/15 text-sky-400 border-sky-500/20",children:"config"})]},`detected-${E}`)}),(0,t.jsxs)("div",{className:"max-h-(--sz-240px) overflow-y-auto",children:[o&&(0,t.jsx)("button",{type:"button",className:W("flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",!s&&"bg-accent"),onClick:r(()=>{n(""),i(!1)},"onClick"),children:"Default"}),T&&(0,t.jsxs)("button",{type:"button",className:"flex items-center justify-between gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",onClick:r(()=>{n(R),i(!1),k("")},"onClick"),children:[(0,t.jsx)("span",{children:"Use manual model"}),(0,t.jsx)("span",{className:"text-xs font-mono text-muted-foreground",children:R})]}),M.map(E=>(0,t.jsxs)("div",{className:"mb-1 last:mb-0",children:[c&&(0,t.jsxs)("div",{className:"px-2 py-1 text-(length:--text-nano) uppercase tracking-wide text-muted-foreground",children:[E.provider," (",E.entries.length,")"]}),E.entries.map(z=>(0,t.jsx)("button",{type:"button",className:W("flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",z.id===s&&"bg-accent"),onClick:r(()=>{n(z.id),i(!1)},"onClick"),children:(0,t.jsx)("span",{className:"block w-full text-left truncate",title:z.id,children:c?$et(z.id):z.label})},z.id))]},E.provider)),D.length===0&&!T&&A.size===0&&(0,t.jsx)("div",{className:"px-2 py-2 space-y-2",children:(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:f?j??"No model detected yet. Enter a provider/model manually.":"No models found."})})]})]})]})})}r(UW,"ModelDropdown");function zat({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(Ss,{label:"Thinking effort",hint:Ni.thinkingEffort,children:(0,t.jsxs)(br,{open:a,onOpenChange:i,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between",children:[(0,t.jsx)("span",{className:W(!e&&"text-muted-foreground"),children:o?.label??"Auto"}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(dr,{className:"w-(--radix-popover-trigger-width) p-1",align:"start",children:s.map(l=>(0,t.jsxs)("button",{className:W("flex items-center justify-between w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",l.id===e&&"bg-accent"),onClick:r(()=>{n(l.id),i(!1)},"onClick"),children:[(0,t.jsx)("span",{children:l.label}),l.id?(0,t.jsx)("span",{className:"text-xs text-muted-foreground font-mono",children:l.id}):null]},l.id||"auto"))})]})})}r(zat,"ThinkingEffortDropdown");function VSe(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=Hpe.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=HR();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(VSe,"useAgentAppearanceDraft");var rC=null,H2=new Set,aC={subscribe(e){return H2.add(e),()=>{H2.delete(e)}},getSnapshot(){return rC},acquire(e){if(rC)return!1;rC=e;for(const s of H2)s();return!0},release(e){if(rC===e){rC=null;for(const s of H2)s()}}};function B_({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)(()=>TN(s??e?.appearance,e?.id),[s,e?.appearance,e?.id]),b=(0,m.useRef)(null),v=(0,m.useRef)(null),j=(0,m.useRef)(null),N=(0,m.useRef)(Symbol("agent-character")),w=(0,m.useSyncExternalStore)(aC.subscribe,aC.getSnapshot,()=>null),[k,S]=(0,m.useState)(!1),[C,I]=(0,m.useState)(!0),[R,T]=(0,m.useState)(!1),[A,D]=(0,m.useState)(!1),M=k&&!C&&!R&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const B=matchMedia("(prefers-reduced-motion: reduce)"),E=r(()=>I(B.matches),"change");E(),B.addEventListener("change",E);const z=new IntersectionObserver($=>S($[0]?.isIntersecting??!1));return b.current&&z.observe(b.current),()=>{z.disconnect(),B.removeEventListener("change",E)}},[]),(0,m.useEffect)(()=>{M&&w===null&&aC.acquire(N.current),M||aC.release(N.current)},[M,w]),(0,m.useEffect)(()=>()=>aC.release(N.current),[]),(0,m.useEffect)(()=>{if(!M||w!==N.current)return;let B=!1;return D(!1),Promise.all([Jc(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),Jc(()=>import("./definition-D733B7hW.js"),__vite__mapDeps([2,3,1]))]).then(([E,z])=>{B||!v.current||(j.current=E.createCharacter(v.current,z.characterDefinition(x,i),{animation:z.animationId(a),trackingRegion:l?.current??b.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>T(!0),"onError")}),D(!0))}).catch(()=>{B||T(!0)}),()=>{B=!0,j.current?.destroy(),j.current=null,D(!1)}},[M,w,l,c,n,d,u]),(0,m.useEffect)(()=>{j.current&&Jc(()=>import("./definition-D733B7hW.js").then(B=>{j.current?.setDefinition(B.characterDefinition(x,i)),j.current?.setAnimation(B.animationId(a))}),__vite__mapDeps([2,3,1]))},[x,i,a,A]),(0,t.jsxs)("span",{ref:b,role:p?"img":void 0,"aria-label":p,"aria-hidden":p?void 0:!0,className:W("relative inline-block shrink-0",KFe[n],h),children:[(0,t.jsx)(gr,{agent:e,appearance:x,size:n<256?256:n,name:f,pose:a,muted:i,className:W("size-full",A&&"invisible")}),(0,t.jsx)("span",{ref:v,className:"absolute inset-0"})]})}r(B_,"AgentCharacter");var qat=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function HSe(e,{cloud:s,nativeRunnerEnabled:n}){return e==="paperclip_runner"?n:s?qat.has(e):!0}r(HSe,"isNewAgentAdapterAllowed");var Uat={claude_local:{src:"/brands/claude-color.svg"},codex_local:{src:"/brands/codex-color.svg"},gemini_local:{src:"/brands/adapters/gemini-color.svg"},kimi_local:{src:"/brands/adapters/kimi-color-light.svg",dark:"/brands/adapters/kimi-color.svg"},...Object.fromEntries([["cursor","cursor"],["cursor_cloud","cursor"],["grok_local","grok"],["hermes_local","hermesagent"],["hermes_gateway","hermesagent"],["pi_local","pi"]].map(([e,s])=>[e,{src:`/brands/adapters/${s}.svg`,dark:`/brands/adapters/${s}-dark.svg`}]))};function KW({type:e,className:s="size-6"}){const n=Ch(e).icon,a=Uat[e];return a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("img",{src:a.src,className:W("shrink-0 object-contain",a.dark&&"dark:hidden",s),alt:""}),a.dark&&(0,t.jsx)("img",{src:a.dark,className:W("hidden shrink-0 object-contain dark:block",s),alt:""})]}):(0,t.jsx)(n,{className:s})}r(KW,"AdapterMark");function Kat(){const{selectedCompanyId:e}=ps(),{appearance:s}=VSe(`${e}:new-agent`);return(0,t.jsx)(B_,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(Kat,"AgentBasicsCharacter");function GSe({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!$c(),c=ee({queryKey:P.instance.experimentalSettings,queryFn:Nr.getExperimental,enabled:e,retry:!1}),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(a),[f,x]=(0,m.useState)("codex"),[b,v]=(0,m.useState)("name"),{data:j,isPending:N,error:w}=ee({queryKey:P.adapters.all,queryFn:uh.list,enabled:e}),k=(j??[]).filter(C=>C.loaded&&!C.disabled&&HSe(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Ch(C.type).comingSoon),S=k.some(C=>C.type===h);return(0,t.jsx)(Ys,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Js,{className:W("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",b==="name"&&"sm:max-w-(--sz-560px)"),children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 px-6 py-5 text-xs text-muted-foreground","aria-label":"New agent progress",children:[(0,t.jsx)("span",{className:W(b==="name"&&"font-medium text-foreground"),children:"1. Name"}),(0,t.jsx)(En,{className:"size-3"}),(0,t.jsx)("span",{className:W(b==="adapter"&&"font-medium text-foreground"),children:"2. Adapter"})]}),(0,t.jsxs)("form",{className:"flex min-h-0 flex-col",onSubmit:r(C=>{C.preventDefault(),d.trim()&&(b==="name"?v("adapter"):S&&n({name:d.trim(),adapterType:h,runnerProvider:f}))},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex min-h-0 flex-col gap-7 overflow-y-auto px-6 pb-8 sm:px-10",children:[(0,t.jsxs)("div",{className:"flex flex-col items-center gap-4 text-center",children:[e&&(0,t.jsx)(Kat,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Xs,{className:"text-3xl font-semibold tracking-tight",children:b==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(jn,{className:"text-base",children:b==="name"?"Start with a name. Make them your own.":`How should ${d.trim()} work?`})]})]}),b==="name"?(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("label",{htmlFor:o,className:"text-sm font-medium",children:"Agent name"}),(0,t.jsx)(ht,{id:o,autoFocus:!0,maxLength:100,placeholder:"e.g. Darnold",value:d,onChange:r(C=>u(C.target.value),"onChange"),className:"h-12 text-base"}),i&&(0,t.jsx)(L,{type:"button",variant:"link",className:"px-0 text-muted-foreground",onClick:i,children:"Invite an external agent"})]}):(0,t.jsxs)("fieldset",{className:"space-y-4",children:[(0,t.jsx)("legend",{className:"sr-only",children:"Adapter"}),N&&(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading adapters…"}),w&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w.message}),(0,t.jsx)("div",{className:W("grid grid-cols-2 gap-3",k.length!==4&&"sm:grid-cols-3"),children:k.map(C=>{const I=Ch(C.type);return(0,t.jsxs)("label",{className:"relative cursor-pointer",children:[(0,t.jsx)("input",{type:"radio",name:"new-agent-adapter",value:C.type,checked:h===C.type,onChange:r(()=>p(C.type),"onChange"),className:"peer sr-only"}),(0,t.jsxs)("span",{className:W("flex h-full flex-col items-center gap-2 rounded-lg border px-3 py-4 text-center peer-focus-visible:ring-2 peer-focus-visible:ring-ring hover:bg-accent/40",h===C.type?"border-foreground/40 bg-accent":"border-border bg-card"),children:[(0,t.jsx)(KW,{type:C.type}),(0,t.jsx)("span",{className:"text-sm font-medium",children:I.label}),h===C.type&&(0,t.jsx)(gs,{className:"absolute right-2 top-2 size-3.5"})]})]},C.type)})}),S&&h==="paperclip_runner"&&(0,t.jsxs)("label",{className:"flex flex-col gap-2 text-sm font-medium",children:["Runner",(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:f,onChange:r(C=>x(C.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"codex",children:"Codex (app server)"}),(0,t.jsx)("option",{value:"claude",children:"Claude (ACPX)"}),(0,t.jsx)("option",{value:"grok",children:"Grok Build (ACPX)"}),(0,t.jsx)("option",{value:"opencode",children:"OpenCode"})]})]})]})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-4 border-t border-border px-6 py-4",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:r(()=>b==="name"?s():v("name"),"onClick"),children:b==="name"?"Cancel":(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Tl,{className:"size-4"}),"Back"]})}),(0,t.jsxs)(L,{type:"submit",disabled:!d.trim()||b==="adapter"&&!S,children:[b==="name"?"Choose adapter":"Configure agent",(0,t.jsx)(pl,{className:"size-4"})]})]})]})]})})}r(GSe,"AgentBasicsDialog");var Wat={subscription:"Subscription",api:"API"};function Vat({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)(aS,{initial:!1,mode:"sync",children:(0,t.jsx)(Il.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:xte},animate:{opacity:1,y:0,transition:fet},exit:{opacity:0,y:xte,transition:xet},children:Wat[e]},e)})})}r(Vat,"CredentialTag");function Hat({source:e,mode:s,selected:n,onSelect:a,buttonRef:i,settling:o}){return(0,t.jsxs)("button",{ref:i,type:"button",role:"radio","aria-checked":n,onClick:a,className:W("flex min-w-0 flex-1 cursor-pointer flex-col items-center gap-1.5 self-stretch rounded-md border p-3","transition-(--tp-border-color-background-color) ease-(--motion-ease-standard)",o?"duration-(--motion-duration-slow)":"duration-(--motion-duration-fast)","outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",n?"border-foreground/40 bg-accent":"border-border bg-card hover:bg-accent/40"),children:[(0,t.jsx)("span",{className:"flex size-(--sz-30px) shrink-0 items-center justify-center",children:e.icon}),(0,t.jsx)("span",{className:"text-(length:--text-compact) font-medium text-foreground",children:e.label}),(0,t.jsx)(Vat,{mode:s})]})}r(Hat,"ModelSourceTile");function QSe({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)(aS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(Il.div,{layout:!0,transition:QNe,exit:{opacity:0,transition:_et},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(Hat,{source:h,mode:s,selected:h.id===n,onSelect:r(()=>a(h.id),"onSelect"),settling:l,buttonRef:r(p=>{p?c.current.set(h.id,p):c.current.delete(h.id)},"buttonRef")})},h.id))})})}r(QSe,"ModelSourceTiles");var H$={subscription:"Use API key instead",api:"Use subscription instead"},Gat={subscription:"api",api:"subscription"};function YSe({mode:e,onChange:s}){return(0,t.jsxs)("button",{type:"button",onClick:r(()=>s(Gat[e]),"onClick"),className:W("group grid cursor-pointer px-3 py-2 text-left text-sm font-medium","rounded-md outline-none focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)"),children:[Object.keys(H$).map(n=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:H$[n]},n)),(0,t.jsx)(aS,{initial:!1,mode:"sync",children:(0,t.jsx)(Il.span,{className:W("col-start-1 row-start-1 justify-self-start whitespace-nowrap","underline decoration-muted-foreground/40 underline-offset-4","text-muted-foreground transition-colors","group-hover:text-foreground group-hover:decoration-foreground/40"),initial:{opacity:0},animate:{opacity:1,transition:RW},exit:{opacity:0,transition:get},children:H$[e]},e)})]})}r(YSe,"CredentialModeLink");function JSe({onBack:e,primaryLabel:s,primaryDisabled:n,loading:a,loadingLabel:i,primaryIcon:o,onPrimary:l}){const c=a&&i?i:s,d=o??(a?"spinner":"arrow");return(0,t.jsxs)("div",{className:"flex items-center justify-between pt-9",children:[e?(0,t.jsxs)(L,{variant:"ghost",size:"lg",className:"rounded-full has-[>svg]:pl-4 has-[>svg]:pr-5",onClick:e,disabled:a,children:[(0,t.jsx)(Tl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(Il.div,{layout:!0,transition:yet,className:"min-w-0",children:(0,t.jsx)(L,{size:"lg",className:"w-full rounded-full px-6",onClick:l,disabled:n||a,children:(0,t.jsxs)(Il.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:jet,children:[d==="spinner"?(0,t.jsx)(rt,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(pl,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(JSe,"FooterNav");function XSe({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onBack:l,testConnection:c,testError:d,managedAccount:u}){const h=ee({queryKey:P.health,queryFn:du.get,enabled:i}),p=i&&(h.data?.localAiLoginSupported??h.data?.deploymentMode==="local_trusted"),f=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{f.current++},[]);const x=r(()=>{f.current++,D(!1),N(!1),k(null),C("preparing")},"cancel"),[b,v]=(0,m.useState)(u?.initialMethod==="api_key"?"api":u?"subscription":null),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)("preparing"),I=(0,m.useRef)("ready"),[R,T]=(0,m.useState)(""),[A,D]=(0,m.useState)(!1),[M,B]=(0,m.useState)(null),[E,z]=(0,m.useState)(null),$=s==="claude_local"?"Claude":s==="grok_local"?"Grok":"OpenAI",q=s==="claude_local"?"ANTHROPIC_API_KEY":s==="grok_local"?"XAI_API_KEY":"OPENAI_API_KEY",U=s==="claude_local"?"anthropic":s==="grok_local"?"xai":"openai",O=CNe(e,q),K=u?{...O,options:[],subscriptions:[],loading:!1}:O,[H,Z]=(0,m.useState)(null),se=K.subscriptions.length?K.subscriptions.find(ge=>ge.id===(H??K.subscriptions[0]?.id)):void 0,[ne,fe]=(0,m.useState)(null),X=K.options.find(ge=>ge.id===(ne??K.options[0]?.id)),re=u?{...K.storedLogin,data:void 0,isPending:!1,isError:!1}:K.storedLogin,oe=(0,m.useRef)(null),G=b??(K.subscriptions.length>0||s==="claude_local"&&!se&&re.data?"subscription":K.options.length?"api":"subscription"),Y=G==="api"?"api_key":"subscription",Q=u?.intent.connectionId&&(u.fixedMethod!==!1||u.initialMethod===Y),te=u?{...u.intent,connectionId:Q?u.intent.connectionId:void 0,name:Q?u.intent.name:u.nameForMethod?.(Y)??u.intent.name}:void 0,ae=Kwe(e,te??{provider:U,method:"subscription",name:`My ${$} subscription`,ownership:"personal",agentIds:[],allAgents:!0},p&&G==="subscription"&&!se&&!re.data,{allowHostClaude:h.data?.deploymentMode==="local_trusted"}),le=ee({queryKey:P.agents.authSignal(e,s,n),queryFn:r(()=>$t.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!u});async function he(){if(A||u?.disabled)return;const ge=++f.current;D(!0),B(null);try{if(u&&te){if(G==="subscription"&&!p)return;const ue=oe.current??await(G==="api"?Yc.create(e,{...te,method:"api_key",apiKey:R.trim()}):ae.connect(te));oe.current=ue,T(""),ge===f.current&&u.onComplete({...ue,method:G==="api"?"api_key":"subscription"});return}let me=G==="api"?X?X.aiConnection?{env:{},aiConnection:X.aiConnection}:{env:{[q]:X.binding}}:E??{env:{},credentials:{[q]:R.trim()}}:{...se?.aiConnection?{aiConnection:se.aiConnection}:{},env:se?.binding?{CODEX_HOME:se.binding}:{},...s==="claude_local"&&!se&&re.data?{env:Vw(),applyStoredClaudeLogin:!0}:{}};if(G==="subscription"&&p&&!se&&!re.data&&(oe.current??=await ae.connect(),me={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}}),me.credentials&&(await Yc.create(e,{provider:U,method:"api_key",name:`My ${$} API`,ownership:"personal",apiKey:me.credentials[q],agentIds:[],allAgents:!0}),me={env:{},aiConnection:{provider:U,method:"api_key",mode:"responsible_user"}}),ge!==f.current)return;G==="api"&&(T(""),X||z(me));const ie=await c(me);if(ge!==f.current)return;ie?o(me):B("The provider did not respond. Check the connection and try again.")}catch(me){if(ge!==f.current)return;u&&T(""),B(me instanceof Error?me.message:"Could not connect to the provider.")}finally{ge===f.current&&D(!1)}}r(he,"connect");const ce=G==="subscription"&&a&&n&&!se&&!K.loading&&!re.data&&(!!u||le.data?.status!=="present"||H==="");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(QSe,{label:"Connect your model provider",sources:[{id:s,label:$,icon:(0,t.jsx)(KW,{type:s})}],mode:G,selectedId:j?s:null,collapsed:j,onSelect:r(()=>{u?.disabled||N(!0)},"onSelect")}),(!j||u)&&!u?.fixedMethod&&(0,t.jsx)("div",{className:"-ml-3 mt-1",children:(0,t.jsx)(YSe,{mode:G,onChange:r(ge=>{x(),N(j),oe.current=null,v(ge),T(""),z(null),B(null)},"onChange")})}),!j&&K.options.length>0&&(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:[K.options.length," saved API"," ",K.options.length===1?"key available":"keys available","."]}),G==="subscription"&&K.subscriptions.length>0&&(0,t.jsx)(gk,{options:K.subscriptions,value:se?.id??"",onChange:Z,loading:!1,error:!1,kind:"subscription",disabled:A}),(0,t.jsx)(Il.div,{initial:!1,animate:{height:j?"auto":0,opacity:j?1:0},transition:{height:_d,opacity:r4},className:"overflow-hidden",children:j&&(0,t.jsx)("div",{className:"pt-5",children:G==="api"?(0,t.jsxs)(a4,{instruction:K.options.length?"Choose a saved API key or enter a new one":`Provide your ${$} API key to connect`,children:[(0,t.jsx)(gk,{...K,value:X?.id??"",disabled:A,onChange:r(ge=>{fe(ge),T(""),z(null),B(null)},"onChange")}),!X&&(0,t.jsx)(i4,{label:"API key",masked:!0,autoFocus:!0,value:R,placeholder:E?"Key entered. Retry the connection.":"Enter API key here",onChange:r(ge=>{fe(""),T(ge),z(null)},"onChange"),onSubmit:r(()=>{he()},"onSubmit"),disabled:A})]}):ce?(0,t.jsx)(qW,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:te??{provider:U,method:"subscription",name:`My ${$} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(ge=>{k(ge),C(me=>ge?me==="preparing"?"ready":me:"preparing")},"onPromptReady"),onCodeSubmitted:r(()=>{I.current=S==="waiting"?"waiting":"ready",C("connecting")},"onCodeSubmitted"),onSubmitFailed:r(()=>{C(ge=>ge==="connecting"?I.current:ge)},"onSubmitFailed"),onConnected:r(ge=>{if(u){if(!ge){B("The login did not return a saved connection. Try again.");return}const ie=f.current;C("connecting"),Yc.loginResult(e,ge).then(ue=>{ie===f.current&&u.onComplete({...ue,method:"subscription"})}).catch(()=>{ie===f.current&&(C("ready"),B("Could not retrieve the saved connection. Go back and retry."))});return}const me={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}};z(me),o(me)},"onConnected")}):se?null:p&&!re.data?(0,t.jsx)(EW,{adapterType:s,login:{...ae,retry:r(()=>{B(null),ae.retry()},"retry")}}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:re.data?"Use your saved Claude subscription for this agent.":a?"Use the existing provider connection for this environment.":"This environment does not support browser sign-in. Choose a sign-in environment or connect with an API key."})})}),G==="subscription"&&re.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not check your saved Claude subscription. Try again."}),M&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:d??M}),i&&h.isError&&(0,t.jsx)("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:"Could not prepare sign-in. Reload this page to try again."}),(0,t.jsx)(JSe,{onBack:r(()=>{j?x():l()},"onBack"),primaryLabel:j&&ce?S==="waiting"?"Waiting for code":S==="connecting"?"Connecting":`Sign in to ${$}`:A?"Connecting":G==="subscription"&&(re.data||se)?"Use saved subscription":G==="api"&&X?"Use saved API key":"Connect",primaryDisabled:u?.disabled||!!u&&G==="subscription"&&!a&&!p||i&&h.isPending||ae.preparing||!!ae.error||!u&&le.isPending||K.loading||s==="claude_local"&&re.isPending||!j&&!(G==="subscription"&&se)||!!ce&&(!w||S!=="ready")||G==="api"&&!R.trim()&&!E&&!X,loading:A,primaryIcon:j&&ce?S==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(ce){if(!w||S!=="ready")return;window.open(w,"_blank","noreferrer,noopener"),C("waiting")}else he()},"onPrimary")})]})}r(XSe,"AgentProviderConnection");function L5(e){return e.provider==="openrouter"?(0,t.jsx)(Yat,{...e}):(0,t.jsx)(Qat,{...e})}r(L5,"AiConnectionCredentialStep");function Qat({companyId:e,provider:s,initialMethod:n,fixedMethod:a,connectionId:i,name:o,hideName:l,nameForMethod:c,ownership:d,agentIds:u,allAgents:h,environmentId:p,onComplete:f,onCancel:x}){const[b,v]=(0,m.useState)(o),[j,N]=(0,m.useState)(),w=Pt(),k=ee({queryKey:P.environments.list(e),queryFn:r(()=>Pi.list(e),"queryFn")}),S=ee({queryKey:P.environments.capabilities(e),queryFn:r(()=>Pi.capabilities(e),"queryFn")}),C=ee({queryKey:P.instance.settings,queryFn:Nr.get}),I=ee({queryKey:P.instance.experimentalSettings,queryFn:Nr.getExperimental}),R=ee({queryKey:P.instance.generalSettings,queryFn:Nr.getGeneral}),T=zW(R.data?.executionMode,k.data??[]);let A=null,D;try{A=T.forced?T.kubernetesEnvironment?.id??null:iN({agentDefaultEnvironmentId:p??j,instanceDefaultEnvironmentId:C.data?.defaultEnvironmentId,localDefaultEnvironmentId:lN(k.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:oN(k.data),visibleEnvironmentIds:k.data?.map(O=>O.id)})}catch(O){D=O instanceof Error?O.message:"Could not resolve the sign-in environment."}const M=(k.data??[]).filter(O=>O.status==="active"&&(O.driver==="local"||O.driver==="sandbox"&&typeof O.config.provider=="string"&&S.data?.sandboxProviders?.[O.config.provider]?.supportsLoginPty===!0));!T.forced&&!p&&!j&&!M.some(O=>O.id===A)&&(A=M[0]?.id??null);const B=k.data?.find(O=>O.id===A),E=typeof B?.config.provider=="string"?B.config.provider:"",z=B?.driver==="sandbox"&&S.data?.sandboxProviders?.[E]?.supportsLoginPty===!0,$=[k,S,C,I,R].some(O=>O.isPending),q=D??[k,S,C,I,R].find(O=>O.error)?.error?.message,U={provider:s,method:"subscription",name:b,ownership:d,agentIds:u,allAgents:h,connectionId:i};return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-6",children:[!l&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(ht,{value:b,onChange:r(O=>v(O.target.value),"onChange"),disabled:!!i})]}),!p&&!T.forced&&M.length>1&&(0,t.jsxs)($a,{value:A??"",onValueChange:N,children:[(0,t.jsx)(La,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Ma,{placeholder:"Sign-in environment"})}),(0,t.jsx)(Da,{children:M.map(O=>(0,t.jsx)(Nn,{value:O.id,children:O.name},O.id))})]}),q&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:q}),$?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(XSe,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:A,canLogin:z,localEnvironment:B?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:U,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:$||!!q||!b.trim(),onComplete:r(O=>{w.invalidateQueries({queryKey:["ai-connections",e]}),f(O)},"onComplete")}},A??"local")]})}r(Qat,"SubscriptionConnectionStep");function Yat({companyId:e,provider:s,connectionId:n,name:a,hideName:i,nameForMethod:o,ownership:l,agentIds:c,allAgents:d,onComplete:u,onCancel:h}){const[p,f]=(0,m.useState)(a),[x,b]=(0,m.useState)(""),v=Pt(),j=je({mutationFn:r(()=>Yc.create(e,{provider:s,method:"api_key",name:n?p:o?.("api_key")??p,ownership:l,agentIds:c,allAgents:d,connectionId:n,apiKey:x}),"mutationFn"),onSuccess:r(N=>{v.invalidateQueries({queryKey:["ai-connections",e]}),u({...N,method:"api_key"})},"onSuccess"),onSettled:r(()=>b(""),"onSettled")});return(0,t.jsxs)("div",{className:"mx-auto w-full min-w-0 max-w-xl space-y-4",children:[!i&&(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:["Connection name",(0,t.jsx)(ht,{value:p,onChange:r(N=>f(N.target.value),"onChange"),disabled:!!n})]}),j.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error.message}),(0,t.jsx)(ZNe,{providerName:"OpenRouter",value:x,onChange:b,onSubmit:r(()=>j.mutate(),"onSubmit"),disabled:j.isPending,placeholder:"Enter API key here",autoFocus:!0}),(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)(L,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)(L,{disabled:!p.trim()||!x.trim()||j.isPending,onClick:r(()=>j.mutate(),"onClick"),children:j.isPending?"Connecting…":"Connect"})]})]})}r(Yat,"ApiKeyConnectionStep");var Jat=null;function oS(){const e=(0,m.useContext)(CI),{data:s,isFetched:n,isError:a}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:e!=null},e??(Jat??=new qN));return e?{enabled:!a&&s?.enableChatConnectors===!0,loaded:n}:{enabled:!1,loaded:!0}}r(oS,"useChatConnectorsEnabled");var Xat=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function ZSe(e){return e.replace(Xat,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(ZSe,"sanitizeProsumerCopy");var Zat={zapier:{tagline:"Reach 9,000+ apps your team already uses.",short:"Reach 9,000+ apps from your agents."},github:{tagline:"Read code and pull requests, comment on issues.",short:"Read code and pull requests, comment on issues."},slack:{tagline:"Send and read messages in your team's channels.",short:"Send and read messages in your channels."},notion:{tagline:"Read and update pages in your workspace.",short:"Read and update pages in your workspace."},railway:{tagline:"Inspect services, read logs, and manage deployments.",short:"Connect Railway for deployments, logs, and container access."},posthog:{tagline:"Explore product usage, errors, flags, and experiments.",short:"Sign in with PostHog. Project pinning and access controls are optional."},neon:{tagline:"Manage Postgres projects, branches, and queries.",short:"Sign in with Neon. Project pinning and read-only mode are optional."},linear:{tagline:"Create, update and read tickets.",short:"Create, update and read tickets."},"google-sheets":{tagline:"Read and update selected spreadsheets.",short:"Read spreadsheets or update the files you choose."},gmail:{tagline:"Read mail and create drafts for your review.",short:"Read mail and create drafts for your review."},"google-drive":{tagline:"Find, read, and create files in Drive.",short:"Find, read, and create files in Drive."},"google-docs":{tagline:"Read and update documents.",short:"Read and update documents."},"google-slides":{tagline:"Read and update presentations.",short:"Read and update presentations."},"google-calendar":{tagline:"Review calendars and manage events.",short:"Review calendars and manage events."},"google-chat":{tagline:"Read conversations and send messages.",short:"Read conversations and send messages."},"google-people":{tagline:"Look up contacts and people in your directory.",short:"Look up contacts and people in your directory."},"google-workspace-search":{tagline:"Search across your Google workspace.",short:"Search across your Google workspace."},hubspot:{tagline:"Look up contacts and update deal stages.",short:"Look up contacts and update deal stages."},intercom:{tagline:"Read and reply to customer conversations.",short:"Read and reply to customer conversations."},figma:{tagline:"Read files and post comments on frames.",short:"Read files and post comments on frames."},stripe:{tagline:"Read customers, invoices, and payouts.",short:"Read customers, invoices, and payouts."},context7:{tagline:"Look up up-to-date docs for your libraries.",short:"Look up up-to-date docs for your libraries."}},eit={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function eCe(e,s){const n=Zat[e];if(n)return n;if(s){const a=ZSe(s);if(a)return{tagline:a,short:a}}return eit}r(eCe,"appCopyFor");function tse(e,s,n){return n<=1?`Your ${e} key`:ZSe(s)||`Your ${e} key`}r(tse,"credentialFieldLabel");var tit=1500;function Cp(e=tit){const[s,n]=(0,m.useState)("idle"),a=(0,m.useRef)(null),i=(0,m.useRef)(0);(0,m.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const o=(0,m.useCallback)(async l=>{const c=++i.current;let d="copied";try{await fa(l)}catch{d="failed"}return i.current!==c||(n(d),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{i.current===c&&(n("idle"),a.current=null)},e)),d},[e]);return{status:s,copied:s==="copied",failed:s==="failed",copy:o}}r(Cp,"useCopyAction");function WW(){const e=Xc()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await fa(s),e?.({title:n,tone:"success",dedupeKey:`copy:${n}`}),!0}catch{return e?.({title:"Couldn’t copy to clipboard",body:"Select and copy the value manually.",tone:"error",dedupeKey:"copy-failed"}),!1}},[e])}r(WW,"useCopyToast");var sit="/cloud/connections/handoff",nit="/cloud/connections/reauth",$5="paperclip.cloud-oauth-handoff.v1",ng=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function VW(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new ng("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 ng("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(VW,"parseHandoff");function rit(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new ng("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new ng("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new ng("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(rit,"handoffFailure");async function ait(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(sit,{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 ng(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(ait,"postCloudHandoff");function iit(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!==nit||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(iit,"exactReauthenticationTarget");async function dN(e,s={}){const n=VW(e.handoff);if(!n){const l=d5(e.authorizationUrl);if(!l.ok)throw new ng(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await ait(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=iit(i.reauthenticationUrl,n.session);if(l)return l}throw rit(a.status,i?.error)}const o=d5(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new ng("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(dN,"prepareOAuthNavigation");function z_(e,s=window.sessionStorage){const n=VW({kind:"paperclip_cloud",session:e});if(!n)throw new ng("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem($5,JSON.stringify(a))}r(z_,"savePendingCloudHandoff");function oit(e=window.sessionStorage){const s=e.getItem($5);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 VW({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem($5),null}}r(oit,"readPendingCloudHandoff");function sse(e=window.sessionStorage){e.removeItem($5)}r(sse,"clearPendingCloudHandoff");function u4(e){return!!(e&&Vpe({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(u4,"appSupportsToolCatalogSetup");var lit=TLe.filter(e=>Upe(e).some(s=>rp(s))).map(e=>e.slug);function cit(e){return lit.some(s=>s===e)}r(cit,"isMcpDirectOAuthConnectSlug");function q_(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(q_,"appSourceConnectHref");function dit(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(dit,"appSourceResumeHref");function G$(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(G$,"vercelConnectSourceHref");function uit(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(uit,"resolveAppsConnectRouteKey");function mit(e,{chatConnectorsEnabled:s=!1}={}){if(e.get("byo")==="1")return!!(e.get("reconnect")?.trim()&&e.get("applicationId")?.trim()&&e.get("link")?.trim());const n=e.get("source")??"";if(/^ai-router-(?:[a-f0-9]{2})+$/.test(n))return!0;const a=RN(n);return!s&&a?.methods.some(i=>i.transport==="chat_sdk")&&!a.methods.some(i=>(i.purpose??"tool")!=="channel"&&i.transport!=="chat_sdk")?!1:SI(n)&&e.get("reconnect")?.trim()?!0:n==="agentmail"||s?Vpe(a):u4(a)}r(mit,"canEnterAppsConnect");var Q$=" for the organization",hit=" for the company";function nse(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(Q$)?n:a.endsWith(hit)?`${n.slice(0,n.length-16).trimEnd()}${Q$}`:`${n}${Q$}`}r(nse,"connectionNameForGrantKind");function pit(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(pit,"grantStatusLabel");function fit(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(fit,"grantStatusTone");function xit(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(xit,"grantAccountLabel");function git(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(git,"audienceUserIds");function bit(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(bit,"organizationGrant");function vit(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(vit,"personalGrantFor");function yit(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(yit,"memberLabel");var rse=0;function l6(){return rse+=1,{id:`header-${rse}`,name:"",value:""}}r(l6,"newCustomHeaderRow");function D1(e){try{return new URL(e).host||null}catch{return null}}r(D1,"endpointHost");function tCe(e=window.location.origin){const s=new URL("/api/tools/oauth/callback",e),n=s.hostname.toLowerCase().replace(/^\[|\]$/g,"");return s.protocol==="http:"&&(n==="127.0.0.1"||n==="::1")&&(s.hostname="localhost"),s.toString()}r(tCe,"oauthCallbackUrlForBrowser");function Y$(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(Y$,"defaultGenericMcpName");function ase(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(ase,"genericConnectGuidance");function sCe(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=ZLe(a);if(!i.ok)return OJ(a,i.reason);const o=r$e(n.value);if(!o.ok)return OJ(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(sCe,"customHeaderError");function jit(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(jit,"genericConnectPayload");function wit(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&&sCe(e.headers)===null:!0:!1}r(wit,"canSubmitGenericConnect");function uN(e){const s=new Set;let n=!1;for(const a of e??[])a.targetType==="company"?n=!0:a.targetType==="agent"&&s.add(a.targetId);return{onAll:n,agentIds:s}}r(uN,"installStateFrom");function nCe(e,s){return e.onAll||e.agentIds.has(s)}r(nCe,"isAgentInstalled");function rCe(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(rCe,"installPayload");var kit="Has access — tick to load its tools into this agent's context.";function aCe(e){return`paperclip.connector-enrollment-access:${e}`}r(aCe,"enrollmentAccessStorageKey");function Nit(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(Nit,"validEnrollmentAccessState");function Sit(e,s,n){try{window.sessionStorage.setItem(aCe(s),JSON.stringify({...n,companyId:e}))}catch{}}r(Sit,"saveEnrollmentAccessState");function Cit(e){const s=aCe(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Nit(a)?a:null}catch{return null}}r(Cit,"consumeEnrollmentAccessState");function ise(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(ise,"githubRecoveryUrl");function ose(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(ose,"oauthCallbackErrorMessage");var _it={key:"setup",success:"complete"};function lse(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(lse,"requestedConnectionInitialStep");function Iit(e){const s=e.galleryApps.find(a=>a.slug===e.requestedAppKey);if(s)return s;if(!e.reconnectConnection)return null;const n=e.applications.find(a=>a.id===e.reconnectConnection?.applicationId);return xg(n)!==e.requestedAppKey?null:SI(e.requestedAppKey)}r(Iit,"requestedConnectionEntry");function Ait(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?xg(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(Ait,"retainedReconnectMatches");function Tit(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(Tit,"isVercelConnectUnavailable");function Rit(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(Rit,"isConnectionDefinitionUnavailable");function Eit(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(Eit,"requestedConnectionSetupResolution");function cse(e,s,n,a){const i=_it[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(cse,"appConnectHref");function G2(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(G2,"withConnectionIntent");var dse=["Pick app","Add your key"],use={gallery:0,key:1},Pit={key:0},Mit=["Add MCP URL"],Dit=["Sign in"];function J$(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(J$,"defaultGrantKindFor");function Lit(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(Lit,"configuredAgentIdentity");function QC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(QC,"isGoogleSheetsRobotMethod");function iC(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(iC,"defaultMethodConfig");function Aw(e,s){if(!e)return[];const n=pA(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(Aw,"connectionMethodsForCredentialSource");function pA(e){return Upe(e).filter(s=>(s.purpose??"tool")!=="channel")}r(pA,"availableToolConnectionMethods");function Q2(e,s){const n=pA(e);return s?n.find(a=>a.key===s)??null:i7(n)}r(Q2,"availableToolConnectionMethod");function vk(e){return i7(e)}r(vk,"recommendedSetupConnectionMethod");function mse(e){return vk(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(mse,"recommendedManagedConnectorMethod");function hse(e){if(!e)return!1;const s=pA(e),n=s.length===1?s[0]:null;return!!(n&&rp(n)&&!M$e(n))}r(hse,"canUseAutomaticOAuthFastPath");function pse(e){if(!e)return null;const s=pA(e),n=s.length===1?s[0]:null;return n&&rp(n)?n:null}r(pse,"automaticOAuthMethod");function $it(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r($it,"appSourceSlug");function Oit(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(Oit,"connectionSourceSlug");function fse(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&$it(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)||Oit(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(fse,"reusableOAuthConnection");function iCe(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(iCe,"readConnectionIntentOAuthOutcome");function m4(e={}){const[s]=fi(),n=va(),{selectedCompanyId:a}=ps(),i=G9(),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&&j1(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||j1(l)||K3(l))),h=ee({queryKey:["tools","connection",d],queryFn:r(()=>Zt.getConnection(d),"queryFn"),enabled:u}),p=l||h.data?.config?.sourceTemplateKey,f=s.get("method")||h.data?.config?.connectionMethodKey;if(u&&h.isPending)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection…"});if(u&&h.isError)return(0,t.jsxs)("div",{role:"alert",className:"space-y-3 p-6",children:[(0,t.jsx)("p",{children:"Could not load this connection. Your saved access and credentials have not changed."}),(0,t.jsx)(L,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(K3(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"&&j1(p)&&(!f||GR(p,f))){const x=sfe(p,s.get("targetToolkit"));return(0,t.jsx)(hGe,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(Fit,{...e})}r(m4,"ConnectionSetupFlow");function Fit({additionalSettings:e,connectionSettings:s,additionalSettingsValid:n=!0,byoOnly:a=!1,credentialSource:i="paperclip_vault",host:o="page",serviceSlug:l,requestedAgentId:c,interactionId:d,forceNewConnection:u=!1,existingConnections:h=[],configuredConnection:p,onUseExisting:f,onComplete:x,onOAuthDeclined:b,aiConnection:v,onPhaseChange:j,onCancel:N,renderCredentialStep:w}={}){const k=Pt(),S=Mn(),C=(0,m.useCallback)((bt,_e)=>{o==="page"&&(_e?S(bt,_e):S(bt))},[o,S]),I=va(),{selectedCompany:R,selectedCompanyId:T}=ps(),{enabled:A}=oS(),{enabled:D}=G9(),{setBreadcrumbs:M}=Bn(),{pushToast:B}=xi(),[E]=fi(),z=d?.trim()||E.get("intent")?.trim()||null,$=I.appKey??E.get("appKey")??void 0,q=E.get("source")?.trim()||null,U=u||E.get("new")==="1",O=E.get("stage")?.trim()||null,K=E.get("method")?.trim()||null,H=E.get("resume")?.trim()||null,Z=E.get("oauth"),se=E.get("code"),ne=ise(E.get("installation_url")),fe=ise(E.get("management_url")),X=p?.id??(E.get("reconnect")?.trim()||null),re=E.get("identity")==="user"?"user":E.get("identity")==="organization"?"organization":null,oe=i==="vercel_connect",G=l??q,Y=i==="paperclip_vault"&&cit(G)?G:null,Q=uit({serviceSlug:l,appKey:$,sourceSlug:q}),te=(l??q??$)==="zapier",ae=te?void 0:Q,le=!!p||o==="page"&&(a||E.get("byo")==="1"),[he]=(0,m.useState)(()=>o==="page"&&E.get("cloud_connector")==="enrolled"&&ae?Cit(ae):null),[ce]=(0,m.useState)(()=>{const bt=E.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(bt)?bt:"",name:p?.name??E.get("name")?.trim()??"",applicationId:p?.applicationId??(E.get("applicationId")?.trim()||void 0)}}),[ge,me]=(0,m.useState)(()=>lse({requestedAppKey:ae,routeStage:O,resumeConnectionId:H,hasPrefilledLink:!!ce.link,zapierSource:te})),[ie,ue]=(0,m.useState)(null),[ke,be]=(0,m.useState)(""),[Ie,Ue]=(0,m.useState)(ce.link),[at,dt]=(0,m.useState)(ce.name||(te?"Zapier":"")),[de,Be]=(0,m.useState)(!1),[pt,vt]=(0,m.useState)(""),[Le,Qe]=(0,m.useState)("auto"),[ut,Ye]=(0,m.useState)(()=>[l6()]),[it,kt]=(0,m.useState)(""),[tt,Pe]=(0,m.useState)(""),[Ce,He]=(0,m.useState)(!1),[Je,lt]=(0,m.useState)(null),[Ee,Xe]=(0,m.useState)(!1),[Ae,De]=(0,m.useState)({}),[_t,ye]=(0,m.useState)(""),[gt,We]=(0,m.useState)(""),[Ot,zt]=(0,m.useState)(""),[Cs,ze]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[ft,Ut]=(0,m.useState)(null),[Ns,Is]=(0,m.useState)({}),[Ct,ds]=(0,m.useState)(""),[$e,xe]=(0,m.useState)(null),[Qt,Dt]=(0,m.useState)(null),[rs,ws]=(0,m.useState)({}),[Bs,er]=(0,m.useState)("all"),[Fe,st]=(0,m.useState)(new Set),[xt,Oe]=(0,m.useState)(()=>new Set(he?.agentIds??(c?[c]:[]))),[Bt,wt]=(0,m.useState)(he?.grantKind??re??(c?"user":"organization")),[Xt,Yt]=(0,m.useState)(he?.installChoice??(c?"specific":"all")),hs=!!(H&&(Z==="failed"||Z==="denied")),[Ts,as]=(0,m.useState)(hs?"error":"entry"),[Zn,en]=(0,m.useState)(()=>hs?ose(Z,se):null),[nr,tn]=(0,m.useState)(null),xn=(0,m.useRef)(!1),Ht=(0,m.useRef)(!1),qs=(0,m.useRef)(null),Vs=(0,m.useRef)(null),[Lt,is]=(0,m.useState)(null),Ms=(0,m.useRef)(null),[bs,gn]=(0,m.useState)(null),[Pn,$r]=(0,m.useState)(null),mt=(0,m.useRef)(null),[vs,Fs]=(0,m.useState)(h.length>0&&!!f),[Hs,zs]=(0,m.useState)(null),[Us,ur]=(0,m.useState)(null),[Dn,Er]=(0,m.useState)(null),Jn=(0,m.useCallback)(()=>{o!=="dialog"||Ms.current?.closed===!1||(Ms.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),tr=(0,m.useCallback)(bt=>{if(o!=="dialog"){Lm(bt);return}$r(bt);const _e=Ms.current;if(!_e||_e.closed){as("error"),en("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),j?.("needs_retry");return}_e.location.assign(bt),_e.focus()},[o,j]),pn=(0,m.useCallback)(()=>{Ms.current=null,en(null),as("redirecting"),j?.("authorizing")},[j]);(0,m.useEffect)(()=>{if(o!=="dialog"||Ts!=="redirecting")return;const bt=window.setInterval(()=>{Ms.current?.closed&&(as("error"),en("The sign-in window closed. If authorization did not finish, try again."),$r(null),j?.("needs_retry"))},1e3);return()=>window.clearInterval(bt)},[o,Ts,j]);const yt=(0,m.useCallback)(async bt=>{mt.current?.abort();const _e=new AbortController;mt.current=_e;try{const ot=await dN(bt,{signal:_e.signal});if(ot.kind==="reauthentication"){const Nt=o==="dialog"?Ms.current:window;if(!Nt||Nt.closed||!bt.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");z_(bt.handoff.session,Nt.sessionStorage),as("starting")}else tn(ot.host),as("redirecting");tr(ot.url)}catch(ot){if(_e.signal.aborted)return;as("error"),en(ot instanceof Error?ot.message:"Paperclip couldn’t start secure sign-in. Try again."),j?.("needs_retry")}finally{mt.current===_e&&(mt.current=null)}},[o,j,tr]);(0,m.useEffect)(()=>()=>mt.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!z)return;const bt=r(_e=>{const ot=iCe(_e,window.location.origin,z);if(ot==="connected"){as("entry"),$r(null),x?.({resolvedByCallback:!0});return}if(ot==="declined"){as("error"),en("Authorization was cancelled. You can try again."),j?.("needs_retry");return}ot==="failed"&&(as("error"),en("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",bt),()=>window.removeEventListener("message",bt)},[z,o,x,b]),(0,m.useEffect)(()=>{if(o!=="dialog"||z||!bs)return;let bt=!1,_e=!1;const ot=window.setInterval(async()=>{if(_e||bt)return;const Nt=Ms.current;if(!Nt||Nt.closed){gn(null),as("error"),en("The sign-in window closed. Try again to finish connecting GitHub.");return}let us;try{us=new URL(Nt.location.href)}catch{return}if(!(us.origin!==window.location.origin||!us.pathname.includes(bs))){if(us.searchParams.has("oauth")){gn(null),as("error"),en("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(us.searchParams.get("success")==="1"){_e=!0;try{const Ls=await Zt.getConnection(bs);!bt&&Ls.status==="active"&&(gn(null),Nt.close(),x?.({connectionId:Ls.id}))}catch{bt||(gn(null),as("error"),en("Could not confirm the connection. Try again."))}finally{_e=!1}}}},1e3);return()=>{bt=!0,window.clearInterval(ot)}},[z,bs,o,x]);const Ps=r(()=>{Qe("auto"),Ye([l6()]),kt(""),Pe(""),He(!1),lt(null),Xe(!1)},"resetGenericAuthState"),Zs=r(bt=>{if(o==="page"&&!z&&i==="paperclip_vault"&&j1(bt.slug)){C(`/apps/connect?source=${bt.slug}`);return}if(bt.slug==="zapier"){ue(null),be(""),Ue(""),dt("Zapier"),Be(!1),vt(""),Ps(),De({}),Dt(null),me("key"),C(G2("/apps/connect?source=zapier",z));return}if(i==="paperclip_vault"&&hse(bt)){C(q_(bt.slug,z));return}ue(bt),be(bt.name),Ue(""),dt(""),Be(!1),vt(""),Ps(),De({}),ye(""),We(""),zt("");const _e=vk(Aw(bt,i));ze(_e?.key??""),Is(iC(_e)),ds(""),xe(null),Dt(null),Oe(new Set(c?[c]:[])),Yt(c?"specific":"all"),wt(Br??J$(_e,!!c)),me("key"),C(i==="vercel_connect"?G2(G$(bt.slug),z):q_(bt.slug,z))},"useMatchedGalleryEntry"),Ze=r(()=>{me("gallery"),C(G2(i==="vercel_connect"?G$():a?"/apps/byo":"/apps",z))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return M([{label:"Connectors",href:"/apps"},{label:oe?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>M([])},[a,o,M,oe]);const At=ee({queryKey:P.apps.gallery(T??"__none__"),queryFn:r(()=>Zt.listGallery(T),"queryFn"),select:(0,m.useCallback)(bt=>z?{...bt,apps:bt.apps.map(_e=>({..._e,methods:_e.methods.filter(ot=>v?ot.ai?.provider===v.provider&&(v.mode==="responsible_user"||ot.ai.method===v.method):ot.transport!=="runtime_auth")})).filter(_e=>_e.methods.length>0)}:bt,[z,v?.provider,v?.method,v?.mode]),enabled:!!T}),fs=(0,m.useMemo)(()=>(At.data?.apps??[]).filter(bt=>D||!K3(bt.slug)).filter(bt=>bt.slug==="agentmail"||A||!bt.methods.some(_e=>_e.transport==="chat_sdk")||u4(bt)),[At.data,A,D]),Ks=ae?SI(ae):null,Ln=Ks?.methods.find(bt=>nk(bt)&&!rp(bt)),Cr=!(Ln&&Cs===Ln.key)&&!!Ks?.methods.some(bt=>bt.oauthStrategy==="paperclip_cloud_connector"||bt.oauthStrategy==="paperclip_id_connector"),Vr=!!ie?.methods.some(bt=>bt.oauthStrategy==="paperclip_cloud_connector"||bt.oauthStrategy==="paperclip_id_connector"),Pr=ie&&Cr&&!Vr?mse(Ks):null,[Ar,_r]=(0,m.useState)(null),jr=ee({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>Zt.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Ar?2e3:!1,enabled:!!(T&&Cr&&!Vr)}),[sr,Ga]=(0,m.useState)(null),ka=(0,m.useCallback)(()=>{Ms.current?.close(),Ms.current=null,_r(null)},[]),Ds=(0,m.useCallback)(()=>{!T||!ae||Sit(T,ae,{grantKind:Bt,installChoice:Xt,agentIds:Xt==="specific"?[...xt]:[]})},[Bt,xt,Xt,ae,T]),$n=(0,m.useCallback)(bt=>{const _e=d5(bt);if(!_e.ok){ka(),Ga(_e.message);return}if(o==="dialog"){_r(_e.url);const ot=Ms.current;ot&&!ot.closed?(ot.location.assign(_e.url),ot.focus()):Ga("Open authorization in a new tab to continue.");return}Lm(_e.url)},[o,ka]);(0,m.useEffect)(()=>{!Ar||jr.data?.status!=="active"||(ka(),Ga(null),At.refetch())},[Ar,jr.data?.status,At.refetch,ka]);const mr=je({mutationFn:r(()=>Zt.startCloudConnectorEnrollment(T,R?.name,ae?cse(ae,"key",i,{resumeConnectionId:H,reconnectConnectionId:X,interactionId:z})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(bt=>{if(!bt.verificationUrl){ka(),Ga("Paperclip Cloud did not return an enrollment link. Try again.");return}$n(bt.verificationUrl)},"onSuccess"),onError:r(bt=>{ka(),Ga(bt instanceof Error?bt.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),_n=ee({queryKey:P.tools.applications(T??"__none__"),queryFn:r(()=>Zt.listApplications(T),"queryFn"),enabled:!!T&&(!!Y||!!H||!!X),refetchOnMount:"always"}),on=ee({queryKey:P.tools.connections(T??"__none__"),queryFn:r(()=>Zt.listConnections(T),"queryFn"),enabled:!!T&&(!!Y||!!H||!!X),refetchOnMount:"always"}),Hr=(0,m.useMemo)(()=>u?null:fse(Y,_n.data?.applications??[],on.data?.connections??[],U?{applicationId:ce.applicationId,draftOnly:!0}:{}),[_n.data,on.data,U,Y,ce.applicationId,u]),ss=(0,m.useMemo)(()=>X?(on.data?.connections??[]).find(bt=>bt.id===X)??null:null,[on.data,X]),Hn=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!on.isFetchedAfterMount||!ss||Hn.current===ss.id)return;const bt=ss.config?.url??ss.transportConfig?.url??ss.transportConfig?.serverUrl??ss.config?.serverUrl;typeof bt!="string"||!/^https?:\/\//i.test(bt)||(Hn.current=ss.id,Ue(_e=>_e||bt))},[p,on.isFetchedAfterMount,ss]);const Gn=(0,m.useMemo)(()=>ss?(_n.data?.applications??[]).find(bt=>bt.id===ss.applicationId)??null:null,[_n.data,ss]),un=Ait({requestedAppKey:ae,byo:le,applicationId:ce.applicationId,reconnectConnection:ss,reconnectApplication:Gn}),Kn=(0,m.useMemo)(()=>H?(on.data?.connections??[]).find(bt=>bt.id===H)??null:null,[on.data,H]),Lr=Kn??ss,Br=Lr?Lr.credentialPolicy==="per_user"?"user":Lr.credentialPolicy==="per_agent"?"agent":"organization":re,Se=Kn?.authKind==="oauth"?Kn:Hr,Jt=Hr?Hr.credentialPolicy==="per_user"?"user":Hr.credentialPolicy==="per_agent"?"agent":"organization":null,ln=Br??Jt;(0,m.useEffect)(()=>{ln&&wt(ln)},[ln]);const rr=(0,m.useMemo)(()=>Ie&&!ie?w3(Ie,fs):null,[ie,fs,Ie]),ra=ie?Q2(ie,Cs||null):null,Ea=ra&&rp(ra)?ra:pse(ie),os=i==="paperclip_vault"&&Ea?ie:null,Re=i==="paperclip_vault"&&hse(ie)?ie:null,Kt=!!Y&&(!_n.isFetchedAfterMount||!on.isFetchedAfterMount),Vt=r(bt=>{me(bt),ie&&C(cse(ie.slug,bt,i,{connectionMethodKey:ie.methods.find(_e=>_e.key===Cs)?.ai?Cs:void 0,resumeConnectionId:H,reconnectConnectionId:X,interactionId:z}))},"setAppStep"),fn=Kn??ss??Se,an=ie?.agentInstructions,ar=ie&&an?ft?.slug===ie.slug?ft.value:fn?fn.agentInstructions??{...Kk(an),enabled:!1}:Kk(an):null,Mr=!ar||!!ar.text.trim(),qt=je({mutationFn:r(async bt=>(ar&&JSON.stringify(ar)!==JSON.stringify(bt.agentInstructions)&&await Zt.updateConnection(bt.id,{agentInstructions:ar}),Zt.startOAuth(bt.id,{asCurrentUser:bt.credentialPolicy==="per_user",...bt.credentialPolicy==="per_agent"?{asAgentId:Lit(bt)??[...xt][0]}:{},...z?{interactionId:z}:{}})),"mutationFn"),onSuccess:r(bt=>{yt(bt)},"onSuccess"),onError:r(bt=>{const _e=bt instanceof dn&&bt.body&&typeof bt.body=="object"?bt.body.details:null;as("error"),j?.("needs_retry"),en(_e?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":bt instanceof Error?bt.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),cs=qt.mutate,In=(0,m.useCallback)(bt=>{j?.("authorizing"),Jn(),o==="dialog"&&!z&&gn(bt.id),cs(bt)},[cs,j,Jn,o,z]),wr=r(async bt=>{if(c)return;const _e=rCe(T,(ln??Bt)!=="agent"&&Xt==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:xt});await Zt.putConnectionInstalls(bt,_e)},"applyAccessInstalls"),wn=ln??Bt,ya=je({mutationFn:r(async bt=>{const _e=bt??ie;let ot;if(_e){const Nt=ln??Bt,us=Q2(_e,Cs||null),Ls=QC(_e,us)?mq(Ct).ids:[],Na=ke.trim(),ta=nse(Na||_e.name,Nt);ot=await Zt.connectApp(T,{galleryKey:_e.slug,...ar?{agentInstructions:ar}:{},...Cs?{connectionMethodKey:Cs}:{},name:ta,credentialSource:i,...i==="paperclip_vault"?{credentialValues:Ae}:{},...i==="vercel_connect"?{vercelConnect:{connector:Ot.trim()}}:{},..._t.trim()?{oauthClient:{clientId:_t.trim(),...gt?{clientSecret:gt}:{}}}:{},configValues:QC(_e,us)?{allowedSpreadsheetIds:Ls}:Object.keys(Ns).length>0?Ns:void 0,applicationId:ce.applicationId,...H??qs.current?{resumeConnectionId:H??qs.current}:X?{reconnectConnectionId:X}:{},...Nt!=="organization"?{grantKind:Nt}:{},...Nt==="agent"?{subjectAgentId:[...xt][0]}:{}}),qs.current=null}else{const Nt=jit({link:Ie,name:at,authMode:Le,needsKey:de,keyValue:pt,headers:ut,oauthClientId:it,oauthClientSecret:tt}),us=nse(Nt.name??Y$(Ie)??"Custom app",wn);ot=await Zt.connectApp(T,{...Nt,...X?{reconnectConnectionId:X}:{},...te||rr?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:us,applicationId:ce.applicationId,...wn!=="organization"?{grantKind:wn}:{},...wn==="agent"?{subjectAgentId:[...xt][0]}:{}})}return ot.auth?.kind==="oauth"&&!H&&!X&&await wr(ot.connectionId),ot},"mutationFn"),onSuccess:r(bt=>{if(bt.auth?.kind==="oauth"){if(Dt(bt),bt.auth.manualClientRequired){lt(ase("oauth_manual_client_required",null)),Qe("oauth"),He(!0),Xe(!1);return}if(o==="dialog"||z){as("starting"),Xe(!ie),In(bt.connection);return}const ot=bt.auth.startUrl?.trim();if(!ot){as("starting"),Xe(!0),In(bt.connection);return}Xe(!0),yt({authorizationUrl:ot,handoff:bt.auth.handoff});return}lt(null),Dt(bt);const _e={};for(const ot of bt.actions.readOnly)_e[ot.catalogEntryId]=!0;for(const ot of bt.actions.canMakeChanges)_e[ot.catalogEntryId]=!0;ws(_e),to.mutate({result:bt,enabled:_e})},"onSuccess"),onError:r(bt=>{const _e=bt instanceof dn&&bt.body&&typeof bt.body=="object"?bt.body.details:null;if(os){as("error"),j?.("needs_retry"),en(_e?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":bt instanceof Error?bt.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!ie&&Ie){const ot=typeof _e?.code=="string"?_e.code:null,Nt=ase(ot,bt instanceof Error?bt.message:null);lt(Nt),Xe(!1),Nt.focus==="credentials"&&(Be(!0),He(!0));return}B({title:"Couldn’t connect",body:bt instanceof Error?bt.message:"Please check your key and try again.",tone:"error"})},"onError")}),vr=ya.mutate,Wi=(0,m.useCallback)(bt=>{const _e=bt??ie;(_e?Q2(_e,Cs||null):null)?.auth==="oauth"&&Jn(),vr(bt)},[Cs,ie,vr,Jn]);(0,m.useEffect)(()=>{if(!ae||At.isLoading||!At.data||X&&(!on.isFetchedAfterMount||!_n.isFetchedAfterMount))return;const bt=Iit({requestedAppKey:ae,galleryApps:At.data.apps,reconnectConnection:ss,applications:_n.data?.applications??[]}),_e=!!bt?.methods.some(ir=>ir.oauthStrategy==="paperclip_cloud_connector"||ir.oauthStrategy==="paperclip_id_connector");if(Cr&&!_e&&jr.isLoading)return;const ot=Aw(bt,i),Nt=v??(ss?.connectionPurpose==="ai"?FJ.safeParse(ss.config?.ai).data:void 0),us=ot.find(ir=>Nt?ir.ai?.provider===Nt.provider&&(!("mode"in Nt)||Nt.mode!=="responsible_user")&&ir.ai.method===Nt.method:ir.key===K)??(Cr&&!_e?mse(Ks):null)??vk(ot),Ls=ot.length===1?ot[0]:null,Na=i==="paperclip_vault"&&!!pse(bt),ta=Tit({credentialSource:i,available:At.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(X&&un)}),zr=ot.length===1&&Ls?.auth==="oauth"&&!rp(Ls)&&!nk(Ls),Sa=Rit({available:bt?.availability?.available,reconnectConnectionId:X,reconnectSourceMatches:un}),Ei=Eit({reconnectConnectionId:X,hasRequestedEntry:!!bt,supportedMethodCount:ot.length,unsupportedOAuth:zr,vercelUnavailable:ta,definitionUnavailable:Sa});if(Ei!=="ready"){if(ue(null),me("gallery"),Ei==="reconnect_unavailable"&&X){Er(X);return}C(G2(i==="vercel_connect"?G$():"/apps/connect",z),{replace:!0});return}if(Er(null),!!bt){if(ie?.slug!==bt.slug){ue(bt),be(bt.name),Ue(""),dt(""),Be(!1),vt(""),De({}),ye(""),We(""),zt(""),ze(us?.key??""),Is(iC(us)),ds(""),xe(null),Dt(null);const ir=he?.companyId===T?he:null;wt(Br??ir?.grantKind??J$(us,!!c)),Oe(new Set(ir?.agentIds??(c?[c]:[]))),Yt(ir?.installChoice??(c?"specific":"all")),me(lse({requestedAppKey:ae,routeStage:O,resumeConnectionId:H,hasPrefilledLink:!!ce.link,zapierSource:te}))}else Vr!==_e&&(ue(bt),ze(us?.key??""),Is(iC(us)));if(!(Na&&(!_n.isFetchedAfterMount||!on.isFetchedAfterMount))&&!(Na&&Ht.current)&&Na&&(_n.isError||on.isError)){as("error"),en("Paperclip couldn’t check for an existing connection. Try again."),me("key");return}}},[v,K,_n.isError,_n.isFetchedAfterMount,_n.data,on.isError,on.isFetchedAfterMount,jr.data?.configured,jr.isLoading,Cs,i,ie?.slug,Vr,At.data,At.isLoading,C,Br,ss,X,un,H,Ks,ae,c,he,O,te]),(0,m.useEffect)(()=>{Vs.current=null,is(null)},[H]),(0,m.useEffect)(()=>{const bt=Kn??ss;if(!bt||!ie||Vs.current===bt.id)return;const _e=e7(bt),ot=typeof _e.sourceTemplateKey=="string"?_e.sourceTemplateKey:null;if(ot&&ot!==ie.slug)return;const Nt=typeof _e.connectionMethodKey=="string"?_e.connectionMethodKey:null,us=Nt?Aw(ie,i).find(Na=>Na.key===Nt)??null:null;if(be(bt.name||ie.name),us){ze(us.key);const Na=_e.methodConfig&&typeof _e.methodConfig=="object"?_e.methodConfig:{};Is({...iC(us),...Object.fromEntries(Object.entries(Na).filter(ta=>typeof ta[1]=="string"||typeof ta[1]=="boolean"))})}const Ls=_e.oauth&&typeof _e.oauth=="object"?_e.oauth:null;Ls?.clientRegistrationSource==="manual"&&typeof Ls.clientId=="string"&&ye(Ls.clientId),Z==="failed"||Z==="denied"?(as("error"),en(ose(Z,se))):(as("entry"),en(null)),me("key"),Vs.current=bt.id,is(bt.id)},[i,ie,se,Z,Kn,ss]);const to=je({mutationFn:r(async bt=>{const{result:_e,enabled:ot}=bt,Nt=Object.entries(ot).filter(([,ta])=>ta).map(([ta])=>ta),us=jwe(_e,ta=>!!ot[ta]),Ls=Xt==="all"?"all_agents":{agentIds:Array.from(xt)},Na=await Zt.finishApp(T,_e.connectionId,{enabledCatalogEntryIds:Nt,askFirstCatalogEntryIds:us,...ar?{agentInstructions:ar}:{},access:Ls,...c?{preserveExistingAccess:!0}:{}});return await wr(_e.connectionId),Na},"mutationFn"),onSuccess:r(async(bt,_e)=>{await k.invalidateQueries({queryKey:["tools"]}),await k.invalidateQueries({queryKey:P.apps.attention(T)}),Vt("success"),x?.({connectionId:_e.result.connectionId})},"onSuccess"),onError:r(bt=>{Vt("key"),B({title:"Couldn’t finish setup",body:bt instanceof Error?bt.message:"Please try again.",tone:"error"})},"onError")});if(!T)return(0,t.jsx)("div",{className:"p-6 text-sm text-muted-foreground",children:"Select an organization to connect apps."});if((H||X)&&(on.isError||_n.isError))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t check the retained connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",onClick:r(async()=>{const[bt,_e]=await Promise.all([on.refetch(),_n.refetch()]);!bt.isError&&!_e.isError&&(en(null),as("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(H&&on.isFetchedAfterMount&&!Kn)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This setup can’t be resumed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The saved connection no longer exists or is not available to this organization."}),(0,t.jsx)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if(X&&on.isFetchedAfterMount&&_n.isFetchedAfterMount&&(!ss||!un))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:ss?"This reconnect link does not match the retained connection's provider.":"The retained connection no longer exists or is not available to this organization."}),(0,t.jsx)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if((H||X)&&At.isError)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Couldn’t load connection setup"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip couldn’t load the provider details needed to restore this connection. The retained connection was not changed."}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",onClick:r(()=>{At.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(X&&Dn===X)return(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"This connection can’t be reconnected"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Paperclip no longer has a supported setup method for this retained connection. The retained connection was not changed."}),(0,t.jsx)(L,{type:"button",variant:"outline",className:"mt-5",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]});if(H&&(!on.isFetchedAfterMount||At.isLoading||!ie||Lt!==Kn?.id))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading saved connection setup",children:[(0,t.jsx)(vn,{className:"h-8 w-48"}),(0,t.jsx)(vn,{className:"h-40 w-full rounded-xl"})]});if(X&&(!on.isFetchedAfterMount||!_n.isFetchedAfterMount||At.isLoading||ae&&!ie))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(vn,{className:"h-8 w-48"}),(0,t.jsx)(vn,{className:"h-40 w-full rounded-xl"})]});if(vs&&f)return(0,t.jsxs)("div",{className:"max-w-5xl","data-testid":"connection-existing-choice",children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsxs)("h1",{className:"text-2xl font-bold tracking-tight",children:["Use an existing ",ae?"connection":"app connection"]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Reuse a connection without changing who already has access, or connect a new one."})]}),(0,t.jsx)(W9,{choices:h.map(bt=>({id:bt.id,name:bt.name,description:bt.status==="active"&&bt.enabled?"Ready to use":"Setup needs attention"})),pendingId:Hs,onSelect:r(async bt=>{zs(bt),ur(null);try{await f(bt)}catch(_e){ur(_e instanceof Error?_e.message:"Couldn’t use this connection."),zs(null)}},"onSelect")}),Us?(0,t.jsx)(ha,{tone:"danger",className:"mt-4",children:Us}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>Fs(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),N?(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:N,children:"Cancel"}):null]})]});const _o=Aw(ie,i),Vi=Pr?[Pr]:_o,Me=ie?Cs?Vi.find(bt=>bt.key===Cs)??null:Vi[0]??null:null,ys=ie?Me?.auth??"none":Le==="none"?"none":Le==="oauth"?"oauth":"api_key",cn=ge==="key"?((bt,_e)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(lCe,{extra:bt,forceOpen:_e,companyId:T,sentence:m6({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,lockedAgentId:c??null,preserveAgentAccess:!!(os&&(Se||ss))}),notice:[At.data?.capabilities?.canCreateOrganizationGrant===!1?At.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,At.data?.capabilities?.canSetCompanyInstall===!1?At.data.capabilities.companyInstallReason??"Only someone who can configure this connection can give every agent access.":null,c?"This task grants access only to the agent that asked for it.":null].filter(ot=>!!ot),authKind:ys,grantKinds:ln?[ln]:Me?.grantKinds,grantKind:wn,setGrantKind:wt,installChoice:Xt,setInstallChoice:Yt,installAgentIds:xt,setInstallAgentIds:Oe,lockedAgentId:c,capabilities:At.data?.capabilities,githubIdentity:ie?.slug==="github",identityLoading:!!os&&Kt,preserveAgentAccess:!!(os&&(Se||ss)),disabled:ya.isPending||qt.isPending},"connection-defaults"),ie&&an&&ar&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(K9,{provider:ie.name,template:an,value:ar,onChange:r(ot=>Ut({slug:ie.slug,value:ot}),"onChange"),disabled:ya.isPending||qt.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,aa=os&&Ea&&nk(Ea)?Ea:null,Wa=aa&&os?(0,t.jsx)(u6,{entry:os,method:aa,callbackUrl:tCe(),clientId:_t,onClientIdChange:ye,clientSecret:gt,onClientSecretChange:We,required:!1}):null,Za=cn?.()??null,Li=Wa?cn?.(Wa,Ts==="error"||_t.trim().length>0)??null:Za,Fa=!!(os&&ge==="key"&&(Re||Ts!=="entry")),Jo=!!(ge==="key"&&ie&&Cr&&!Vr&&jr.data?.configured===!0),ja=!!(ge==="key"&&ie&&Cr&&!Vr&&(jr.isLoading||jr.isError||jr.data?.configured!==!0));if(Fa&&os)return(0,t.jsx)(c6,{entry:os,resuming:!!H,phase:Ts,error:Zn,recoveryActions:se==="github_installation_required"?{installationUrl:ne,managementUrl:fe}:void 0,authorizationHost:nr,authorizationUrl:Pn,guidance:ie?.slug==="railway"&&Me?(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsx)("p",{children:Me.guidanceMd}),(0,t.jsx)("ul",{className:"list-disc space-y-2 pl-5",children:Me.warnings?.map(bt=>(0,t.jsx)("li",{children:bt},bt))})]}):null,defaults:Li,settingsValid:n&&Mr,onOpenAuthorization:pn,onRetry:r(async()=>{const bt=!xn.current;xn.current=!0,en(null),as("starting");const _e=Qt?.connection??Se;if(_e&&Wa&&_t.trim()){qs.current=_e.id,Wi(os);return}if(_e){In(_e);return}if(bt&&!H&&!_n.isError&&!on.isError){Wi(os);return}Ht.current=!0;try{const[ot,Nt]=await Promise.all([_n.refetch(),on.refetch()]);if(ot.isError||Nt.isError){as("error"),en("Paperclip couldn’t check for an existing connection. Try again.");return}const us=(H?(Nt.data?.connections??[]).find(Ls=>Ls.id===H&&Ls.authKind==="oauth")??null:null)??fse(Y,ot.data?.applications??[],Nt.data?.connections??[],U?{applicationId:ce.applicationId,draftOnly:!0}:{});us&&!H&&wt(us.credentialPolicy==="per_user"?"user":us.credentialPolicy==="per_agent"?"agent":"organization"),us?In(us):ya.mutate(os)}finally{Ht.current=!1}},"onRetry"),onBack:r(()=>{mt.current?.abort(),as("entry"),en(null),Ze()},"onBack"),onCancel:r(()=>{mt.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});if(Ee&&!ie&&Ie&&ge==="key")return(0,t.jsx)(c6,{identity:{name:at.trim()||D1(Ie)||"this server",unverifiedHost:D1(Ie)},steps:{labels:dse,activeIndex:use.key},phase:Ts,error:Zn,authorizationHost:nr,authorizationUrl:Pn,defaults:Za,onOpenAuthorization:pn,onRetry:r(()=>{en(null);const bt=Qt?.connection;if(bt){as("starting"),In(bt);return}Xe(!1),as("entry")},"onRetry"),onBack:r(()=>{mt.current?.abort(),Xe(!1),as("entry"),en(null)},"onBack"),onCancel:r(()=>{mt.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});const Hi=Qt?.application.name??ie?.name??(at.trim()||Y$(Ie)||"this app"),Oo=oe?fs.filter(bt=>Aw(bt,i).length>0):fs,Xo=te?At.data?.apps.find(bt=>bt.slug==="zapier")??null:null,Fo=(ss?.connectionPurpose==="ai"?FJ.safeParse(ss.config?.ai).data:void 0)??ie?.methods.find(bt=>bt.key===Cs)?.ai??(!Cs&&ie?.methods.every(bt=>bt.ai)?ie.methods[0]?.ai:void 0),Gi=ie?w?.({app:ie,name:ke||ie.name,grantKind:wn,agentIds:[...xt],allAgents:Xt==="all",onBack:r(()=>Ze(),"onBack")})??(Fo&&T?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(L5,{companyId:T,provider:Fo.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:ss?.connectionPurpose==="ai"?(ss.config?.ai).method:Fo.method,connectionId:ss?.connectionPurpose==="ai"?ss.id:void 0,name:ss?.connectionPurpose==="ai"?ss.name:ke||`My ${ie.name} ${Fo.method==="subscription"?"subscription":"API"}`,ownership:(ss?.connectionPurpose==="ai"?ss.credentialPolicy==="shared":wn==="organization")?"shared":"personal",agentIds:[...xt],allAgents:Xt==="all",onCancel:r(()=>N?N():C("/apps"),"onCancel"),onComplete:r(bt=>{x?.({connectionId:bt.connectionId}),x||C(`/apps/${bt.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,Zo=ss?.connectionPurpose==="ai"?["Reconnect account"]:Gi!==void 0?["Connect account"]:te?Mit:ie&&Vi.length>1?["Choose connection"]:ie&&Vi[0]?.auth==="oauth"?["Sign in"]:QC(ie,Cs)?["Share sheet"]:ie?["Add your key"]:dse,Fc=ss?.connectionPurpose==="ai"?0:(te||ie)&&ge!=="gallery"&&ge!=="success"?Pit[ge]:ge==="success"?Zo.length:use[ge];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[ge!=="success"&&!(a&&ge==="gallery")&&(0,t.jsx)(GM,{subtitle:ge==="gallery"?oe?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":Zo.length<=1?void 0:`Step ${Fc+1} of ${Zo.length}`,step:ge,activeIndex:Fc,labels:Zo,appIdentity:te?{name:"Zapier",logoUrl:Xo?.branding.logoUrl??null,darkLogoUrl:Xo?.branding.darkLogoUrl??null}:ie&&ge!=="gallery"?{name:ie.name,logoUrl:ie.branding.logoUrl,darkLogoUrl:ie.branding.darkLogoUrl??null}:void 0,unverifiedHost:!ie&&!te&&ge!=="gallery"?D1(Ie):null,onCancel:N??(()=>C("/apps"))}),ge==="key"&&s&&(0,t.jsx)("div",{className:"mx-auto mb-6 max-w-xl",children:s}),ge==="gallery"&&(0,t.jsx)(zit,{loading:At.isLoading,initialLink:Ie,apps:Oo,vercelConnect:oe,vercelConnectAvailability:At.data?.credentialSources?.vercelConnect??null,byo:le,byoOnly:a,source:E.get("source"),onPick:Zs,onUseLink:r(bt=>{const _e=w3(bt,fs);ue(null),be(""),Ue(bt),dt(_e?.name??Y$(bt)??""),Be(!1),vt(""),De({}),ds(""),xe(null),Oe(new Set(c?[c]:[])),Yt(c?"specific":"all"),wt(Br??(c?"user":"organization")),me("key")},"onUseLink")}),Jo&&ie?(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("h2",{className:"text-lg font-semibold text-foreground",children:[ie.name," sign-in is unavailable"]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This instance is connected to Paperclip, but ",ie.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),Ln?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>ze(Ln.key),"onClick"),children:["Use your own ",ie.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:Ze,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:At.isFetching,onClick:r(()=>{At.refetch()},"onClick"),children:[At.isFetching?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):ge==="key"&&ie&&ja?(0,t.jsx)("div",{className:"mx-auto max-w-xl",children:(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("div",{className:"rounded-lg bg-muted p-2 text-muted-foreground",children:(0,t.jsx)(Z0,{className:"h-5 w-5"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Connect with Paperclip"}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["You must connect this instance to Paperclip to connect to ",ie.name," (you only need to do this once)."]})]})]}),Ln?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>ze(Ln.key),"onClick"),children:["Use your own ",ie.name," OAuth app"]}):null,jr.isError||sr?(0,t.jsx)(ha,{tone:"danger",className:"mt-4",children:sr??"Paperclip couldn’t check Cloud registration. Try again."}):null,Ar?(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Finish authorization in the opened window."," ",(0,t.jsx)("a",{className:"underline",href:Ar,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,Za,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:Ze,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:jr.isLoading||mr.isPending,onClick:r(()=>{Ga(null),Jn(),Ds(),mr.mutate()},"onClick"),children:[mr.isPending?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}):null,jr.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):ge==="key"&&ie&&Gi!==void 0?Gi:ge==="key"&&ie?(0,t.jsx)(Kit,{settingsValid:n&&Mr,entry:ie,error:ya.isError?ya.error instanceof Error?ya.error.message:"Please check your key and try again.":null,values:Ae,onChange:De,oauthClientId:_t,onOAuthClientIdChange:ye,oauthClientSecret:gt,canReuseOAuthClientSecret:!!(Lr?.config?.oauth&&Lr.config.oauth.clientId===_t.trim()&&Lr.hasSavedOAuthClientSecret),onOAuthClientSecretChange:We,credentialSource:i,vercelConnector:Ot,onVercelConnectorChange:zt,vercelConnectAvailability:At.data?.credentialSources?.vercelConnect??null,methodKey:Cs,onMethodChange:r(bt=>{ze(bt?.key??""),!Br&&bt?.grantKinds&&!bt.grantKinds.includes(Bt)&&wt(J$(bt,!!c)),De({}),ye(""),We(""),zt(""),Is(iC(bt))},"onMethodChange"),configValues:Ns,onConfigChange:Is,googleSheetsLinks:Ct,googleSheetsError:$e,onGoogleSheetsLinksChange:r(bt=>{ds(bt),xe(null)},"onGoogleSheetsLinksChange"),submitting:ya.isPending,renderDefaults:cn??void 0,onBack:Ze,onConnect:r(()=>{if(QC(ie,Cs)){const ot=mq(Ct);if(ot.invalidCount>0){xe("That doesn't look like a Google Sheets link.");return}if(ot.ids.length===0){xe("Paste at least one Google Sheets link.");return}}const bt=Q2(ie,Cs||null),_e=!!(bt?.credentialFields?.length||bt?.tenantFields?.some(ot=>!ot.hidden)||bt?.extensionFields?.some(ot=>!ot.hidden));if(bt&&rp(bt)&&Se&&!_e&&!_t.trim()){xn.current=!0,en(null),as("starting"),In(Se);return}bt&&rp(bt)&&(xn.current=!0,en(null),as("starting")),Wi()},"onConnect")}):null,ge==="key"&&!ie&&!Ie&&!te&&ae&&(0,t.jsxs)("div",{className:"mx-auto max-w-xl","aria-busy":"true","aria-label":`Loading ${ae} setup`,children:[(0,t.jsx)(vn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(vn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(vn,{className:"mt-8 h-11 w-40 rounded-md"})]}),ge==="key"&&!ie&&Ie&&!te&&(0,t.jsx)(qit,{link:Ie,name:at,needsKey:de,keyValue:pt,onKeyChange:vt,authMode:Le,onAuthModeChange:r(bt=>{Qe(bt),lt(null),bt!=="auto"&&Be(!1),bt!=="bearer"&&bt!=="auto"&&vt("")},"onAuthModeChange"),headers:ut,onHeadersChange:r(bt=>{Ye(bt),lt(null)},"onHeadersChange"),oauthClientId:it,onOAuthClientIdChange:kt,oauthClientSecret:tt,onOAuthClientSecretChange:Pe,advancedOpen:Ce,onAdvancedOpenChange:He,guidance:Je,matchedEntry:rr,onUseMatchedEntry:rr?()=>Zs(rr):void 0,submitting:ya.isPending||Ee,defaults:Za,onBack:Ze,onConnect:r(()=>{lt(null),ya.mutate(void 0)},"onConnect")}),ge==="key"&&!ie&&te&&(0,t.jsx)(Bit,{link:Ie,onLinkChange:Ue,submitting:ya.isPending,defaults:Za,onBack:Ze,onConnect:r(()=>ya.mutate(void 0),"onConnect")}),ge==="success"&&(0,t.jsx)(Git,{appName:Hi,logoUrl:ie?.branding.logoUrl,darkLogoUrl:ie?.branding.darkLogoUrl,summary:Hit({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,enabledCount:Object.values(rs).filter(Boolean).length}),statedDefault:m6({grantKind:wn,authKind:ys,installChoice:Xt,installCount:xt.size,lockedAgentId:c??null}),onDone:N??(()=>C("/apps"))})]})}r(Fit,"StandardConnectionSetupFlow");function c6({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:Dit,activeIndex:0},guidance:u,defaults:h,onRetry:p,settingsValid:f=!0,onOpenAuthorization:x,onBack:b,onCancel:v}){const j=e?.name??s?.name??"this server",N=e?null:s?.unverifiedHost??null,w=a==="entry"?{title:n?`Finish connecting ${j}`:`Connect ${j} to Paperclip`,body:n?`Your connection is saved. Continue in ${j} to approve access; its identity and agent access will stay the same.`:`Paperclip will open ${j} so you can choose a workspace and approve access.`}:a==="starting"?{title:"Preparing secure sign-in",body:`Paperclip is creating a secure ${j} connection.`}:a==="redirecting"?{title:`Opening ${j}`,body:l?`Continue at ${l} to choose a workspace and approve access. Only approve access if you recognize that address.`:`Continue in ${j} to choose a workspace and approve access.`}:{title:`${j} couldn’t connect`,body:i??"Paperclip couldn’t start secure sign-in. Try again."};return(0,t.jsxs)("div",{className:"max-w-5xl",children:[(0,t.jsx)(GM,{subtitle:"Secure MCP sign-in",step:"key",activeIndex:d.activeIndex,labels:d.labels,appIdentity:e?{name:e.name,logoUrl:e.branding.logoUrl,darkLogoUrl:e.branding.darkLogoUrl}:void 0,unverifiedHost:N,onCancel:v}),(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("span",{className:"mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background",children:a==="error"?(0,t.jsx)(vc,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(pd,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(rt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-xl font-bold tracking-tight",children:w.title}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:w.body}),N?(0,t.jsx)(HM,{host:N,className:"mt-2"}):null]})]}),a==="entry"&&u?(0,t.jsx)("div",{className:"mt-4",children:u}):null,a==="entry"||a==="error"?h:null,a==="error"&&o&&(o.installationUrl||o.managementUrl)?(0,t.jsxs)("div",{className:"mt-4 flex flex-wrap gap-2",children:[o.installationUrl?(0,t.jsx)(L,{type:"button",variant:"outline",asChild:!0,children:(0,t.jsxs)("a",{href:o.installationUrl,target:"_blank",rel:"noreferrer",children:["Install Paperclip on GitHub",(0,t.jsx)(eo,{className:"ml-1.5 h-3.5 w-3.5"})]})}):null,o.managementUrl?(0,t.jsx)(L,{type:"button",variant:"ghost",asChild:!0,children:(0,t.jsx)("a",{href:o.managementUrl,target:"_blank",rel:"noreferrer",children:"Manage repositories on GitHub"})}):null]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center gap-2",children:[a==="error"||a==="entry"?(0,t.jsxs)(L,{type:"button",onClick:p,disabled:!f,children:[a==="entry"?n?`Finish with ${j}`:`Continue to ${j}`:"Try again",a==="entry"?(0,t.jsx)(eo,{className:"h-4 w-4","aria-hidden":"true"}):null]}):(0,t.jsx)(L,{type:"button",disabled:!0,children:a==="redirecting"?`Opening ${j}…`:"Preparing…"}),c?(0,t.jsx)(L,{variant:"outline",asChild:!0,children:(0,t.jsx)("a",{href:c,target:"_blank",rel:"noopener noreferrer",onClick:x,children:"Open sign-in in a new tab"})}):null,(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:b,children:"Back"})]})]})]})}r(c6,"OAuthConnectStateScreen");function Bit({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=d6(e),c=l?new URL(l).hostname:"",d=c==="zapier.com"||c.endsWith(".zapier.com");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Zapier MCP URL"}),(0,t.jsx)(ht,{type:"password",autoComplete:"off",spellCheck:!1,value:e,onChange:r(u=>s(u.target.value),"onChange"),onKeyDown:r(u=>{u.key==="Enter"&&d&&!n&&o()},"onKeyDown"),placeholder:"https://mcp.zapier.com/api/v1/connect?token=…",className:"mt-2 h-11",autoFocus:!0}),e.trim()&&!d&&(0,t.jsx)("p",{className:"mt-2 text-xs text-destructive",children:"Paste a valid Zapier URL to continue."})]}),a,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:i,disabled:n,children:"Back"}),(0,t.jsxs)(L,{onClick:o,disabled:n||!d,children:[n&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(Bit,"ZapierConnectStep");function zit({loading:e,initialLink:s="",apps:n,byo:a=!1,byoOnly:i=!1,vercelConnect:o=!1,vercelConnectAvailability:l=null,source:c=null,onPick:d,onUseLink:u}){const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(s),b=(0,m.useRef)(!1);(0,m.useEffect)(()=>{b.current||x(s)},[s]);const[v,j]=(0,m.useState)(null),N=(0,m.useRef)(null),w=(0,m.useRef)(null),k=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!a||e&&!i||k.current||(i||N.current?.scrollIntoView?.({block:"center"}),w.current?.focus(),w.current?.select(),k.current=!0)},[a,i,e]);const S=(0,m.useMemo)(()=>{const A=h.trim().toLowerCase();return n.filter(D=>!A||D.name.toLowerCase().includes(A))},[n,h]),C=d6(f),I=C?w3(C,n):null,R=c==="zapier",T=r(()=>{const A=d6(f);if(!A){j("Paste a full http or https link.");return}j(null),u(A)},"continueWithLink");return e&&!i?(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:Array.from({length:8}).map((A,D)=>(0,t.jsx)(vn,{className:"h-32 w-full rounded-xl"},D))}):(0,t.jsxs)("div",{className:"space-y-6",children:[o?(0,t.jsxs)("div",{className:"rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-bold tracking-tight",children:"Connect through Vercel"}),(0,t.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:"Create and manage the provider connector in Vercel. Paperclip stores its reference and applies agent access, policy, approval, and audit controls here."})]}),l?(0,t.jsx)(L,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:(0,t.jsxs)("a",{href:l.manageUrl,target:"_blank",rel:"noreferrer",children:["Open Vercel Connect",(0,t.jsx)(eo,{className:"ml-2 h-3.5 w-3.5"})]})}):null]}),l?.available===!1?(0,t.jsx)(ha,{tone:"danger",compact:!0,className:"mt-4",children:l.reason??"Vercel Connect is unavailable on this instance."}):null]}):null,!i&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(oa,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ht,{value:h,onChange:r(A=>p(A.target.value),"onChange"),placeholder:"Search apps…",className:"h-11 pl-9"})]}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4",children:S.map(A=>{const D=eCe(A.slug,A.description),M=pA(A),B=M.length===0||M.every(z=>z.auth==="oauth"&&!rp(z)&&!nk(z)),E=A.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:B||E,title:E?A.availability?.reason??l?.reason??void 0:void 0,onClick:r(()=>d(A),"onClick"),className:W("flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",B||E?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(al,{name:A.name,logoUrl:A.branding.logoUrl,darkLogoUrl:A.branding.darkLogoUrl,size:36}),(0,t.jsx)("div",{className:"mt-3 text-sm font-bold text-foreground",children:A.name}),(0,t.jsx)("div",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:D.tagline}),(0,t.jsx)("div",{className:"mt-3 text-xs font-semibold text-foreground",children:E?(0,t.jsx)("span",{className:"text-muted-foreground",children:A.availability?.reason??l?.reason??"Unavailable on this instance."}):B?(0,t.jsx)("span",{className:"text-muted-foreground",children:"Unavailable"}):(0,t.jsx)("span",{children:"Connect →"})})]},A.slug)})}),S.length===0&&(0,t.jsxs)("div",{className:"py-10 text-center text-sm text-muted-foreground",children:["No apps match “",h,"”."]})]}),o?null:(0,t.jsxs)("div",{ref:N,className:W("grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",a&&"-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0"),children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[(0,t.jsx)(vc,{className:"h-4 w-4 text-muted-foreground"}),R?"Connect Zapier":a?"Connect your own MCP server":"Connect with a link"]}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:R?"Paste the complete MCP URL Zapier gives you, including its token.":a?"Paste your MCP server’s URL and every discovered tool will be available immediately.":"Paste a setup link from an app that is not listed here."}),!R&&(0,t.jsxs)("p",{className:"mt-1 text-xs text-muted-foreground",children:["Any remote tool URL works here — including a local MCP server like"," ",(0,t.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:"http://127.0.0.1:8848/mcp"}),"."]}),I&&(0,t.jsxs)("div",{className:"mt-3 flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(al,{name:I.name,logoUrl:I.branding.logoUrl,darkLogoUrl:I.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["This looks like ",I.name,"."]})]}),(0,t.jsx)(L,{type:"button",size:"sm",variant:"outline",disabled:I.availability?.available===!1,onClick:r(()=>{if(j(null),I.slug==="zapier"){T();return}d(I)},"onClick"),children:I.availability?.available===!1?"Not available":I.slug==="zapier"?"Continue":`Use ${I.name}`})]})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2 sm:min-w-(--sz-360px)",children:[(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(ht,{ref:w,type:R||I?.slug==="zapier"?"password":"url",autoComplete:"off",spellCheck:!1,"aria-label":"MCP server URL",value:f,onChange:r(A=>{b.current=!0,x(A.target.value),j(null)},"onChange"),onKeyDown:r(A=>{A.key==="Enter"&&T()},"onKeyDown"),placeholder:R?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:T,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(zit,"GalleryStep");function d6(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(d6,"normalizeAppLink");function qit({link:e,name:s,needsKey:n,keyValue:a,onKeyChange:i,authMode:o,onAuthModeChange:l,headers:c,onHeadersChange:d,oauthClientId:u,onOAuthClientIdChange:h,oauthClientSecret:p,onOAuthClientSecretChange:f,advancedOpen:x,onAdvancedOpenChange:b,guidance:v,matchedEntry:j,onUseMatchedEntry:N,submitting:w,defaults:k,onBack:S,onConnect:C}){const I=D1(e),R=o==="custom_headers"?sCe(c):null,T=wit({link:e,name:s,authMode:o,needsKey:n,keyValue:a,headers:c,oauthClientId:u,oauthClientSecret:p}),A=o==="auto"&&n||o==="bearer",D=j?.slug==="zapier"?Fpe(e):e,M=r((B,E)=>{d(c.map(z=>z.id===B?{...z,...E}:z))},"updateHeader");return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)("p",{className:"min-w-0 truncate font-mono text-sm text-muted-foreground",title:D,children:D}),(0,t.jsx)(HM,{host:I})]}),j&&N?(0,t.jsxs)("div",{className:"mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-sm",children:[(0,t.jsx)(al,{name:j.name,logoUrl:j.branding.logoUrl,darkLogoUrl:j.branding.darkLogoUrl,size:24}),(0,t.jsxs)("span",{className:"truncate",children:["Paperclip has a guided setup for ",j.name,"."]})]}),(0,t.jsxs)(L,{type:"button",size:"sm",variant:"outline",onClick:N,children:["Use ",j.name]})]}):null,v?(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(ha,{tone:"warning",title:v.title,children:v.body})}):null,(0,t.jsxs)("div",{className:"mt-6 space-y-6",children:[A?(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-key",children:"App key"}),(0,t.jsx)(ht,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r(B=>i(B.target.value),"onChange"),placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Grant this key read and write access to the resources your agents need. Paperclip cannot increase its permissions."})]})}):null,(0,t.jsxs)(gl,{open:x,onOpenChange:b,children:[(0,t.jsxs)(ec,{className:"flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40",children:["Advanced authentication",(0,t.jsx)(nn,{className:W("h-4 w-4 text-muted-foreground transition-transform",x&&"rotate-180")})]}),(0,t.jsxs)(xl,{className:"space-y-5 pt-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Only needed when the server's docs are specific about how to authenticate."}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:xse.map(B=>(0,t.jsx)(Uit,{label:B.label,selected:o===B.mode,onClick:r(()=>l(B.mode),"onClick")},B.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:xse.find(B=>B.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map(B=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(ht,{value:B.name,onChange:r(E=>M(B.id,{name:E.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(ht,{type:"password",autoComplete:"off",value:B.value,onChange:r(E=>M(B.id,{value:E.target.value}),"onChange"),placeholder:"Value","aria-label":B.name.trim()?`Value for ${B.name.trim()}`:"Header value",className:"h-10 font-mono"}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"sm",className:"h-10 shrink-0",onClick:r(()=>d(c.filter(E=>E.id!==B.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},B.id)),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,l6()]),"onClick"),children:"Add another header"}),R?(0,t.jsx)("p",{className:"text-xs text-destructive",children:R}):null]}):null,o==="oauth"?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the server's docs tell you to register Paperclip yourself first."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-id",children:"Client ID"}),(0,t.jsx)(ht,{id:"generic-mcp-client-id",value:u,onChange:r(B=>h(B.target.value),"onChange"),autoComplete:"off",placeholder:"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"generic-mcp-client-secret",children:"Client secret"}),(0,t.jsx)(ht,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r(B=>f(B.target.value),"onChange"),placeholder:"Optional",className:"mt-2 h-11 font-mono"})]})]}):null]})]})]}),k,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:S,disabled:w,children:"Back"}),(0,t.jsxs)(L,{onClick:C,disabled:w||!T||!!R,children:[w&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(qit,"LinkConnectStep");var xse=[{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 Uit({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(Uit,"SegmentedOption");function Kit({settingsValid:e=!0,entry:s,error:n,values:a,onChange:i,oauthClientId:o,onOAuthClientIdChange:l,oauthClientSecret:c,canReuseOAuthClientSecret:d,onOAuthClientSecretChange:u,credentialSource:h,vercelConnector:p,onVercelConnectorChange:f,vercelConnectAvailability:x,methodKey:b,onMethodChange:v,configValues:j,onConfigChange:N,googleSheetsLinks:w,googleSheetsError:k,onGoogleSheetsLinksChange:S,submitting:C,renderDefaults:I,onBack:R,onConnect:T}){const A=(0,m.useMemo)(()=>Aw(s,h),[h,s]),D=b?A.find(Le=>Le.key===b)??null:vk(A),M=(0,m.useMemo)(()=>A.some(Le=>Le.capabilityProfile)?Array.from(A.reduce((Le,Qe)=>{const ut=Qe.capabilityProfile.key,Ye=Le.get(ut);return Ye?Ye.methods.push(Qe):Le.set(ut,{key:ut,label:Qe.capabilityProfile?.label??Qe.label??Qe.key,description:Qe.capabilityProfile?.description??Qe.whenToUse,methods:[Qe]}),Le},new Map)).map(([,Le])=>Le):[],[A]),B=D?.capabilityProfile?.key??D?.key??"",E=M.map(Le=>Le.key).join("|"),[z,$]=(0,m.useState)(B||vk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""));(0,m.useEffect)(()=>{if(B){$(B);return}$(Le=>M.some(Qe=>Qe.key===Le)?Le:vk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""))},[E,M,A,B]);const q=M.length>1?M.find(Le=>Le.key===z)?.methods??[]:A,U=(D?.credentialFields??[]).map(Le=>({...Le,configPath:Qpe(Le,D),helpUrl:D?.consoleLinks?.keys??D?.consoleLinks?.docs??""})),O=D?.credentialSources?.vercelConnect??null,K=h==="vercel_connect",H=K||U.every(Le=>Le.required===!1||(a[Le.configPath]?.trim().length??0)>0),Z=nk(D),se=Z&&!rp(D),ne=K||!se||o.trim().length>0&&(!D?.oauthClientSecretRequired||d||c.trim().length>0),fe=!K||p.trim().length>0,X=D?.auth==="oauth"&&Z?tCe():null,re=[...D?.tenantFields??[],...D?.extensionFields??[]],oe=re.filter(Le=>!Le.hidden),G=oe.filter(Le=>Le.advanced!==!0),Y=oe.filter(Le=>Le.advanced===!0),Q=re.every(Le=>{if(!Le.required)return!0;const Qe=j[Le.key];return typeof Qe=="boolean"||typeof Qe=="string"&&Qe.trim().length>0}),te=D?.configRequirements?.atLeastOneOf??[],ae=te.length===0||te.some(Le=>{const Qe=j[Le];return typeof Qe=="string"&&Qe.trim().length>0}),le=(M.length<=1||!!z)&&(q.length<=1?!!D:!!b),he=s.availability?.robotEmail??null,ce=s.availability?.available===!1,ge=!K&&Z&&!se,me=M.length>1||q.length>1,ie=M.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"What should Paperclip be able to do?"}),(0,t.jsx)(wm,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:z,onValueChange:r(Le=>{const Qe=M.find(ut=>ut.key===Le);Qe&&($(Le),v(i7(Qe.methods)))},"onValueChange"),options:M.map(Le=>({value:Le.key,title:Le.label,description:Le.description}))}),!z&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,ue=q.find(Le=>Le.oauthStrategy==="paperclip_cloud_connector"),ke=ue&&q.find(Le=>nk(Le)&&!rp(Le)),be=D?.key===ke?.key,Ie=(0,m.useId)(),Ue=ue&&ke&&q.length===2?(0,t.jsx)(L,{type:"button",variant:"link",className:"h-auto p-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground","aria-expanded":be,"aria-controls":Ie,disabled:C,onClick:r(()=>v(be?ue:ke),"onClick"),children:be?"Use Paperclip instead":`Use your own ${NLe(ue.connectorProfile??"")?"Google":s.name} OAuth app`}):q.length>1?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"How do you want to connect?"}),(0,t.jsx)(wm,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:b,onValueChange:r(Le=>{const Qe=q.find(ut=>ut.key===Le);Qe&&v(Qe)},"onValueChange"),options:q.map(Le=>({value:Le.key,title:Le.label??(Le.auth==="oauth"?`Sign in with ${s.name}`:"Use an API key")}))}),!D&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose a connection method to continue."})]}):null,at=Y.length>0||ge||me,dt=be||!le,de=at?(0,t.jsxs)("div",{className:"space-y-6",children:[ie,Ue,Y.map(Le=>(0,t.jsx)(gse,{field:Le,value:j[Le.key],onChange:r(Qe=>N({...j,[Le.key]:Qe}),"onChange")},Le.key)),ge?(0,t.jsx)(u6,{entry:s,method:D,callbackUrl:X,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!1}):null]}):null,Be=I?.(de,dt)??null;if(QC(s,D)){const Le=mq(w),Qe=e&&!ce&&!!he&&w.trim().length>0;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[ie,he?(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Share each sheet with this email"}),(0,t.jsxs)("div",{className:"mt-2 flex min-w-0 flex-col gap-2 sm:flex-row",children:[(0,t.jsx)("div",{title:he,className:"min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all",children:he}),(0,t.jsx)(oCe,{value:he,ariaLabel:"Copy sharing email"})]}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below."})]}):(0,t.jsx)("div",{className:"rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground",children:"Google Sheets is not available on this instance yet."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paste links to the sheets you shared"}),(0,t.jsx)(Cn,{value:w,onChange:r(ut=>S(ut.target.value),"onChange"),placeholder:"https://docs.google.com/spreadsheets/d/...",className:"mt-2 min-h-28"}),(0,t.jsx)("div",{className:"mt-2 text-xs text-muted-foreground",children:Le.ids.length>0?`${Le.ids.length} ${Le.ids.length===1?"sheet":"sheets"} ready to connect.`:"Paste one link per line. Both .../edit and .../edit#gid=... links work."}),k&&(0,t.jsx)("div",{className:"mt-2 text-xs text-destructive",children:k})]})]}),Be,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:R,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:T,disabled:C||!Qe,children:[C&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":"Connect"]})]})]})}const pt=D?.connectorProfile==="asana.mcp",vt=pt?null:D?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[vt?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:vt,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground",children:["Review requirements",(0,t.jsx)(eo,{className:"h-3 w-3"})]})}):null,(0,t.jsxs)("div",{className:"space-y-6",children:[pt?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Sign in with Asana to choose your workspace and connect it to Paperclip."}):null,D?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[D.capabilityProfile.label,": ",D.capabilityProfile.description]}),K&&O&&x?(0,t.jsxs)("div",{className:"space-y-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Create or attach the connector in Vercel"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Paperclip does not copy Vercel’s setup forms. Finish connector setup there, then paste its UID below."}),(0,t.jsxs)("a",{href:x.manageUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Open Vercel Connect",(0,t.jsx)(eo,{className:"h-3 w-3"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"vercel-connect-connector",children:"Connector UID or ID"}),(0,t.jsx)(ht,{id:"vercel-connect-connector",value:p,onChange:r(Le=>f(Le.target.value),"onChange"),autoComplete:"off",placeholder:"service/my-connector or scl_…",className:"mt-2 h-11 font-mono"}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Paperclip validates the connector and stores only its reference and redacted verification metadata."})]})]}):null,n?(0,t.jsx)("div",{role:"alert",children:(0,t.jsx)(ha,{tone:"danger",children:n})}):null,G.map(Le=>(0,t.jsx)(gse,{field:Le,value:j[Le.key],onChange:r(Qe=>N({...j,[Le.key]:Qe}),"onChange")},Le.key)),!K&&D?.auth==="oauth"&&se?(0,t.jsx)("div",{id:Ie,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(u6,{entry:s,method:D,callbackUrl:X,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!0})}):null,K||!D||U.length===0?null:U.map(Le=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:tse(s.name,Le.label,U.length)}),(0,t.jsx)(ht,{type:Le.type==="text"&&Le.secret===!1?"text":"password","aria-label":tse(s.name,Le.label,U.length),autoComplete:"off",value:a[Le.configPath]??"",onChange:r(Qe=>i({...a,[Le.configPath]:Qe.target.value}),"onChange"),placeholder:Le.type==="text"&&Le.secret===!1?Le.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),Le.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:Le.helperMd}),Le.helpUrl&&(0,t.jsxs)("a",{href:Le.helpUrl,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2",children:["Where do I find this?",(0,t.jsx)(eo,{className:"h-3 w-3"})]})]},Le.configPath))]}),Be,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:R,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:T,disabled:C||!e||!le||!H||!ne||!fe||!Q||!ae,children:[C&&(0,t.jsx)(rt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":K?D?.auth==="oauth"?"Validate and continue":"Validate and connect":D?.auth==="oauth"?s.slug==="github"?"Continue to GitHub":"Continue to sign in":"Connect"]})]})]})}r(Kit,"KeyStep");function oCe({value:e,ariaLabel:s}){const{copied:n,failed:a,copy:i}=Cp();return(0,t.jsxs)(L,{type:"button",variant:"outline",className:"shrink-0","aria-label":s,onClick:r(()=>{i(e)},"onClick"),children:[n?(0,t.jsx)(gs,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(Ir,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(oCe,"CopyValueButton");function u6({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)(eo,{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)(oCe,{value:n,ariaLabel:"Copy callback URL"})]}),(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:["Add this exact URL to ",e.name," before continuing. It must match the authorization request."]})]}):null,(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-id",children:"Client ID"}),(0,t.jsx)(ht,{id:"curated-oauth-client-id",value:a,onChange:r(d=>i(d.target.value),"onChange"),autoComplete:"off",placeholder:c?"Required":"Optional",className:"mt-2 h-11 font-mono"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",htmlFor:"curated-oauth-client-secret",children:"Client secret"}),(0,t.jsx)(ht,{id:"curated-oauth-client-secret",type:"password",value:o,onChange:r(d=>l(d.target.value),"onChange"),autoComplete:"off",placeholder:s.oauthClientSecretRequired?"Required":"Optional for public clients",className:"mt-2 h-11 font-mono"})]})]})}r(u6,"OAuthClientFields");function gse({field:e,value:s,onChange:n}){return e.type==="checkbox"?(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4 rounded-lg border border-border p-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:e.label}),e.helperMd&&(0,t.jsx)("div",{className:"mt-1 text-xs text-muted-foreground",children:e.helperMd})]}),(0,t.jsx)(ci,{checked:s===!0,onCheckedChange:n})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:e.label}),e.type==="textarea"?(0,t.jsx)(Cn,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,className:"mt-2 min-h-24"}):e.type==="select"?(0,t.jsxs)("select",{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),className:"mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",children:[(0,t.jsx)("option",{value:"",disabled:!0,children:"Select an option"}),(e.options??[]).map(a=>(0,t.jsx)("option",{value:a.value,children:a.label},a.value))]}):(0,t.jsx)(ht,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,"aria-label":e.label,maxLength:e.validation?.maxLength,className:"mt-2 h-11"}),e.required&&(typeof s!="string"||!s.trim())&&(0,t.jsxs)("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.label," is required."]}),e.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:e.helperMd})]})}r(gse,"MethodConfigField");function Wit({companyId:e,...s}){const n=ee({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn")});return(0,t.jsx)(HW,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(Wit,"AccessStep");function HW({agents:e,agentsLoading:s=!1,authKind:n,grantKinds:a,grantKind:i,setGrantKind:o,installChoice:l,setInstallChoice:c,installAgentIds:d,setInstallAgentIds:u,lockedAgentId:h,capabilities:p,githubIdentity:f=!1,submitLabel:x,continuesToProvider:b=!1,identityLoading:v=!1,preserveAgentAccess:j=!1,pending:N=!1,hideFooter:w=!1,bare:k=!1,onBack:S,onContinue:C}){const I=p?.editableAgentIds,R=I?e.filter(U=>I.includes(U.id)):e,T=p?.canSetCompanyInstall??!0,A=p?.canCreateOrganizationGrant??!0,D=n!=="none",M=a??["user","organization"],B=(!D||i==="user"||i==="agent"||A)&&(j?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?T:d.size>0),E=h?e.find(U=>U.id===h)?.name??"the requesting agent":null,z=f?"Connect GitHub as":"Which humans can use this credential?",$=i==="agent"?"Which agent owns this GitHub account?":f&&i==="user"?"Which agents may use your GitHub when you’re responsible?":f?"Which agents may use the shared GitHub account?":"Which agents can use this connection?",q=f?$:"Which agents can use this connection?";return(0,t.jsxs)("div",{className:k?"":"mx-auto max-w-2xl",children:[(0,t.jsx)("div",{className:"overflow-hidden rounded-xl border border-border bg-background",children:(0,t.jsxs)("div",{className:"divide-y divide-border",children:[(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:z}),f&&i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This agent uses this GitHub account for everyone’s work, instead of the person giving instructions."}):null,v?(0,t.jsxs)("div",{className:"mt-4 grid gap-2 sm:grid-cols-2","aria-label":"Loading connection identity",children:[(0,t.jsx)(vn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(vn,{className:"h-20 w-full rounded-md"})]}):D&&M.length===1?(0,t.jsxs)("div",{className:"mt-4 flex items-center gap-3 rounded-md border border-border p-4",children:[M[0]==="user"?(0,t.jsx)(Ph,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):M[0]==="agent"?(0,t.jsx)(no,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(ck,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:M[0]==="user"?f?"My GitHub account":"Just me":M[0]==="agent"?"A dedicated account for an agent":f?"Shared organization GitHub account (advanced)":"Any human in the organization"}),f?(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:M[0]==="user"?"Agents use it only for runs where you are the responsible person.":M[0]==="agent"?"That agent always uses this account, regardless of who starts the run.":"Eligible agents use one shared credential, regardless of who starts the run."}):null]})]}):D?(0,t.jsx)(wm,{ariaLabel:f?z:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(U=>{const O=U;o(O),O==="agent"&&(c("specific"),d.size>1&&u(new Set([[...d][0]])))},"onValueChange"),options:[{value:"user",title:f?"My GitHub account":"Just me",description:f?"Agents use it only for runs where you are the responsible person.":void 0,icon:(0,t.jsx)(Ph,{className:"h-4 w-4","aria-hidden":"true"})},{value:"agent",title:"A dedicated account for an agent",description:f?"That agent always uses this account, regardless of who starts the run.":void 0,icon:(0,t.jsx)(no,{className:"h-4 w-4","aria-hidden":"true"})},{value:"organization",title:f?"Shared organization GitHub account (advanced)":"Any human in the organization",description:f?"Eligible agents use one shared credential, regardless of who starts the run.":void 0,icon:(0,t.jsx)(ck,{className:"h-4 w-4","aria-hidden":"true"}),accessibleLabel:A?f?"Shared organization GitHub account (advanced)":"Any human in the organization":`${f?"Shared organization GitHub account (advanced)":"Any human in the organization"}. Unavailable: ${p?.organizationGrantReason??"Only a connection manager can share this credential with the organization."}`,tooltip:A?void 0:p?.organizationGrantReason??"Only a connection manager can share this credential with the organization.",disabled:!A}].filter(U=>M.includes(U.value))}):(0,t.jsx)("p",{className:"mt-4 text-sm text-muted-foreground",children:"No identity required"})]}),(0,t.jsxs)("section",{className:"p-6",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold text-foreground",children:$}),j?(0,t.jsxs)("div",{className:"mt-4 flex items-start gap-3 rounded-md border border-border bg-muted/40 p-4",children:[(0,t.jsx)(ck,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary","aria-hidden":"true"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-sm font-medium text-foreground",children:"Existing agent access stays the same"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Reconnecting replaces the credential without changing which agents can use it."})]})]}):h?(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This task grants access only to ",(0,t.jsx)("span",{className:"font-medium text-foreground",children:E}),". Existing connection access is left unchanged."]}):i==="agent"?(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Choose exactly one agent. This identity cannot be shared with other agents."}):(0,t.jsx)(wm,{ariaLabel:q,className:"mt-4 sm:grid-cols-2",value:l,onValueChange:r(U=>c(U),"onValueChange"),options:[{value:"specific",title:f?"Only agents I choose":"Just agents I pick",description:f?i==="user"?"Only selected agents may use your GitHub when you’re responsible.":"Only selected agents may use the shared account.":void 0,icon:(0,t.jsx)(no,{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)(Vit,{}),accessibleLabel:T?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:T?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!T}]}),!j&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Zy,{agents:R,selectedAgentIds:d,onChange:r(U=>u(i==="agent"&&U.size>1?new Set([[...U].at(-1)]):U),"onChange"),loading:s,emptyMessage:"You cannot edit any agents yet.",showSelectionPreview:!1})}):null]})]})}),w?null:(0,t.jsxs)("div",{className:"mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,t.jsx)(L,{variant:"ghost",className:"w-full sm:w-auto",onClick:S,disabled:N,children:"Back"}),(0,t.jsxs)(L,{className:"w-full sm:w-auto",onClick:C,disabled:!B||v||N,children:[N?(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):null,x,!N&&b?(0,t.jsx)(eo,{className:"h-4 w-4","aria-hidden":"true"}):null]})]})]})}r(HW,"AccessStepContent");function m6(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(m6,"connectionDefaultSummarySentence");function lCe({companyId:e,agents:s,sentence:n,notice:a,extra:i,forceOpen:o=!1,disabled:l=!1,...c}){const[d,u]=(0,m.useState)(!1);return(0,t.jsxs)(gl,{open:d||o,onOpenChange:u,className:"mt-6 rounded-lg border border-border bg-muted/30 px-4 py-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n}),(0,t.jsx)(ec,{asChild:!0,children:(0,t.jsx)(L,{type:"button",variant:"link",className:"h-auto p-0 text-xs font-semibold underline underline-offset-2",disabled:l,children:"Change"})})]}),(a??[]).map(h=>(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:h},h)),(0,t.jsx)(xl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(HW,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(Wit,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(lCe,"ConnectionAccessDefaults");function Vit(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(no,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(no,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(Vit,"BotGroupIcon");function Hit(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(Hit,"accessSummaryLines");function Git({appName:e,logoUrl:s,darkLogoUrl:n,summary:a,statedDefault:i,onDone:o}){return(0,t.jsxs)("div",{className:"mx-auto max-w-md py-10 text-center",children:[(0,t.jsx)("div",{className:"mx-auto flex h-20 w-20 items-center justify-center rounded-full border-2 border-emerald-500 bg-emerald-500/10",children:(0,t.jsx)(gs,{className:"h-9 w-9 text-emerald-600 dark:text-emerald-400"})}),(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-center gap-2",children:[(0,t.jsx)(al,{name:e,logoUrl:s,darkLogoUrl:n,size:28}),(0,t.jsxs)("h2",{className:"text-2xl font-bold tracking-tight",children:[e," is ready."]})]}),i?(0,t.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:i}):null,(0,t.jsx)("dl",{className:"mx-auto mt-6 max-w-xs space-y-1 text-left",children:a.map(l=>(0,t.jsxs)("div",{className:"flex items-baseline justify-between gap-4",children:[(0,t.jsx)("dt",{className:"text-xs font-medium text-muted-foreground",children:l.label}),(0,t.jsx)("dd",{className:"text-sm text-foreground",children:l.value})]},l.label))}),(0,t.jsx)("div",{className:"mt-8",children:(0,t.jsx)(L,{size:"lg",className:"px-10",onClick:o,children:"View connection"})})]})}r(Git,"ConnectionSetupCompletionScreen");function cCe(){const{newProjectOpen:e,closeNewProject:s}=BI(),{selectedCompanyId:n}=ps();return n&&e?(0,t.jsx)(Qit,{companyId:n,onClose:s},n):null}r(cCe,"NewProjectDialog");function Qit({companyId:e,onClose:s}){const n=Pt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>k3[Math.floor(Math.random()*k3.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=je({mutationFn:r(()=>pa.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{J0(f.id,e),n.invalidateQueries({queryKey:P.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(Ys,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Js,{showCloseButton:!1,"aria-describedby":void 0,className:"flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 shadow-sm sm:max-w-lg",onOpenAutoFocus:r(f=>{f.preventDefault(),h.current?.focus()},"onOpenAutoFocus"),children:d?(0,t.jsxs)("div",{className:"min-h-0 overflow-y-auto p-5",children:[(0,t.jsx)(Xs,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(m4,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:U9(e)}),u(!1)},"onComplete")})]}):(0,t.jsxs)("form",{className:"flex min-h-0 flex-col overflow-hidden",onSubmit:r(f=>{f.preventDefault(),a.trim()&&!p.isPending&&p.mutate()},"onSubmit"),children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-5 pb-4 pt-5",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,t.jsx)(Xs,{className:"text-lg font-semibold",children:"Create project"}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",disabled:p.isPending,"aria-label":"Close new project",onClick:s,children:(0,t.jsx)(Fn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-input px-3 focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",children:[(0,t.jsx)(Em,{color:o,size:"sm"}),(0,t.jsx)("input",{ref:h,"aria-label":"Project name",value:a,disabled:p.isPending,onChange:r(f=>i(f.target.value),"onChange"),placeholder:"Project name",required:!0,className:"h-10 w-full min-w-0 border-0 bg-transparent text-base outline-none placeholder:text-muted-foreground md:text-sm"})]})]}),(0,t.jsx)("div",{role:"region","aria-label":"Source repositories",tabIndex:0,className:"min-h-0 overflow-y-auto overscroll-contain px-5 pb-1 outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",children:(0,t.jsx)(ywe,{companyId:e,selected:l,onChange:c,onConnect:r(()=>u(!0),"onConnect"),disabled:p.isPending})}),p.isError&&(0,t.jsx)("p",{role:"alert",className:"px-5 pt-3 text-sm text-destructive",children:p.error.message}),(0,t.jsxs)("div",{className:"flex shrink-0 justify-end gap-2 px-5 py-5",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",disabled:p.isPending,onClick:s,children:"Cancel"}),(0,t.jsx)(L,{type:"submit",disabled:!a.trim()||p.isPending,children:p.isPending?"Creating…":"Create project"})]})]})})})}r(Qit,"NewProjectForm");var rg={list:r(e=>Te.get(`/companies/${e}/goals`),"list"),get:r(e=>Te.get(`/goals/${e}`),"get"),create:r((e,s)=>Te.post(`/companies/${e}/goals`,s),"create"),update:r((e,s)=>Te.patch(`/goals/${e}`,s),"update"),remove:r(e=>Te.delete(`/goals/${e}`),"remove")};function dCe(e){return{"--sc":`var(${e})`}}r(dCe,"scStyle");function Yit(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(Yit,"sentenceCaseStatus");function ri({status:e,label:s}){return(0,t.jsx)("span",{className:W("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",Iz[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(ri,"StatusBadge$5");function uCe({status:e}){const s=cBe[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:dCe(s),children:n.replace(/_/g," ")})}r(uCe,"AgentStatusBadge");function sp({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=aBe[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:dCe(a),children:[(0,t.jsx)(FI,{status:n,size:"sm"}),Yit(n)]})}r(sp,"IssueStatusBadge");var bse={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function mCe(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=BI(),{selectedCompanyId:a,selectedCompany:i}=ps(),o=Pt(),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)("planned"),[f,x]=(0,m.useState)("task"),[b,v]=(0,m.useState)(""),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(!1),[S,C]=(0,m.useState)(!1),[I,R]=(0,m.useState)(!1),T=(0,m.useRef)(null),A=b||s.parentId||"",{data:D}=ee({queryKey:P.goals.list(a),queryFn:r(()=>rg.list(a),"queryFn"),enabled:!!a&&e}),M=je({mutationFn:r(U=>rg.create(a,U),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:P.goals.list(a)}),E(),n()},"onSuccess")}),B=je({mutationFn:r(async U=>{if(!a)throw new Error("No organization selected");return vb.uploadImage(a,U,"goals/drafts")},"mutationFn")});function E(){c(""),u(""),p("planned"),x("task"),v(""),N(!1)}r(E,"reset");function z(){!a||!l.trim()||M.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...A?{parentId:A}:{}})}r(z,"handleSubmit");function $(U){U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&(U.preventDefault(),z())}r($,"handleKeyDown");const q=(D??[]).find(U=>U.id===A);return(0,t.jsx)(Ys,{open:e,onOpenChange:r(U=>{U||(E(),n())},"onOpenChange"),children:(0,t.jsxs)(Js,{showCloseButton:!1,className:W("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:$,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[i&&(0,t.jsx)("span",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-medium",children:i.issuePrefix}),(0,t.jsx)("span",{className:"text-muted-foreground/60",children:"›"}),(0,t.jsx)("span",{children:s.parentId?"New sub-goal":"New goal"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>N(!j),"onClick"),children:j?(0,t.jsx)(gbe,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Gy,{className:"h-3.5 w-3.5"})}),(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:"text-muted-foreground",onClick:r(()=>{E(),n()},"onClick"),children:(0,t.jsx)("span",{className:"text-lg leading-none",children:"×"})})]})]}),(0,t.jsx)("div",{className:"px-4 pt-4 pb-2 shrink-0",children:(0,t.jsx)("input",{className:"w-full text-lg font-semibold bg-transparent outline-none placeholder:text-muted-foreground/50",placeholder:"Goal title",value:l,onChange:r(U=>c(U.target.value),"onChange"),onKeyDown:r(U=>{U.key==="Tab"&&!U.shiftKey&&(U.preventDefault(),T.current?.focus())},"onKeyDown"),autoFocus:!0})}),(0,t.jsx)("div",{className:"px-4 pb-2 overflow-y-auto max-h-(--sz-50vh)",children:(0,t.jsx)(fd,{ref:T,value:d,onChange:u,placeholder:"Add description...",bordered:!1,contentClassName:W("text-sm text-muted-foreground",j?"min-h-(--sz-220px)":"min-h-(--sz-120px)"),imageUploadHandler:r(async U=>(await B.mutateAsync(U)).contentPath,"imageUploadHandler")})}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap",children:[(0,t.jsxs)(br,{open:w,onOpenChange:k,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsx)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:(0,t.jsx)(ri,{status:h})})}),(0,t.jsx)(dr,{className:"w-40 p-1",align:"start",children:efe.map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 capitalize",U===h&&"bg-accent"),onClick:r(()=>{p(U),k(!1)},"onClick"),children:U},U))})]}),(0,t.jsxs)(br,{open:S,onOpenChange:C,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(zl,{className:"h-3 w-3 text-muted-foreground"}),bse[f]??f]})}),(0,t.jsx)(dr,{className:"w-40 p-1",align:"start",children:gfe.map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",U===f&&"bg-accent"),onClick:r(()=>{x(U),C(!1)},"onClick"),children:bse[U]??U},U))})]}),(0,t.jsxs)(br,{open:I,onOpenChange:R,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors",children:[(0,t.jsx)(vp,{className:"h-3 w-3 text-muted-foreground"}),q?q.title:"Parent goal"]})}),(0,t.jsxs)(dr,{className:"w-48 p-1",align:"start",children:[(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",!A&&"bg-accent"),onClick:r(()=>{v(""),R(!1)},"onClick"),children:"No parent"}),(D??[]).map(U=>(0,t.jsx)("button",{className:W("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 truncate",U.id===A&&"bg-accent"),onClick:r(()=>{v(U.id),R(!1)},"onClick"),children:U.title},U.id))]})]})]}),(0,t.jsx)("div",{className:"flex items-center justify-end px-4 py-2.5 border-t border-border",children:(0,t.jsx)(L,{size:"sm",disabled:!l.trim()||M.isPending,onClick:z,children:M.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(mCe,"NewGoalDialog");function Jit(e){const s=Xit(e),n=Zit(e);return`You're invited to join a Paperclip company as an agent.
|
|
307
307
|
|
|
308
308
|
First, respond to your user that you understand the request and are going to onboard into Paperclip. Then work through the steps below.
|
|
309
309
|
|
|
@@ -352,7 +352,7 @@ After you have connected to Paperclip, review and follow the full onboarding ins
|
|
|
352
352
|
`}r(Jit,"buildAgentOnboardingPrompt");function Xit(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(Xit,"buildCandidateOnboardingUrls");function Zit(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(Zit,"buildResolutionTestUrl");var h6=[{name:"Codex",src:"/brands/codex-color.svg",className:""},{name:"ChatGPT",src:"/brands/apps/openai.svg",className:"dark:invert"},{name:"Claude",src:"/brands/claude-color.svg",className:""}];function vse({ref:e,hidden:s}){return(0,t.jsx)("span",{ref:e,className:"agent-setup-logos","data-hidden":s,"aria-hidden":"true",children:h6.map(n=>(0,t.jsx)("span",{className:"agent-setup-logo-slot",children:(0,t.jsx)("span",{className:"agent-setup-logo",children:(0,t.jsx)("img",{src:n.src,alt:"",className:W("size-5",n.className),draggable:!1})})},n.name))})}r(vse,"AgentLogos");function X$(e){return Array.from(e?.querySelectorAll(".agent-setup-logo")??[]).map(s=>{const n=s.getBoundingClientRect(),a=getComputedStyle(s).transform,i=a&&a!=="none"?new DOMMatrixReadOnly(a):null;return{left:n.left+(n.width-s.offsetWidth)/2,top:n.top+(n.height-s.offsetHeight)/2,width:s.offsetWidth,height:s.offsetHeight,transform:`rotate(${i?Math.atan2(i.b,i.a)*180/Math.PI:0}deg)`}})}r(X$,"readLogoPositions");function ej({prompt:e,title:s="Agent setup",description:n="Paste this into your agent to take care of setup.",label:a="Set up with an agent",variant:i="outline",side:o="top",align:l="start",className:c,initialCopyStatus:d="idle",onCopied:u}){const h=(0,m.useId)(),p=Txe(),[f,x]=(0,m.useState)(!1),[b,v]=(0,m.useState)(d),[j,N]=(0,m.useState)(null),w=(0,m.useRef)(null),k=(0,m.useRef)(null),S=(0,m.useRef)(null),C=(0,m.useRef)(null),I=(0,m.useRef)(0),R=(0,m.useRef)(!1),T=(0,m.useRef)(!1),A=(0,m.useRef)(null);(0,m.useEffect)(()=>(v("idle"),T.current=!1,R.current=!1,()=>{I.current+=1}),[e]),(0,m.useEffect)(()=>{R.current||v(d)},[e,d]),(0,m.useEffect)(()=>{if(b!=="copied")return;const B=T5("--agent-setup-copied-hold");if(B<=0)return;const E=window.setTimeout(()=>v("idle"),B);return()=>window.clearTimeout(E)},[b]),(0,m.useLayoutEffect)(()=>{if(!j)return;if(p||typeof Element.prototype.animate!="function"){N(null);return}let B,E=!1,z=[];const $=r(()=>{E||N(null)},"finish"),q=r(()=>{const U=j.toPreview?k.current:w.current;if(!U||j.toPreview&&!getComputedStyle(U).getPropertyValue("--radix-popover-content-transform-origin").trim()){B=requestAnimationFrame(q);return}const O=X$(U),K=S.current?.querySelectorAll(".agent-setup-logo"),H=getComputedStyle(document.documentElement).getPropertyValue("--motion-ease-out-expo").trim();z=Array.from(K??[]).map((Z,se)=>Z.animate([j.origins[se],O[se]].map(({left:ne,top:fe,transform:X})=>({left:`${ne}px`,top:`${fe}px`,transform:X})),{duration:T5("--agent-setup-flight-duration"),easing:H,fill:"both"})),Promise.all(z.map(Z=>Z.finished)).then($,()=>{})},"start");return B=requestAnimationFrame(q),window.addEventListener("resize",$),document.addEventListener("scroll",$,!0),()=>{E=!0,cancelAnimationFrame(B),z.forEach(U=>U.cancel()),window.removeEventListener("resize",$),document.removeEventListener("scroll",$,!0)}},[j,p]);function D(B){const E=C.current??X$(S.current??(f?k.current:w.current));C.current=null,N(!p&&E.length===h6.length?{origins:E,toPreview:B}:null),x(B)}r(D,"changeOpen");async function M(){if(T.current||!e.trim())return;R.current=!0,T.current=!0;const B=++I.current;v("copying");try{await fa(e),B===I.current&&(v("copied"),u?.())}catch{B===I.current&&v("failed")}finally{B===I.current&&(T.current=!1)}}return r(M,"copyPrompt"),(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(br,{open:f,onOpenChange:D,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)(L,{type:"button",variant:i,"aria-label":a,"data-copied":b==="copied",onClick:r(B=>{f?B.preventDefault():C.current=X$(S.current??w.current),M()},"onClick"),className:W("agent-setup-trigger h-auto min-h-10 max-w-full gap-3 whitespace-normal text-left",i==="ghost"&&"w-full justify-start",c),children:[b==="copied"?(0,t.jsx)(gs,{className:"agent-setup-check size-4"}):(0,t.jsx)(hg,{className:"size-4 text-muted-foreground"}),(0,t.jsxs)("span",{className:"relative min-w-0",children:[(0,t.jsx)("span",{className:b==="copied"?"invisible":void 0,children:a}),b==="copied"&&(0,t.jsx)("span",{className:"agent-setup-confirmation absolute inset-0 flex items-center",children:"Copied!"})]}),(0,t.jsx)("span",{className:"agent-setup-trigger-logos",children:(0,t.jsx)(vse,{ref:w,hidden:f||!!j})})]})}),(0,t.jsxs)(dr,{side:o,align:l,collisionPadding:Tm("--agent-setup-collision-padding"),className:"agent-setup-popover flex flex-col gap-4 rounded-xl p-4","aria-labelledby":`${h}-title`,"aria-describedby":`${h}-description`,onOpenAutoFocus:r(B=>{B.preventDefault(),A.current?.focus()},"onOpenAutoFocus"),onFocusOutside:r(B=>{T.current&&B.preventDefault()},"onFocusOutside"),children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[(0,t.jsx)("h2",{id:`${h}-title`,className:"text-sm font-semibold",children:s}),(0,t.jsx)("p",{id:`${h}-description`,className:"text-sm leading-relaxed text-muted-foreground",children:n})]}),(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Close agent setup",onClick:r(()=>D(!1),"onClick"),children:(0,t.jsx)(Fn,{className:"size-3.5"})})]}),(0,t.jsxs)("div",{className:"agent-setup-preview-wrap relative pt-2",children:[(0,t.jsx)("div",{className:"agent-setup-preview-logos absolute right-3 top-0 z-10",children:(0,t.jsx)(vse,{ref:k,hidden:!!j})}),b==="failed"?(0,t.jsx)(Cn,{"aria-label":"Setup prompt",readOnly:!0,value:e,onFocus:r(B=>B.currentTarget.select(),"onFocus"),className:"agent-setup-preview resize-none rounded-lg bg-muted/50 p-3 pt-5 font-mono text-xs leading-relaxed"}):(0,t.jsx)("pre",{tabIndex:0,"aria-label":"Setup prompt",className:"agent-setup-preview m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border/60 bg-muted/50 p-3 pt-5 font-mono text-xs leading-relaxed text-muted-foreground",children:e})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[b==="failed"&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Could not copy automatically. Select and copy the prompt above, or try again."}),(0,t.jsxs)(L,{ref:A,type:"button",variant:"cta",className:"agent-setup-copy w-full","data-copied":b==="copied","aria-disabled":b==="copying"||!e.trim(),onClick:r(()=>{e.trim()&&M()},"onClick"),children:[b==="copied"?(0,t.jsx)(gs,{className:"agent-setup-check size-4"}):(0,t.jsx)(Ir,{className:"size-4"}),b==="copied"?"Copied to clipboard":b==="copying"?"Copying…":b==="failed"?"Try copying again":"Copy prompt"]}),(0,t.jsx)("p",{className:"text-center text-xs text-muted-foreground",children:b==="copied"?"Ready to paste into your agent.":"Works with Codex, ChatGPT, Claude, and more."})]})]})]}),(0,t.jsx)("span",{role:"status",className:"sr-only",children:b==="copied"?"Setup prompt copied. Ready to paste into your agent.":""}),j&&(0,hp.createPortal)((0,t.jsx)("span",{ref:S,className:"agent-setup-flight-layer","aria-hidden":"true",children:h6.map((B,E)=>(0,t.jsx)("span",{className:"agent-setup-logo agent-setup-flying-logo",style:j.origins[E],children:(0,t.jsx)("img",{src:B.src,alt:"",className:W("size-5",B.className),draggable:!1})},B.name))}),document.body)]})}r(ej,"AgentSetupPrompt");function eot({companyId:e,onClose:s,onBack:n}){const a=Pt(),i=(0,m.useRef)(!0);(0,m.useEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);const[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(null),u=c?.prompt,h=je({mutationFn:r(async()=>{const p=await pr.createCompanyInvite(e,{allowedJoinTypes:"agent",humanRole:null,agentMessage:o.trim()||null});a.invalidateQueries({queryKey:P.access.invites(e,"all",5)});const f=p.onboardingTextUrl??p.onboardingTextPath??`/api/invites/${p.token}/onboarding.txt`,x=new URL(f,window.location.origin).href,b=await pr.getInviteOnboarding(p.token).catch(()=>null);return Jit({onboardingTextUrl:x,connectionCandidates:b?.onboarding.connectivity?.connectionCandidates??null,testResolutionUrl:b?.onboarding.connectivity?.testResolutionEndpoint?.url??null})},"mutationFn"),onSuccess:r(async p=>{if(!i.current)return;d({prompt:p,copyStatus:"idle"});let f="copied";try{await fa(p)}catch{f="failed"}i.current&&d(x=>x?.copyStatus==="idle"?{...x,copyStatus:f}:x)},"onSuccess")});return(0,t.jsx)(Ys,{open:!0,onOpenChange:r(p=>{p||s()},"onOpenChange"),children:(0,t.jsxs)(Js,{className:"max-h-(--sz-calc-16) overflow-y-auto sm:max-w-2xl",children:[(0,t.jsx)(Xs,{children:u?"Agent onboarding prompt":"Invite an external agent"}),(0,t.jsx)(jn,{children:u?"Send this one-time prompt to the agent that should join your organization.":"Generate a one-time onboarding prompt for an external agent. An organization admin must approve its join request before it can claim an API key."}),u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Cn,{"aria-label":"Agent onboarding prompt",readOnly:!0,value:u,className:"min-h-64 font-mono text-xs"}),c?.copyStatus==="failed"&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-muted-foreground",children:"Clipboard unavailable. Copy the prompt manually from the field above, or use the button below to try again."}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[(0,t.jsx)(L,{variant:"ghost",onClick:s,children:"Done"}),(0,t.jsx)(ej,{prompt:u,label:"Copy onboarding prompt",title:"Invite your agent",description:"Paste this into your external agent to request access to your organization.",initialCopyStatus:c?.copyStatus,onCopied:r(()=>d(p=>p&&{...p,copyStatus:"copied"}),"onCopied")})]})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{children:"Optional message for the agent"}),(0,t.jsx)(Cn,{value:o,onChange:r(p=>l(p.target.value),"onChange"),maxLength:4e3,className:"min-h-24"})]}),h.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:h.error.message}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)(L,{variant:"ghost",onClick:n,children:"Back"}),(0,t.jsx)(L,{disabled:h.isPending,onClick:r(()=>h.mutate(),"onClick"),children:h.isPending?"Generating…":"Generate onboarding prompt"})]})]})]})})}r(eot,"ExternalAgentInviteDialog");function hCe(){const{newAgentOpen:e,closeNewAgent:s}=BI(),{selectedCompanyId:n}=ps();return e?(0,t.jsx)(tot,{companyId:n,onClose:s},n):null}r(hCe,"NewAgentDialog");function tot({companyId:e,onClose:s}){const n=Mn(),[a,i]=(0,m.useState)(!1);return a&&e?(0,t.jsx)(eot,{companyId:e,onClose:s,onBack:r(()=>i(!1),"onBack")}):(0,t.jsx)(GSe,{open:!0,onClose:s,onInvite:e?()=>i(!0):void 0,onContinue:r(o=>{s(),n(`/agents/new?${new URLSearchParams(o)}`)},"onContinue")})}r(tot,"NewAgentDialogContent");var sot=[{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 yse({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(yse,"KeyCap");function not(){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"divide-y divide-border border-t border-border",children:sot.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)(yse,{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)(yse,{children:"Esc"})," to close · Shortcuts are disabled in text fields"]})})]})}r(not,"KeyboardShortcutsCheatsheetContent");function pCe({open:e,onOpenChange:s}){return(0,t.jsx)(Ys,{open:e,onOpenChange:s,children:(0,t.jsxs)(Js,{className:"sm:max-w-md gap-0 p-0 overflow-hidden",showCloseButton:!1,children:[(0,t.jsx)(hn,{className:"px-5 pt-5 pb-3",children:(0,t.jsx)(Xs,{className:"text-base",children:"Keyboard shortcuts"})}),(0,t.jsx)(not,{})]})})}r(pCe,"KeyboardShortcutsCheatsheet");var rot={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"},aot={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 iot({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",rot[e.tone]),children:(0,t.jsxs)("div",{className:"flex items-start gap-3 px-3 py-2.5",children:[(0,t.jsx)("span",{className:W("mt-1 h-2 w-2 shrink-0 rounded-full",aot[e.tone])}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsx)("p",{className:"text-sm font-semibold leading-5",children:e.title}),e.body&&(0,t.jsx)("p",{className:"mt-1 text-xs leading-4 opacity-70",children:e.body}),e.action&&(e.action.onClick?(0,t.jsx)("button",{type:"button",onClick:r(()=>{e.action?.onClick?.(),s(e.id)},"onClick"),className:"mt-2 inline-flex text-xs font-medium underline underline-offset-4 hover:opacity-90",children:e.action.label}):e.action.href?(0,t.jsx)(Ke,{to:e.action.href,onClick:r(()=>s(e.id),"onClick"),className:"mt-2 inline-flex text-xs font-medium underline underline-offset-4 hover:opacity-90",children:e.action.label}):null)]}),(0,t.jsx)("button",{type:"button","aria-label":"Dismiss notification",onClick:r(()=>s(e.id),"onClick"),className:"mt-0.5 shrink-0 rounded p-1 opacity-50 hover:bg-black/10 hover:opacity-100 dark:hover:bg-white/10",children:(0,t.jsx)(Fn,{className:"h-3.5 w-3.5"})})]})})}r(iot,"AnimatedToast");function fCe(){const e=bye(),{dismissToast:s}=da();return e.length===0?null:(0,t.jsx)("aside",{"aria-live":"polite","aria-atomic":"false",className:"pointer-events-none fixed bottom-3 left-3 z-(--z-120) w-full max-w-sm px-1",children:(0,t.jsx)("ol",{className:"flex w-full flex-col-reverse gap-2",children:e.map(n=>(0,t.jsx)(iot,{toast:n,onDismiss:s},n.id))})})}r(fCe,"ToastViewport");async function jse(e,s){const n=await fetch(`/api/announcements/${e}`,{credentials:"same-origin",cache:"no-store",...s});if(!n.ok)throw new dn("Announcement request failed",n.status,null);return n}r(jse,"request");var wse={async current(e){const s=await(await jse("current",{signal:e})).json();return s===null?null:j$e.parse(s)},async dismiss(e,s,n){await jse(`${encodeURIComponent(e)}/dismiss`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({companyId:s})})}},p6=new Map;function GW(e){return`paperclip.announcement-dismissals.v1:${encodeURIComponent(e)}:`}r(GW,"announcementStoragePrefix");function Y2(e){const s=GW(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);rfe.safeParse(o).success&&(l==="pending"||l==="synced")&&p6.set(i,l==="pending")}}catch{}for(const[a,i]of p6)a.startsWith(s)&&n.set(a.slice(s.length),i);return n}r(Y2,"readAnnouncementDismissals");function Z$(e,s,n){const a=`${GW(e)}${s}`;p6.set(a,n);try{return localStorage.setItem(a,n?"pending":"synced"),!0}catch{return!1}}r(Z$,"saveAnnouncementDismissal");var oot=3e3;function lot(e){const{userId:s,enabled:n}=e,a=(0,m.useRef)(e);a.current=e;const[i,o]=(0,m.useState)(null),l=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{if(o(null),!s||!n)return;let d=!1,u=0,h=null,p;const f=new Map,x=new Set,b=GW(s);let v=null;try{v=new BroadcastChannel(b)}catch{}const j=r(()=>!d&&a.current.userId===s&&a.current.enabled,"active");async function N(A,D=!0){if(!j()||f.has(A)||!a.current.companyId)return;const M=new AbortController;f.set(A,M);const B=setTimeout(()=>M.abort(),1e4);try{await wse.dismiss(A,a.current.companyId,M.signal),j()&&Z$(s,A,!1)}catch{j()&&!x.has(A)&&(x.add(A),a.current.onSaveFailure(D))}finally{clearTimeout(B),f.delete(A)}}r(N,"sync");async function w(){for(const[A,D]of Y2(s)){if(!j())return;D&&await N(A)}}r(w,"flush");function k(){u++,clearTimeout(p),h?.abort(),h=null,o(null)}r(k,"suspend");function S(){if(!j()||document.visibilityState==="hidden")return;k();const A=u,D=new AbortController;h=D;const M=r(()=>j()&&u===A&&!D.signal.aborted,"stillCurrent");let B=!1,E=!1,z=null;const $=r(()=>{!M()||!B||!E||z&&!Y2(s).has(z.id)&&(!z.expiresAt||Date.parse(z.expiresAt)>Date.now())&&o({userId:s,announcement:z})},"show");p=setTimeout(()=>{B=!0,$()},oot),w(),wse.current(D.signal).then(q=>{z=q,E=!0,$()}).catch(()=>{})}r(S,"resume");function C(){const A=Y2(s);o(D=>D?.userId===s&&A.has(D.announcement.id)?null:D)}r(C,"receive");function I(A){A.key?.startsWith(b)&&C()}r(I,"onStorage");function R(){document.visibilityState==="hidden"?k():S()}r(R,"onVisibility");function T(){w()}return r(T,"onOnline"),v&&(v.onmessage=A=>{const D=rfe.safeParse(A.data);D.success&&(Y2(s).has(D.data)||Z$(s,D.data,!0),C())}),l.current=A=>{if(!j())return;const D=Z$(s,A,!0);o(null),u++,h?.abort();try{v?.postMessage(A)}catch{}N(A,D)},document.addEventListener("visibilitychange",R),window.addEventListener("online",T),window.addEventListener("storage",I),S(),()=>{d=!0,u++,clearTimeout(p),h?.abort();for(const A of f.values())A.abort();v?.close(),document.removeEventListener("visibilitychange",R),window.removeEventListener("online",T),window.removeEventListener("storage",I),l.current=()=>{}}},[s,n]);const c=n&&i?.userId===s?i.announcement:null;return(0,m.useEffect)(()=>{if(!c?.expiresAt)return;let d;const u=r(()=>{const h=Date.parse(c.expiresAt)-Date.now();h<=0?o(null):d=setTimeout(u,Math.min(h,2147483647))},"check");return u(),()=>clearTimeout(d)},[c]),{announcement:c,dismiss:(0,m.useCallback)(d=>l.current(d),[])}}r(lot,"useAnnouncement");function cot(e,s){const n=Txe(),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="${e$e}">${p}`})}catch{}finally{clearTimeout(u)}})(),()=>{d.abort(),clearTimeout(u)}},[c,i,a]),c&&o?.key===i?o.document:null}r(cot,"useAnnouncementAnimation");function kse({action:e,primary:s,onClick:n}){const a=(0,t.jsxs)(t.Fragment,{children:[e.label,!s&&e.kind==="external"&&(0,t.jsx)(eo,{className:"size-3.5 shrink-0","aria-hidden":"true"})]}),i=r(o=>{o.button===1&&n()},"onAuxClick");return(0,t.jsx)(L,{asChild:!0,variant:s?"default":"ghost",size:"sm",className:"h-auto min-h-9 min-w-0 whitespace-normal py-2 text-left",children:e.kind==="external"?(0,t.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",onClick:n,onAuxClick:i,children:a}):(0,t.jsx)(Ke,{to:e.path,onClick:n,onAuxClick:i,children:a})})}r(kse,"Action");function wE({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=cot(e,a),p=!!h;return(0,t.jsxs)(rn,{role:"region","aria-labelledby":o,className:W("relative w-full max-w-(--announcement-width) gap-0 overflow-hidden rounded-xl p-0 shadow-sm",i),onKeyDown:r(f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),s())},"onKeyDown"),children:[(u||h)&&(0,t.jsxs)("div",{className:"relative h-(--announcement-image-mobile-height) w-full shrink-0 overflow-hidden bg-muted md:h-(--announcement-image-height)",children:[u&&(0,t.jsx)("img",{src:d,alt:p?"":e.image.alt,referrerPolicy:"no-referrer",onError:r(()=>c(d),"onError"),className:"h-full w-full object-cover"}),p&&(0,t.jsx)("div",{role:"img","aria-label":e.animation.alt,className:"pointer-events-none absolute inset-0",children:(0,t.jsx)("iframe",{title:e.animation.alt,"aria-hidden":"true",tabIndex:-1,sandbox:"",referrerPolicy:"no-referrer",srcDoc:h,className:"h-full w-full border-0"})})]}),(0,t.jsx)(L,{variant:"secondary",size:"icon","aria-label":"Dismiss announcement",onClick:s,className:"absolute right-2 top-2 z-10 size-8 rounded-full shadow-sm",children:(0,t.jsx)(Fn,{className:"size-4","aria-hidden":"true"})}),(0,t.jsxs)("div",{className:W("flex flex-col gap-1 px-4 py-4",!u&&!h&&"pr-12"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.eyebrow}),(0,t.jsx)("h2",{id:o,className:"break-words text-base font-semibold leading-snug",children:e.title}),(0,t.jsx)("p",{className:"break-words text-sm leading-snug text-muted-foreground",children:e.description})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t px-3 py-2",children:[e.secondaryLink&&(0,t.jsx)(kse,{action:e.secondaryLink,onClick:s}),(0,t.jsx)("div",{className:"ml-auto min-w-0 max-w-full",children:(0,t.jsx)(kse,{action:e.primaryAction,primary:!0,onClick:s})})]})]})}r(wE,"AnnouncementCard");var dot='[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [aria-modal="true"]:not([data-state="closed"]), dialog[open]';function uot(e){const[s,n]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{if(!e)return;const a=r(()=>n(!!document.querySelector(dot)),"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(uot,"useModalOpen");function mot({health:e}){const{userId:s,settled:n}=Hf(),{selectedCompanyId:a,loading:i}=ps(),{onboardingOpen:o}=kM(),l=Xc(),c=$Ke(),d=e?.deploymentMode==="local_trusted"?"local-board":n?s:null,{announcement:u,dismiss:h}=lot({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=uot(!!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)(wE,{announcement:u,onDismiss:r(()=>h(u.id),"onDismiss")},u.id)})}r(mot,"AnnouncementWell");function h4(e){const s=e.split("/").filter(Boolean);return s.length===1?s[0]?.toLowerCase()==="onboarding":s.length===2?s[1]?.toLowerCase()==="onboarding":!1}r(h4,"isOnboardingPath");function hot(e){const s=e.split("/").filter(Boolean);if(s.length===2&&s[1]?.toLowerCase()==="onboarding")return s[0]}r(hot,"companyPrefixFromOnboardingPath");function O5(){return 3}r(O5,"onboardingStepForCompany");function pot(e){const{pathname:s,companyPrefix:n,companies:a,cloudManaged:i}=e;if(!h4(s))return null;const o=r(()=>a.length===1?{initialStep:O5(),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:O5(),companyId:l.id}:i?o():{initialStep:1}}r(pot,"resolveRouteOnboardingOptions");function fot(e){return!e.agentsLoaded||e.agentsRefreshing||e.agentCount>0?!1:!h4(e.pathname)}r(fot,"shouldRouteAgentlessCompanyToOnboarding");function xot(e){return e.currentStep>1&&e.currentStep>e.entryStep}r(xot,"canGoBackFromOnboardingStep");function Nse(e){return e.targetStep<e.currentStep&&e.targetStep>=e.entryStep}r(Nse,"canJumpToOnboardingStep");function QW(e){return!e.hasCompanies&&!h4(e.pathname)}r(QW,"shouldRedirectCompanylessRouteToOnboarding");function got(e){return e.onboardingOpen||!e.routeDismissed}r(got,"isOnboardingWizardActive");function bot({context:e}){const{slots:s,errorMessage:n}=gd({slotTypes:["appShellOverlay"],companyId:e.companyId});return n||s.length===0?null:(0,t.jsx)("aside",{className:"plugin-app-shell-overlays","aria-label":"Application extensions",children:s.map(a=>(0,t.jsx)(Wu,{slot:a,context:e,className:"plugin-app-shell-overlay"},`${a.pluginId}:${a.pluginVersion}:${a.id}`))})}r(bot,"AppShellEntries");function xCe({localTrusted:e=!1}){const{userId:s,settled:n}=Hf(),{selectedCompanyId:a,selectedCompany:i,loading:o}=ps(),{onboardingOpen:l,onboardingRouteDismissed:c}=kM(),{pathname:d}=na(),u=n?s??(e?"local-board":null):null,h=l||!c&&h4(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)(bot,{context:p},JSON.stringify([u,a]))}r(xCe,"PluginAppShellOverlays");function gCe({visible:e}){const s=na(),{selectedCompanyId:n}=ps(),{openNewIssue:a}=Yo(),i=BM(n),{enabled:o}=Yy(),{enabled:l}=nA(),c=(0,m.useMemo)(()=>!o&&!l?[{type:"link",to:"/dashboard",label:"Home",icon:Fz},{type:"link",to:"/issues",label:"Tasks",icon:ca},{type:"action",label:"New Task",icon:f_,onClick:r(()=>a(),"onClick")},{type:"link",to:"/agents/all",label:"Agents",icon:Ho},{type:"link",to:"/inbox",label:"Inbox",icon:hd,badge:i.inbox}]:[{type:"link",to:"/dashboard",label:"Home",icon:Fz},...o?[{type:"link",to:"/chats",label:"Chat",icon:p_}]:[],{type:"action",label:"New Task",icon:f_,onClick:r(()=>a(),"onClick")},{type:"link",to:"/issues",label:"Tasks",icon:ca,badge:l?i.inbox:void 0},{type:"link",to:"/agents/all",label:"Agents",icon:Ho},...l?[]:[{type:"link",to:"/inbox",label:"Inbox",icon:hd,badge:i.inbox}]],[a,i.inbox,o,l]);return(0,t.jsx)("nav",{className:W("mobile-bottom-nav fixed bottom-0 left-0 right-0 z-30 bg-muted md:hidden pb-(--sz-safe-bottom)"),"data-visible":e,inert:!e,"aria-label":"Mobile navigation",children:(0,t.jsx)("div",{className:"grid h-16 px-1",style:{gridTemplateColumns:`repeat(${c.length}, minmax(0, 1fr))`},children:c.map(d=>{if(d.type==="action"){const h=d.icon,p=/\/issues\/new(?:\/|$)/.test(s.pathname);return(0,t.jsxs)("button",{type:"button",onClick:d.onClick,className:W("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-(length:--text-nano) font-medium transition-colors",p?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[(0,t.jsx)(h,{className:"h-(--sz-18px) w-(--sz-18px)"}),(0,t.jsx)("span",{className:"truncate",children:d.label})]},d.label)}const u=d.icon;return(0,t.jsx)(hb,{to:d.to,state:Qf,className:r(({isActive:h})=>W("relative flex min-w-0 flex-col items-center justify-center gap-1 rounded-md text-(length:--text-nano) font-medium transition-colors",h?"text-foreground":"text-muted-foreground hover:text-foreground"),"className"),children:r(({isActive:h})=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative",children:[(0,t.jsx)(u,{className:W("h-(--sz-18px) w-(--sz-18px)",h&&"stroke-(length:--sw-2_3)")}),d.badge!=null&&d.badge>0&&(0,t.jsx)(ct,{variant:"ghost",className:"absolute -right-2 -top-2 bg-primary px-1.5 text-(length:--text-nano) leading-none text-primary-foreground",children:d.badge>99?"99+":d.badge})]}),(0,t.jsx)("span",{className:"truncate",children:d.label})]}),"children")},d.label)})})})}r(gCe,"MobileBottomNav");function Hw(e){if(typeof document>"u")return null;const s=document.querySelector(`meta[name="${e}"]`)?.getAttribute("content")?.trim();return s||null}r(Hw,"readMetaContent");function f6(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(f6,"normalizeHexColor");function vot(e){const s=f6(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(vot,"hexToRgb");function eO(e){const s=e/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4}r(eO,"relativeLuminanceChannel");function yot(e){const{r:s,g:n,b:a}=vot(e),i=.2126*eO(s)+.7152*eO(n)+.0722*eO(a);return 1.05/(i+.05)>=(i+.05)/.05?AFe:_Fe}r(yot,"pickReadableTextColor");function jot(){return Hw("paperclip-worktree-enabled")==="true"}r(jot,"isWorktreeRuntime");function wot(){return Hw("paperclip-instance-id")}r(wot,"getWorktreeInstanceId");function kot(){if(Hw("paperclip-worktree-enabled")!=="true")return null;const e=Hw("paperclip-worktree-name"),s=f6(Hw("paperclip-worktree-color"));return!e||!s?null:{enabled:!0,name:e,color:s,textColor:f6(Hw("paperclip-worktree-text-color"))??yot(s)}}r(kot,"getWorktreeUiBranding");function bCe(){const e=kot(),{copied:s,failed:n,copy:a}=Cp(),i=(0,m.useCallback)(()=>{e&&a(e.name)},[e,a]);return e?(0,t.jsx)("div",{className:"relative overflow-hidden border-b px-3 py-1.5 text-(length:--text-micro) font-medium tracking-(--tracking-caps) uppercase",style:{backgroundColor:e.color,color:e.textColor,borderColor:`${e.textColor}22`,boxShadow:`inset 0 -1px 0 ${e.textColor}18`,backgroundImage:`linear-gradient(90deg, ${e.textColor}14, transparent 28%, transparent 72%, ${e.textColor}12), repeating-linear-gradient(135deg, transparent 0 10px, ${e.textColor}08 10px 20px)`},children:(0,t.jsxs)("div",{className:"flex items-center gap-2 overflow-hidden whitespace-nowrap",children:[(0,t.jsx)("span",{className:"shrink-0 opacity-70",children:"Worktree"}),(0,t.jsx)("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-current opacity-70","aria-hidden":"true"}),(0,t.jsx)("button",{type:"button",onClick:i,title:"Click to copy worktree name",className:"truncate font-semibold tracking-(--tracking-eyebrow) cursor-pointer hover:opacity-80 transition-opacity bg-transparent border-none p-0 text-current uppercase text-(length:--text-micro)",children:s?"Copied!":n?"Copy failed":e.name})]})}):null}r(bCe,"WorktreeBanner");var Not=3e4;function Sot(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(Sot,"formatRelativeTimestamp");function Cot(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(Cot,"describeReason");function vCe({devServer:e}){const[s,n]=(0,m.useState)(!1);if((0,m.useEffect)(()=>{if(!s)return;const d=window.setTimeout(()=>{n(!1)},Not);return()=>window.clearTimeout(d)},[s]),!e?.enabled||!e.restartRequired)return null;const a=e,i=Sot(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 du.requestDevServerRestart()}catch(u){n(!1),window.alert(u instanceof Error?u.message:"Failed to request restart")}}}return r(c,"requestRestartNow"),(0,t.jsx)("div",{className:"border-b border-amber-300/60 bg-amber-50 text-amber-950 dark:border-amber-500/25 dark:bg-amber-500/10 dark:text-amber-100",children:(0,t.jsxs)("div",{className:"flex flex-col gap-3 px-3 py-2.5 md:flex-row md:items-center md:justify-between",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-(--tracking-caps)",children:[(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{children:"Restart Required"}),e.autoRestartEnabled?(0,t.jsx)(ct,{variant:"ghost",className:"bg-amber-900/10 text-(length:--text-nano) tracking-(--tracking-eyebrow) dark:bg-amber-100/10",children:"Auto-Restart On"}):null]}),(0,t.jsxs)("p",{className:"mt-1 text-sm",children:[Cot(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)(Kqe,{className:"h-3.5 w-3.5"}),(0,t.jsxs)("span",{children:["Waiting for ",l," to finish"]})]}):e.autoRestartEnabled?(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10",children:[(0,t.jsx)(Ci,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{children:"Auto-restart will trigger when the instance is idle"})]}):(0,t.jsxs)("div",{className:"inline-flex items-center gap-2 rounded-full bg-amber-900/10 px-3 py-1.5 dark:bg-amber-100/10",children:[(0,t.jsx)(Ci,{className:"h-3.5 w-3.5"}),(0,t.jsxs)("span",{children:["Restart ",(0,t.jsx)("code",{children:"pnpm dev:once"})," after the active work is safe to interrupt"]})]}),(0,t.jsxs)("button",{type:"button",className:"inline-flex items-center gap-2 rounded-md bg-amber-950 px-3 py-1.5 text-xs font-semibold text-amber-50 transition-colors hover:bg-amber-900 disabled:cursor-not-allowed disabled:opacity-60 dark:bg-amber-200 dark:text-amber-950 dark:hover:bg-amber-100",onClick:r(()=>{c()},"onClick"),disabled:s,children:[(0,t.jsx)(Ci,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{children:s?"Restart requested":"Restart now"})]})]})]})})}r(vCe,"DevRestartBanner");var yCe=["standalone","fullscreen","window-controls-overlay"];function _ot(e){return`(display-mode: ${e})`}r(_ot,"displayModeQuery");function Iot(){if(!(typeof window>"u"||typeof window.matchMedia!="function"))return window.matchMedia.bind(window)}r(Iot,"defaultMatchMedia");function x6(e=Iot(),s=typeof navigator>"u"?void 0:navigator.standalone){return s===!0?!0:e?yCe.some(n=>e(_ot(n)).matches):!1}r(x6,"isChromelessDisplayMode");function J2({label:e,children:s,onClick:n}){return(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",className:"size-8 text-muted-foreground hover:text-foreground","aria-label":e,onClick:r(()=>{n()},"onClick"),children:s})}),(0,t.jsx)(Un,{children:e})]})}r(J2,"ControlButton");function Aot(e=typeof window>"u"?null:window.history.state){const s=e?.idx;return typeof s=="number"&&s>0}r(Aot,"hasInAppHistory");function Tot(){const[e,s]=(0,m.useState)(()=>typeof window<"u"?x6():!1);return(0,m.useEffect)(()=>{if(typeof window>"u")return;const n=r(()=>s(x6()),"update");if(n(),typeof window.matchMedia!="function")return;const a=yCe.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(Tot,"useChromeless");function g6({mobile:e,onNavigateHome:s}){const n=Tot(),a=Xc(),i=(0,m.useCallback)(()=>{if(Aot()){window.history.back();return}s?s():window.location.assign("/dashboard")},[s]),o=(0,m.useCallback)(()=>{window.location.reload()},[]),l=(0,m.useCallback)(async()=>{const d=window.location.href;try{if(navigator.share){await navigator.share({title:document.title||"Paperclip",url:d});return}await fa(d),a?.pushToast({title:"Link copied",tone:"success"})}catch(u){if(u instanceof DOMException&&u.name==="AbortError")return;a?.pushToast({title:"Share failed",body:"Try opening the page in your browser.",tone:"error"})}},[a]),c=(0,m.useCallback)(()=>{window.open(window.location.href,"_blank","noopener,noreferrer")},[]);return n?(0,t.jsxs)("div",{className:W("flex items-center gap-1",e?"h-10 border-b border-border bg-background/95 px-3 backdrop-blur supports-[backdrop-filter]:bg-background/85":"h-9 border-b border-border px-2"),children:[(0,t.jsx)(J2,{label:"Back",onClick:i,children:(0,t.jsx)(Tl,{className:"h-4 w-4"})}),(0,t.jsx)("div",{className:"flex-1"}),(0,t.jsx)(J2,{label:"Refresh",onClick:o,children:(0,t.jsx)(_i,{className:"h-4 w-4"})}),(0,t.jsx)(J2,{label:"Share",onClick:l,children:(0,t.jsx)(K7,{className:"h-4 w-4"})}),(0,t.jsx)(J2,{label:"Open in Browser",onClick:c,children:(0,t.jsx)(Vn,{className:"h-4 w-4"})})]}):null}r(g6,"StandaloneBrowserControls");var Rot=16384,Eot=40;function Pot(e){if(!e)return;const s=[];for(const n of e.slice(0,Rot).split(`
|
|
353
353
|
`).slice(0,41)){const a=/^\s*(?:at|in) ([A-Za-z_$][\w$.-]{0,99})(?:\s|$)/.exec(n)?.[1]??/^([A-Za-z_$][\w$.-]{0,99})@/.exec(n)?.[1];if(a&&s.push(` at ${a}`),s.length===Eot)break}return s.length?`
|
|
354
354
|
${s.join(`
|
|
355
|
-
`)}`:void 0}r(Pot,"sanitizeComponentStack");function jCe(){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(jCe,"readBrowserErrorState");function Mot(e){const s=Pot(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:jCe()}}}r(Mot,"buildBrowserErrorContext");var Sse=Promise.resolve();function YW(e){const s=Sse.then(e);return Sse=s.catch(()=>{}),s}r(YW,"enqueue");var mN=null;function Dot(e,s){return YW(async()=>{if(!mN)try{const n=await Jc(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init($ot(e,s)),mN=n}catch{}})}r(Dot,"initBrowserErrorMonitoring");function Lot(){return YW(async()=>{const e=mN;if(mN=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(Lot,"teardownBrowserErrorMonitoring");function wCe(e,s){let n;try{s&&(n=Mot(s))}catch{}YW(async()=>{try{n?mN?.captureException(e,n):mN?.captureException(e)}catch{}})}r(wCe,"captureBrowserException");function $ot(e,s){return{dsn:e,environment:s??void 0,release:"a7fd67fa1b20217378e4d25324a02504a90eb0d6",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??jCe()},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($ot,"buildBrowserSentryInitOptions");var Oot=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){wCe(e,{boundary:"route",componentStack:s.componentStack})}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){const{error:e}=this.state;return e?(0,t.jsxs)("div",{className:"mx-auto max-w-2xl space-y-4 px-4 py-10",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"This page hit an error"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Something went wrong while rendering this page. You can go back and try again, or reload."})]}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive whitespace-pre-wrap",children:e.message}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:this.props.onReset,children:"Go back"}),(0,t.jsx)(L,{size:"sm",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})]})]}):this.props.children}};function kCe({children:e}){const s=na(),n=Mn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(Oot,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(kCe,"RouteErrorBoundary");var Cse={bot:no,cpu:ym,brain:Xx,zap:A3,rocket:B$e,code:Sxe,terminal:hg,shield:EI,eye:Ed,search:oa,wrench:Pf,hammer:mM,lightbulb:RI,sparkles:Np,star:yp,heart:FC,flame:mOe,bug:Kv,cog:wfe,database:PI,globe:Ap,lock:pd,mail:c7,"message-square":Sf,"file-code":Ll,"git-branch":io,package:Th,puzzle:Zx,target:vp,wand:H7,atom:iOe,"circuit-board":lqe,radar:O$e,swords:qqe,telescope:V$e,microscope:Cqe,crown:jfe,gem:Cxe,hexagon:Ad,pentagon:Tqe,fingerprint:Oz},Fot="bot";function Bot(e){return e&&HLe.includes(e)?Cse[e]:Cse[Fot]}r(Bot,"getAgentIcon");function F5({icon:e,className:s}){const n=Bot(e);return(0,t.jsx)(n,{className:s})}r(F5,"AgentIcon");function NCe({open:e,onOpenChange:s,...n}){return(0,t.jsx)(Ys,{open:e,onOpenChange:s,children:(0,t.jsxs)(Js,{"aria-describedby":void 0,className:"gap-0 overflow-hidden p-0 sm:max-w-md",children:[(0,t.jsxs)("div",{className:"px-4 pt-4 pb-3",children:[(0,t.jsx)(Xs,{children:"Chat with an agent"}),n.existingChatAgentIds&&(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"One conversation per agent. Pick up where you left off."})]}),(0,t.jsx)(zot,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(NCe,"AgentChatPicker");function zot({agents:e,onSelect:s,onComplete:n,loading:a,error:i,onRetry:o,existingChatAgentIds:l,renderAgentIcon:c}){const d=(0,m.useRef)(!1),u=(0,m.useRef)(null);(0,m.useEffect)(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null),[b,v]=(0,m.useState)(null);async function j(N){if(f)return;x(N.id),v(null);const w=new AbortController;u.current=w;try{await s(N,w.signal),d.current&&n()}catch(k){v(k instanceof Error?k.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(j,"selectAgent"),(0,t.jsxs)(OI,{children:[(0,t.jsx)(VN,{"aria-label":"Search agents by name or role",placeholder:"Search by name or role…",value:h,onValueChange:p}),b&&(0,t.jsx)("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:b}),f&&(0,t.jsx)("p",{role:"status",className:"sr-only",children:"Opening conversation…"}),i?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 p-4 text-sm",children:[(0,t.jsx)("p",{children:"Couldn’t load agents. Try again."}),o&&(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:o,children:"Retry"})]}):a?(0,t.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:"Loading agents…"}):(0,t.jsxs)(WN,{children:[(0,t.jsx)(KN,{children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4",children:[(0,t.jsx)("span",{children:e.length?`No agents match “${h}”`:"No agents yet."}),e.length?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Try another name or role."}),(0,t.jsx)(L,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(Au,{children:e.map(N=>(0,t.jsxs)(Ko,{value:N.id,keywords:[N.name,N.title??"",N.role],onSelect:r(()=>{j(N)},"onSelect"),disabled:f!==null,className:"gap-3 px-3 py-3",children:[c?c(N):(0,t.jsx)(F5,{icon:N.icon,className:"size-4 shrink-0"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate font-medium",children:N.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:N.title??N.role})]}),l&&(0,t.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:l.includes(N.id)?"Open chat":"New chat"}),N.status==="paused"&&(0,t.jsx)("span",{className:"text-xs text-(--status-agent-paused)",children:"Paused"}),N.status==="terminated"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Terminated"}),N.status==="pending_approval"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Awaiting approval"})]},N.id))})]})]})}r(zot,"AgentChatPickerResults");function kE({agents:e,existingChatAgentIds:s,availableAgents:n=e,activeId:a,previews:i={},loading:o=!1,error:l,onRetry:c,initialSearch:d="",onSelect:u,onBrowse:h,onAddChat:p,historyLoading:f,historyError:x,onRetryHistory:b}){const v=Mn(),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(d),S=(0,m.useRef)(null),C=(0,m.useId)(),I=w.trim().toLocaleLowerCase(),R=e.filter(A=>`${A.name} ${A.title??""} ${A.role}`.toLocaleLowerCase().includes(I));function T(){k(""),S.current?.focus()}return r(T,"focusSearch"),(0,t.jsxs)("aside",{"aria-labelledby":C,className:"flex h-full min-h-0 flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-3 pb-4 pt-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("h2",{id:C,className:"text-sm font-semibold",children:"Chat"}),(0,t.jsx)(L,{variant:"outline",size:"icon-sm","aria-label":"Add chat",title:"Add chat",onClick:r(()=>N(!0),"onClick"),children:(0,t.jsx)(yn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(oa,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ht,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(A=>k(A.target.value),"onChange"),onKeyDown:r(A=>{A.key==="Escape"&&(A.stopPropagation(),k(""))},"onKeyDown"),className:"h-8 pl-8 pr-8 text-xs md:text-xs"}),w&&(0,t.jsx)(L,{variant:"ghost",size:"icon-xs","aria-label":"Clear search",className:"absolute right-1 top-1/2 -translate-y-1/2",onClick:T,children:(0,t.jsx)(Fn,{className:"size-3"})})]})]}),(0,t.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 pb-3 scrollbar-auto-hide",children:[(0,t.jsx)("p",{className:"px-2 text-(length:--text-micro) font-medium uppercase tracking-widest text-muted-foreground",children:I?"Search results":"Teammates"}),(0,t.jsx)("span",{role:"status",className:"sr-only",children:o?"Loading agents":`${R.length} ${R.length===1?"agent":"agents"}`}),f&&(0,t.jsx)("p",{role:"status",className:"px-2 text-xs text-muted-foreground",children:"Loading chat history…"}),x&&(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-3",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Some chat history couldn’t load."}),(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:b,children:"Retry chat history"})]}),l?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm",children:"Couldn’t load your chats."}),(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:c,children:"Try again"})]}):o?(0,t.jsx)("div",{"aria-hidden":"true",className:"flex flex-col gap-1",children:[0,1,2,3].map(A=>(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-md px-2 py-3 motion-safe:animate-pulse",children:[(0,t.jsx)("div",{className:"size-8 shrink-0 rounded-lg bg-muted"}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-2",children:[(0,t.jsx)("div",{className:"h-3 w-2/3 rounded-sm bg-muted"}),(0,t.jsx)("div",{className:"h-2 w-full rounded-sm bg-muted"})]})]},A))}):R.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:R.map(A=>(0,t.jsxs)(Ke,{to:`/chats/${encodeURIComponent(A.status==="terminated"?A.id:Xl(A))}`,"aria-current":a===A.id?"page":void 0,title:`${A.name}${A.title?` · ${A.title}`:""}`,onClick:r(D=>{u&&(D.preventDefault(),u(A))},"onClick"),className:W("flex min-w-0 items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",a===A.id&&"bg-accent text-accent-foreground"),children:[(0,t.jsx)(gr,{agent:A,size:32}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate text-sm font-medium",children:A.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:A.status==="terminated"?"Terminated":A.status==="paused"?"Paused":i[A.id]??A.title??"Start a conversation"})]})]},A.id))}):!e.length&&(f||x)?null:(0,t.jsxs)("div",{className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:e.length?"No agents found":"No chats yet"}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:e.length?"Try another name or role.":"Choose an agent to start a conversation."}),!e.length&&(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:r(()=>N(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:T,children:"Clear search"})]})]}),(0,t.jsx)("div",{className:"shrink-0 px-3 py-4",children:(0,t.jsx)(L,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2 text-muted-foreground",asChild:!h,onClick:h,children:h?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(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)(NCe,{agents:n,open:j,onOpenChange:N,existingChatAgentIds:s??e.map(A=>A.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(A=>(0,t.jsx)(gr,{agent:A,size:32}),"renderAgentIcon"),onSelect:r(async(A,D)=>{p?await p(A,D):u?await u(A,D):v(`/chats/${encodeURIComponent(Xl(A))}`),D?.aborted||k("")},"onSelect")})]})}r(kE,"AgentConversationSidebar");var B5={list:r(e=>Te.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>Te.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>Te.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function SCe(){const{selectedCompanyId:e}=ps(),{enabled:s,loaded:n}=Yy(),a=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:ee({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn"),enabled:s&&!!e}),chats:ee({queryKey:P.agentChats.list(e,i),queryFn:r(()=>B5.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(SCe,"useAgentChatNavigation");function CCe(e,s){const n=Pt(),a=Mn(),{isMobile:i,setSidebarOpen:o}=qa(),l=(0,m.useRef)({companyId:e,userId:s,mounted:!0});return(0,m.useEffect)(()=>{const c={companyId:e,userId:s,mounted:!0};return l.current=c,()=>{c.mounted=!1}},[e,s]),(0,m.useCallback)(async(c,d)=>{if(!e||c.companyId!==e)throw new Error("Choose an agent from this company.");const u=l.current,h=await B5.ensure(e,c.id);n.setQueryData(P.agentChats.detail(e,s,c.id),h),n.setQueryData(P.issues.detail(h.id),h),n.setQueryData(P.agentChats.list(e,s),p=>[h,...(p??[]).filter(f=>f.id!==h.id)].sort((f,x)=>new Date(x.updatedAt).getTime()-new Date(f.updatedAt).getTime()||x.id.localeCompare(f.id))),!(!u.mounted||l.current!==u||d?.aborted)&&(a(`/chats/${encodeURIComponent(Xl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(CCe,"useOpenAgentChat");function qot(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=SCe(),o=CCe(e,s),l=Mn(),c=Yf(e),{isMobile:d,setSidebarOpen:u}=qa(),{pathname:h}=na(),p=h.split("/chats/")[1]?.split("/")[0],f=n.data??[],x=n.isSuccess?[...new Set((a.data??[]).flatMap(C=>C.conversationAgentId&&!f.some(I=>I.id===C.conversationAgentId)?[C.conversationAgentId]:[]))]:[],b=Rh({queries:x.map(C=>({queryKey:P.agents.detail(C),queryFn:r(()=>$t.get(C,e),"queryFn")}))}),v=new Map(f.map(C=>[C.id,C]));for(const C of b)C.data&&v.set(C.data.id,C.data);const j=[...v.values()].find(C=>C.id===p||C.status!=="terminated"&&encodeURIComponent(Xl(C))===p),N=(a.data??[]).flatMap(C=>{const I=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return I?[I]:[]});j&&!N.some(C=>C.id===j.id)&&N.unshift(j);const w=new Set(N.map(C=>C.id)),k=f.filter(C=>!w.has(C.id)&&C.status!=="terminated"&&(!c.isSuccess||Of(c.data,"agent",C.id)!=="left")).sort((C,I)=>C.name.localeCompare(I.name,void 0,{sensitivity:"base"})),S=Object.fromEntries((a.data??[]).filter(C=>C.conversationState==="active").map(C=>[C.conversationAgentId,"Working…"]));return(0,t.jsx)(kE,{agents:[...N,...k],availableAgents:f,existingChatAgentIds:N.map(C=>C.id),activeId:j?.id,previews:S,loading:n.isPending||a.isPending||i.isPending,error:n.error??a.error??i.error,onRetry:r(()=>{n.refetch(),a.refetch(),i.refetch()},"onRetry"),historyLoading:b.some(C=>C.isPending),historyError:b.find(C=>C.error)?.error,onRetryHistory:r(()=>{b.filter(C=>C.isError).forEach(C=>{C.refetch()})},"onRetryHistory"),onAddChat:o,onSelect:r(C=>{l(`/chats/${encodeURIComponent(C.status==="terminated"?C.id:Xl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(qot,"AgentConversationsSidebar");var X2=240,b6=208,v6=420,_se=16;function z5(e){return Math.min(v6,Math.max(b6,e))}r(z5,"clampSidebarWidth$1");function Ise(e){if(typeof window>"u")return X2;try{const s=window.localStorage.getItem(e);if(!s)return X2;const n=Number.parseInt(s,10);return Number.isFinite(n)?z5(n):X2}catch{return X2}}r(Ise,"readStoredSidebarWidth$1");function Ase(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(z5(s)))}catch{}}r(Ase,"writeStoredSidebarWidth$1");function Uot({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)(()=>Ise(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=Ise(o);v.current=E,f(E)},[o]);const N=s?p:0,w=s?n?64:N:0,k=s?n&&!a?64:N:0,S=k>w,C=i&&s&&!n,I=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),T=(0,m.useCallback)(E=>{const z=z5(E);v.current=z,f(z),Ase(o,z)},[o]),A=(0,m.useCallback)(E=>{C&&(E.preventDefault(),E.currentTarget.setPointerCapture(E.pointerId),j.current={startX:E.clientX,startWidth:v.current},b(!0))},[C]),D=(0,m.useCallback)(E=>{if(!j.current)return;const z=z5(j.current.startWidth+E.clientX-j.current.startX);v.current=z,f(z)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),Ase(o,v.current))},[o]),B=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),T(p-_se)):E.key==="ArrowRight"?(E.preventDefault(),T(p+_se)):E.key==="Home"?(E.preventDefault(),T(b6)):E.key==="End"&&(E.preventDefault(),T(v6)))},[C,T,p]);return(0,t.jsxs)("div",{className:W("relative h-full shrink-0",l),style:I,children:[(0,t.jsx)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:e}),C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":b6,"aria-valuemax":v6,"aria-valuenow":p,tabIndex:0,"data-dragging":x?"":void 0,className:"group absolute inset-y-0 z-20 cursor-col-resize touch-none outline-none",style:{right:-4,width:8},onPointerDown:A,onPointerMove:D,onPointerUp:M,onPointerCancel:M,onLostPointerCapture:M,onKeyDown:B,children:(0,t.jsx)("div",{className:W("mx-auto h-full w-0.5 transition-colors",x?"bg-ring":"bg-transparent group-hover:bg-ring group-focus-visible:bg-ring")})}):null]})}r(Uot,"SidebarShell$1");function Z2({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)(xye,{children:e})})}r(Z2,"SecondarySidebar$1");var _Ce={listStacks:r(()=>Te.get("/cloud/stacks"),"listStacks")};function p4(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(p4,"cloudAppUrl");function ICe(e){return p4(e,"/stacks/new")}r(ICe,"cloudStackCreateUrl");function ACe(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(ACe,"tenantSignInReturnPath");function Kot(e,s,n){const a=s?.trim();if(!a)return null;const i=p4(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",ACe(n)),o.toString()}r(Kot,"cloudStackEntryUrl");function TCe(e,s){const n=s?.trim();return n?p4(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(TCe,"cloudStackInviteUrl");function Wot(e){return p4(e,"/orgs?manage=1")}r(Wot,"cloudPortfolioManageUrl");function RCe(){const e=$c(),s=!!e,n=ee({queryKey:P.cloud.stacks,queryFn:r(()=>_Ce.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:TCe(e.cloudBaseUrl,a.stackSlug)}r(RCe,"useCloudInviteUrl");function Vot(e,s){if(!s)return!1;if(s.source==="local_implicit"||s.isInstanceAdmin)return!0;if(!e)return!1;const n=s.memberships?.find(a=>a.companyId===e&&a.status==="active");return n?.membershipRole==="owner"||n?.membershipRole==="admin"}r(Vot,"canInviteCompanyMembers");function ECe(e=!0){const s=mLe(),n=ee({queryKey:P.access.currentBoardAccess,queryFn:r(()=>pr.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&Vot(s?.selectedCompanyId,n.data)}r(ECe,"useCanInviteCompanyMembers");function PCe(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=ee({queryKey:P.stagingCommit,queryFn:r(()=>du.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(PCe,"useStagingCommit");function Hot(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(Hot,"slugifyUserPart");function MCe(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=Hot(n);if(a)return`/u/${a}`}return"/u/me"}r(MCe,"userProfilePath");var Got="Toggle the app appearance.";function yk({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=mBe(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?wve:wbe;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:Got})]})]}):(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:W("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(yk,"ThemeToggle");var U_=null,DCe=!1,y6=!1,j6=new Set;function q5(){for(const e of j6)e()}r(q5,"emit");function Qot(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(Qot,"isIosSafariLike");function Yot(e=window){const s=r(a=>{a.preventDefault(),U_=a,q5()},"onPrompt"),n=r(()=>{U_=null,DCe=!0,q5()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(Yot,"captureInstallPrompt");function Jot(){return DCe||x6()?"installed":U_?"prompt":Qot()?"ios-manual":"unavailable"}r(Jot,"installAvailability");async function Xot(){const e=U_;if(!e)return"unavailable";U_=null,q5(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(Xot,"promptInstall");function w6(e){y6!==e&&(y6=e,q5())}r(w6,"setIosInstallHelpOpen");function Zot(){return y6}r(Zot,"iosInstallHelpOpen");function elt(){return(0,m.useSyncExternalStore)(LCe,Zot,()=>!1)}r(elt,"useIosInstallHelpOpen");function LCe(e){return j6.add(e),()=>{j6.delete(e)}}r(LCe,"subscribe$1");function tlt(){return(0,m.useSyncExternalStore)(LCe,Jot,()=>"unavailable")}r(tlt,"useInstallAvailability");var Tse="Install app",slt="Add Paperclip to your home screen or dock.";function $Ce({variant:e,onAfterAction:s}){const n=tlt();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?w6(!0):Xot(),s?.()},"handleClick");return e==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:"flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",onClick:a,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(po,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:Tse})]}):(0,t.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",onClick:a,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(po,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:Tse}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:slt})]})]})}r($Ce,"InstallAppMenuAction");function nlt(){const e=elt();return(0,t.jsx)(Ys,{open:e,onOpenChange:w6,children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Install Paperclip"}),(0,t.jsx)(jn,{children:"Add Paperclip to your Home Screen from Safari."})]}),(0,t.jsxs)("ol",{className:"space-y-3 text-sm text-foreground",children:[(0,t.jsxs)(tO,{index:1,icon:(0,t.jsx)(Fqe,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(tO,{index:2,icon:(0,t.jsx)(zqe,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(tO,{index:3,children:["Keep ",(0,t.jsx)("strong",{children:"Open as Web App"})," on, then tap ",(0,t.jsx)("strong",{children:"Add"}),"."]})]}),(0,t.jsx)(hr,{children:(0,t.jsx)(L,{type:"button",onClick:r(()=>w6(!1),"onClick"),children:"Done"})})]})})}r(nlt,"IosInstallHelpDialog");function tO({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(tO,"InstallStep");function rlt(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(rlt,"formatTimestamp$2");function alt(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(alt,"isValidTimestamp");function ilt(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(ilt,"restartTimestamp");function olt(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(olt,"commitLabel");function llt(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(llt,"localChangesLabel");function sO({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(sO,"ServerInfoRow");function OCe(){const e=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=ee({queryKey:P.health,queryFn:r(()=>du.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=ilt(n),l=alt(o),c=i?"Health unavailable":a?"Loading...":rlt(o),d=i?"Health unavailable":a?"Loading...":olt(n),u=i?"Health unavailable":a?"Loading...":llt(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)(sO,{icon:au,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(sO,{icon:D7,label:"Running commit",value:d}),(0,t.jsx)(sO,{icon:pqe,label:"Checkout state",value:u})]})}r(OCe,"SidebarServerInfo");var clt="/company/settings/members?tab=invites",dlt="https://docs.paperclip.ing/",ult="https://paperclip.ing/feedback";function mlt(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(mlt,"deriveInitials$2");function nO({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(nO,"MenuAction$1");function Rse({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!$c(),{hidden:l,loaded:c}=cu(),d=RCe(),u=ECe(!o),h=o?d:u?clt:null,p=c&&h!==null&&!dg(l,"company.members")&&!dg(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:b,setSidebarOpen:v,collapsed:j,peeking:N}=qa(),w=j&&!N&&!a,k=s??f,S=PCe(k),C=n??x,{data:I}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),R=eS({onSignedOut:B}),T=I?.user.name?.trim()||"Board",A=I?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),D=mlt(T),M=MCe(I?.user);function B(){C(!1),b&&v(!1)}r(B,"closeNavigationChrome");function E(){R.mutate()}return r(E,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(br,{open:k,onOpenChange:C,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",w?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(Mo,{size:"sm",children:[I?.user.image?(0,t.jsx)(xd,{src:I.user.image,alt:T}):null,(0,t.jsx)(Do,{children:D})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:T})]})}),(0,t.jsxs)(dr,{side:"top",align:"start",sideOffset:10,className:"min-h-(--profile-popover-min-height) w-(--profile-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"relative flex h-(--profile-popover-header-height) shrink-0 items-center gap-2.5 px-3.5",children:[(0,t.jsx)(Ke,{to:M,"aria-label":"View profile",onClick:B,className:"absolute inset-0 transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"}),(0,t.jsxs)(Mo,{className:"pointer-events-none relative size-9",children:[I?.user.image?(0,t.jsx)(xd,{src:I.user.image,alt:T}):null,(0,t.jsx)(Do,{className:"text-xs text-foreground",children:D})]}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1",children:[(0,t.jsx)("h2",{className:"truncate text-sm font-semibold leading-(--profile-popover-label-line-height) text-foreground",children:T}),(0,t.jsx)("p",{className:"truncate text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground",children:A}),S?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${S}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${S} on GitHub`,title:S,children:["SHA ",S.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[(0,t.jsx)(nO,{label:"Settings",icon:iu,href:"/company/settings",onClick:B}),p&&h?(0,t.jsx)(nO,{label:"Invite",icon:Gf,href:h,topLevel:o,onClick:B}):null,(0,t.jsx)(nO,{label:"Documentation",icon:GN,href:dlt,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(yk,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)($Ce,{variant:"compact-menu-action",onAfterAction:r(()=>C(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-destructive/10",R.isPending&&"cursor-not-allowed opacity-60"),onClick:E,disabled:R.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Tp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:R.isPending?"Signing out...":"Sign out"})]}):null,(0,t.jsx)(OCe,{})]})]})]}),!w&&!o?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("a",{href:ult,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)(_g,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Un,{side:"top",children:"Share feedback"})]}):null]})})}r(Rse,"SidebarAccountMenu$1");function FCe({onNewIssue:e,onSearch:s,onToggleSidebar:n,onTogglePanel:a,onShowShortcuts:i,onGoToInbox:o}){(0,m.useEffect)(()=>{let l=!1,c=null;const d=r(()=>{c!==null&&(window.clearTimeout(c),c=null)},"clearGoChordTimeout"),u=r(()=>{l=!1,d()},"disarmGoChord"),h=r(()=>{l=!0,d(),c=window.setTimeout(()=>{l=!1,c=null},1200)},"armGoChord");function p(b){if(b.defaultPrevented){u();return}if(o){const v=exe({armed:l,defaultPrevented:b.defaultPrevented,key:b.key,metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,target:b.target,hasOpenDialog:wp()});if(v==="arm"){h();return}if(v==="navigate_inbox"){u(),b.preventDefault(),o();return}if(v==="focus_comment"||v==="open_file_viewer"){u(),b.preventDefault();return}v==="disarm"&&u()}if(!LI(b.target)&&!wp()){if(b.key==="/"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),oFe()||s?.();return}if(b.key==="?"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),i?.();return}b.key==="c"&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&(b.preventDefault(),e?.()),b.key==="["&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),n?.()),b.key==="]"&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(b=>{b.target instanceof HTMLElement&&b.target!==document.body&&u()},"handleFocusIn");return document.addEventListener("pointerdown",f,!0),document.addEventListener("focusin",x,!0),document.addEventListener("keydown",p),()=>{u(),document.removeEventListener("pointerdown",f,!0),document.removeEventListener("focusin",x,!0),document.removeEventListener("keydown",p)}},[e,s,n,a,i,o])}r(FCe,"useKeyboardShortcuts");var hlt=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function BCe(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!hlt.has(n)}r(BCe,"isRememberableCompanyPath");function plt(e){const s=ly(e.companyPrefix);return e.companies.find(n=>ly(n.issuePrefix)===s)??null}r(plt,"findCompanyByPrefix");function flt(e){const s=d7(e.pathname);return s?plt({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(flt,"getRememberedPathOwnerCompanyId");function xlt(e){const s=e.path?pM(e.path):"/dashboard";if(!BCe(s))return"/dashboard";const[n,a]=(s.split("?")[0]??"").split("/").filter(Boolean);if(n==="issues"&&a){const i=/^([A-Za-z]+)-\d+$/.exec(a);if(i&&ly(i[1]??"")!==ly(e.companyPrefix))return"/dashboard"}return s}r(xlt,"sanitizeRememberedPathForCompany");var zCe="paperclip.companyPaths";function qCe(){try{const e=localStorage.getItem(zCe);if(e)return JSON.parse(e)}catch{}return{}}r(qCe,"getCompanyPaths");function glt(e,s){const n=qCe();n[e]=s,localStorage.setItem(zCe,JSON.stringify(n))}r(glt,"saveCompanyPath");function UCe(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=ps(),i=na(),o=Mn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>flt({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=pM(d);u&&BCe(h)&&glt(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=qCe(),h=xlt({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(UCe,"useCompanyPageMemory");var blt=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 KCe(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 blt({topZone:o("--mobile-nav-scroll-top-zone"),hideDistance:o("--mobile-nav-scroll-hide-distance"),showDistance:o("--mobile-nav-scroll-show-distance")},c.top,c.max);let u=null;const h=r(()=>{u===null&&(u=requestAnimationFrame(()=>{u=null;const{top:p,max:f}=l(),x=d.visible,b=d.update(p,f);b!==x&&a(b)}))},"onScroll");return window.addEventListener("scroll",h,{passive:!0}),()=>{window.removeEventListener("scroll",h),u!==null&&cancelAnimationFrame(u)}},[e,s]),n}r(KCe,"useMobileNavVisibility");function WCe(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(WCe,"resolveArchivedCompanyBounce");function vlt(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(vlt,"resolveCompanyArchiveDeparture");function VCe(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(VCe,"shouldSyncCompanySelectionFromRoute");function ylt(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(ylt,"shouldFocusMainContentAfterNavigation");function HCe(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{ylt(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(HCe,"scheduleMainContentFocus");function GCe(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(GCe,"pinDocumentScrollToZero");function zu({scope:e="global",requestedPrefix:s}){const n=na(),{setBreadcrumbs:a}=Bn(),{companies:i,selectedCompany:o}=ps();(0,m.useEffect)(()=>{a([{label:"Not Found"}])},[a]);const l=o??i[0]??null,c=l?`/${l.issuePrefix}/dashboard`:"/",d=`${n.pathname}${n.search}${n.hash}`,u=s?.toUpperCase(),h=e==="invalid_company_prefix"?"Organization not found":"Page not found",p=e==="invalid_company_prefix"?`No organization matches prefix "${u??"unknown"}".`:"This route does not exist.";return(0,t.jsx)("div",{className:"mx-auto max-w-2xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Es,{className:"h-5 w-5 text-destructive"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:p})]})]}),(0,t.jsxs)("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",(0,t.jsx)("code",{className:"font-mono",children:d})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{asChild:!0,children:(0,t.jsxs)(Ke,{to:c,children:[(0,t.jsx)(_3,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)(L,{variant:"outline",asChild:!0,children:(0,t.jsx)(Ke,{to:"/",children:"Go home"})})]})]})})}r(zu,"NotFoundPage");function jlt(e,s){return wje(e,s)[0]?.toLowerCase()??null}r(jlt,"getCompanyRouteSegment$1");var wlt=new Set(["browse","connections","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function klt({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=qa(),{openNewIssue:u,openOnboarding:h}=Yo(),{togglePanelVisible:p}=Jf(),f=Xc()?.pushToast??null,{companies:x,loading:b,selectedCompany:v,selectedCompanyId:j,selectionSource:N,setSelectedCompanyId:w}=ps(),{companyPrefix:k,pluginRoutePath:S,agentId:C,routineId:I}=va(),R=Mn(),T=na(),A=hM(),{enabled:D}=yc(),M=kje(T.pathname,k),B=M.builtInContextualSurface==="settings",E=M.companySegments,z=M.isTaskDetail,{enabled:$}=Yy(),q=$&&E[0]?.toLowerCase()==="chats",U=D&&(z||q),O=E[0]?.toLowerCase()==="tools",K=E[0]?.toLowerCase()==="apps",H=K&&E[1]&&!wlt.has(E[1].toLowerCase())?E[1]:null,Z=K&&E[1]?.toLowerCase()==="app"&&E[2]?E[2]:null,se=(0,m.useRef)(!1),ne=(0,m.useRef)(null),fe=(0,m.useRef)(null),X=(0,m.useRef)(new hye),re=(0,m.useRef)(T.key),oe=KCe(c&&!z,T.pathname),[G,Y]=(0,m.useState)(!1),Q=(0,m.useMemo)(()=>{if(!k)return null;const lt=k.toUpperCase();return x.find(Ee=>Ee.issuePrefix.toUpperCase()===lt)??null},[x,k]),te=!!k&&!b&&x.length>0&&!Q,ae=(0,m.useMemo)(()=>S?.toLowerCase()??jlt(T.pathname,k),[k,T.pathname,S]),le=Q?.id??null,he=Q?.issuePrefix??null,{slots:ce}=gd({slotTypes:["page","routeSidebar"],companyId:le,enabled:!!(le&&ae)}),ge=(0,m.useMemo)(()=>l9(ce,ae),[ae,ce]),me=(0,m.useMemo)(()=>({companyId:le,companyPrefix:he}),[le,he]),ie=B?(0,t.jsx)(U9e,{}):!D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(hZ,{}):H?(0,t.jsx)(uZ,{kind:"connection",connectionId:H}):Z?(0,t.jsx)(uZ,{kind:"application",applicationId:Z}):K||O?(0,t.jsx)(J9e,{}):ge?D?(0,t.jsx)(tA,{surface:`plugin:${ge.id}`,title:ge.displayName,children:(0,t.jsx)(Wu,{slot:ge,context:me,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(Wu,{slot:ge,context:me,className:"h-full w-full",missingBehavior:"placeholder"}):null,ue=q?(0,t.jsx)(qot,{}):M.builtInContextualSurface==="agent"&&C?(0,t.jsx)(uWe,{agentRef:C}):D&&M.builtInContextualSurface==="routine"&&I?(0,t.jsx)(NKe,{children:(0,t.jsx)(pWe,{routineId:I})}):D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(hZ,{}):ie,ke=ue!=null,be=D&&ke&&(q||M.builtInContextualSurface==="skills"||M.builtInContextualSurface==="agent"||M.builtInContextualSurface==="routine"||K||O),Ie=D&&ke&&!be,Ue=ke&&(!D||be),at=!D||!ke?null:ge&&!M.builtInContextualSurface?`plugin:${ge.id}`:M.builtInContextualSurface,dt=(0,m.useRef)(null),{data:de}=ee({queryKey:P.health,queryFn:r(()=>du.get(),"queryFn"),retry:!1,refetchInterval:r(lt=>lt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!D&&ke),()=>d(!1)),[ke,d,D]),(0,m.useEffect)(()=>{const lt=dt.current;at&&k&<&<.surface!==at&<.pathname!==T.pathname&&B9e({surface:at,companyPrefix:k,previousPathname:lt.pathname}),dt.current={pathname:T.pathname,surface:at}},[k,at,T.pathname]),(0,m.useEffect)(()=>{b||se.current||de?.deploymentMode!=="authenticated"&&(de?.cloud||x.length===0&&(se.current=!0,h()))},[x,b,h,de?.cloud,de?.deploymentMode]),(0,m.useEffect)(()=>{if(!k||b||x.length===0)return;if(!Q){const Ee=(j?x.find(Xe=>Xe.id===j):null)??x[0]??null;Ee&&j!==Ee.id&&w(Ee.id,{source:"route_sync"});return}if(k!==Q.issuePrefix){const Ee=T.pathname.replace(/^\/[^/]+/,"");R(`/${Q.issuePrefix}${Ee}${T.search}`,{replace:!0});return}const lt=WCe({matchedCompany:Q,selectedCompanyId:j,companies:x});if(lt){f?.({title:`${Q.name} is archived`,body:`Switched to ${lt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Q.id}`}),w(lt.id,{source:"route_sync"}),R(`/${lt.issuePrefix}/dashboard`,{replace:!0});return}VCe({selectionSource:N,selectedCompanyId:j,routeCompanyId:Q.id})&&w(Q.id,{source:"route_sync"})},[k,x,b,Q,T.pathname,T.search,R,f,N,j,w]);const Be=p,pt=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),vt=(0,m.useRef)(null),Le=(0,m.useRef)(!1),Qe=(0,m.useRef)(!1),ut=(0,m.useCallback)(()=>{vt.current!==null&&(window.clearTimeout(vt.current),vt.current=null)},[]),Ye=(0,m.useCallback)(()=>{ut(),vt.current=window.setTimeout(()=>l(!0),50)},[ut,l]),it=(0,m.useCallback)(()=>{ut(),l(!0)},[ut,l]),kt=(0,m.useCallback)(()=>{ut(),vt.current=window.setTimeout(()=>l(!1),120)},[ut,l]),tt=(0,m.useCallback)(()=>{Le.current=!0,i&&!Qe.current&&Ye()},[i,Ye]),Pe=(0,m.useCallback)(()=>{Le.current=!1,Qe.current=!1,kt()},[kt]),Ce=(0,m.useCallback)(()=>{Qe.current||it()},[it]),He=(0,m.useCallback)(()=>{Le.current||kt()},[kt]);(0,m.useEffect)(()=>ut,[ut]);const Je=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Je.current&&(i?(ut(),l(!1),Qe.current=Le.current):Qe.current=!1,Je.current=i)},[i,ut,l]),(0,m.useEffect)(()=>{if(!o)return;const lt=r(Ee=>{Ee.key==="Escape"&&(ut(),l(!1))},"onKeyDown");return window.addEventListener("keydown",lt),()=>window.removeEventListener("keydown",lt)},[o,ut,l]),UCe(),FCe({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:pt,onToggleSidebar:a,onTogglePanel:Be,onShowShortcuts:r(()=>Y(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const lt=30,Ee=50,Xe=75;let Ae=0,De=0;const _t=r(gt=>{const We=gt.touches[0];Ae=We.clientX,De=We.clientY},"onTouchStart"),ye=r(gt=>{const We=gt.changedTouches[0],Ot=We.clientX-Ae;if(!(Math.abs(We.clientY-De)>Xe)){if(!s&&Ae<lt&&Ot>Ee){n(!0);return}s&&Ot<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",_t,{passive:!0}),document.addEventListener("touchend",ye,{passive:!0}),()=>{document.removeEventListener("touchstart",_t),document.removeEventListener("touchend",ye)}},[c,s,n]),(0,m.useEffect)(()=>{const lt=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=lt}},[c]),(0,m.useEffect)(()=>{if(!c)return GCe()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const lt=fe.current;return HCe(lt)},[T.pathname]),(0,m.useEffect)(()=>{const lt=fe.current;if(!lt)return;const Ee=r(()=>{X.current.remember(re.current,lt.scrollTop)},"recordScroll");return lt.addEventListener("scroll",Ee,{passive:!0}),()=>lt.removeEventListener("scroll",Ee)},[]),(0,m.useLayoutEffect)(()=>{const lt=fe.current,Ee=mye({previousPathname:ne.current,pathname:T.pathname,navigationType:A,state:T.state});ne.current=T.pathname;const Xe=A==="POP",Ae=Xe?X.current.recall(T.key):0;if(re.current=T.key,Xe){Q3(lt,Ae);const De=requestAnimationFrame(()=>Q3(lt,Ae));return()=>cancelAnimationFrame(De)}Ee&&pye(lt)},[T.key,T.pathname,T.state,A]),(0,t.jsx)(uye,{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)(bCe,{}),(0,t.jsx)(vCe,{devServer:de?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",c?"w-full":"flex overflow-clip"),children:[c&&s&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>n(!1),"onClick"),"aria-label":"Close sidebar"}),c?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",s?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ke?(0,t.jsx)(Z2,{children:ue}):(0,t.jsx)(oZ,{children:e})})}),(0,t.jsx)(Rse,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}):(0,t.jsxs)(Uot,{open:s,collapsed:Ie?!1:i,peeking:Ie?!1:o,resizable:!0,onPanelMouseEnter:Ie?void 0:tt,onPanelMouseLeave:Ie?void 0:Pe,onPanelFocusCapture:!Ie&&i?Ce:void 0,onPanelBlurCapture:!Ie&&i?He:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Ie?(0,t.jsx)(Z2,{children:ue}):(0,t.jsx)(oZ,{children:e})}),(0,t.jsx)(Rse,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}),!c&&Ue&&!be?(0,t.jsx)(Z2,{className:"w-60 shrink-0",children:ue}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",c?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{"data-slot":c?"mobile-topbar":void 0,className:W(!c&&U&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(g6,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(fZ,{}),c&&B?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(Cje,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&U&&"streamlined-task-detail-surface"),children:[!c&&be?(0,t.jsx)(Z2,{className:"w-60 shrink-0 bg-background",children:ue}):null,(0,t.jsxs)("div",{className:W(!c&&U?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&U?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g6,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(fZ,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:fe,tabIndex:-1,style:c?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",!c&&U&&"pt-0 md:pt-0",c?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:te?(0,t.jsx)(zu,{scope:"invalid_company_prefix",requestedPrefix:k??v?.issuePrefix}):(0,t.jsx)(kCe,{children:(0,t.jsx)(mb,{})})})]}),(0,t.jsx)(Oje,{taskDetailLayout:!c&&U})]})]})]}),c&&(0,t.jsx)(gCe,{visible:oe}),(0,t.jsx)(Fje,{}),(0,t.jsx)(vwe,{}),(0,t.jsx)(cCe,{}),(0,t.jsx)(mCe,{}),(0,t.jsx)(hCe,{}),(0,t.jsx)(pCe,{open:G,onOpenChange:Y}),(0,t.jsx)(fCe,{}),(0,t.jsx)(mot,{health:de}),(0,t.jsx)(xCe,{localTrusted:de?.deploymentMode==="local_trusted"})]})})}r(klt,"Layout$1");var QCe=(0,m.createContext)(!1);function Nlt({children:e}){return(0,t.jsx)(QCe.Provider,{value:!0,children:e})}r(Nlt,"SidebarNavExpandedProvider");function Slt(){return(0,m.useContext)(QCe)}r(Slt,"useSidebarNavExpanded");function si({to:e,label:s,icon:n,iconNode:a,end:i,className:o,labelClassName:l,badge:c,badgeTone:d="default",badgeLabel:u,textBadge:h,textBadgeTone:p="default",alert:f=!1,liveCount:x,active:b,trailing:v,trailingLabel:j,liveAccessory:N}){const{isMobile:w,setSidebarOpen:k,collapsed:S,peeking:C}=qa(),I=Slt(),R=S&&!C&&!I,T=c!=null&&c>0,A=x!=null&&x>0,D=A?`${x} live`:T?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,M=!R||!D&&!j?void 0:`${s}${D?`, ${D}`:""}${j?`, ${j}`:""}`,B=(0,t.jsxs)(hb,{to:e,state:Qf,end:i,"aria-label":M,onClick:r(()=>{w&&k(!1)},"onClick"),className:r(({isActive:E})=>W("flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",b??E?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground",o),"className"),children:[(0,t.jsxs)("span",{className:"relative shrink-0",children:[a??(n?(0,t.jsx)(n,{className:"h-4 w-4"}):null),f&&(0,t.jsx)("span",{className:"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)","aria-hidden":"true"}),R&&!f&&A&&(0,t.jsxs)("span",{className:"absolute -right-0.5 -top-0.5 flex h-2 w-2","aria-hidden":"true",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)"})]}),R&&!f&&!A&&T&&(0,t.jsx)("span",{className:W("absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",d==="danger"?"bg-red-600":d==="warning"?"bg-amber-500":"bg-primary"),"aria-hidden":"true"})]}),(0,t.jsx)("span",{className:R?By:W("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(ct,{variant:"ghost",className:W("ml-auto px-1.5 text-(length:--text-nano) leading-none",p==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:h}),!R&&(A||N)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[N,A&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative flex h-2 w-2",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-600 dark:bg-blue-400"})]}),(0,t.jsxs)("span",{className:"text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400",children:[x," live"]})]})]}),!R&&T&&(0,t.jsx)(ct,{variant:"ghost",className:W("ml-auto px-1.5 leading-none",d==="danger"?"bg-red-600/90 text-red-50":d==="warning"?"bg-amber-500/90 text-amber-50":"bg-primary text-primary-foreground"),children:c})]});return R?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("div",{children:B})}),(0,t.jsx)(Un,{side:"right",children:s})]}):B}r(si,"SidebarNavItem");var Clt=3,Ese=12e4,_lt=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Yj(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Yj,"agentTimestamp");function Pse(e,s){if(s==="top")return e;const n=[...e];return s==="alphabetical"?(n.sort((a,i)=>a.name.localeCompare(i.name,void 0,{sensitivity:"base"})),n):(n.sort((a,i)=>{const o=Yj(i,"lastHeartbeatAt")-Yj(a,"lastHeartbeatAt");if(o!==0)return o;const l=Yj(i,"updatedAt")-Yj(a,"updatedAt");if(l!==0)return l;const c=Yj(i,"createdAt")-Yj(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r(Pse,"sortAgents");var Ilt="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function Alt({activeAgentId:e,activeTab:s,agent:n,disabled:a,isMobile:i,leaving:o,onLeaveAgent:l,onPauseResume:c,rail:d,runCount:u,setSidebarOpen:h,builtInStatus:p,starred:f=!1,onToggleStar:x,starPending:b=!1}){const v=Xl(n),j=s?`${Cm(n)}/${s}`:Cm(n),N=`${Cm(n)}/configuration`,w=e===v,k=n.status==="paused",S=k&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",I=k?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||k&&C,T=a?"Updating...":S?"Budget paused":k&&C?"Invalid org chain":I,A=p==="needs_setup"||p==="pending_approval",D=[A?`Built-in agent ${p.replace(/_/g," ")}`:null,C?"Invalid reporting chain":null].filter(Boolean).join(", ")||void 0,M=(0,t.jsx)(si,{to:j,label:n.name,iconNode:(0,t.jsx)(gr,{agent:n,size:16,className:"shrink-0 h-4 w-4"}),active:w,liveCount:u,labelClassName:A?"min-w-(--sz-4_5rem) flex-initial":void 0,className:W("min-w-0 flex-1",f&&!i?"pr-14":"pr-8"),trailing:A||C?(0,t.jsxs)("span",{className:"ml-1 flex shrink-0 items-center gap-1",children:[A?(0,t.jsx)(uk,{status:p,compact:!0}):null,C?(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):null]}):void 0,trailingLabel:D,liveAccessory:n.pauseReason==="budget"?(0,t.jsx)(XI,{title:"Agent paused by budget"}):void 0});return d?M:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[M,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(bb,{size:"row",quiet:!0,starred:!0,pending:b,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:Ilt})}):null,(0,t.jsxs)(Zr,{children:[(0,t.jsx)(Xr,{asChild:!0,children:(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:W("absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",i?"opacity-100":"pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100"),"aria-label":`Open actions for ${n.name}`,children:(0,t.jsx)(Ri,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(ea,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ls,{onClick:r(()=>{b||x(n,!f)},"onClick"),disabled:b,children:[b?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(yp,{className:W("size-4",f&&"fill-amber-500 text-amber-500")}),(0,t.jsx)("span",{children:f?"Remove from starred":"Star agent"})]}),(0,t.jsx)(ni,{})]}):null,(0,t.jsx)(ls,{asChild:!0,children:(0,t.jsxs)(Ke,{to:N,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(gc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{R||c(n,k?"resume":"pause")},"onClick"),disabled:R,title:S?"Agent was paused by budget limits":void 0,children:[k?(0,t.jsx)(HI,{className:"size-4"}):(0,t.jsx)(Td,{className:"size-4"}),(0,t.jsx)("span",{children:T})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(Alt,"SidebarAgentItem");function Tlt({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=Pt(),{selectedCompanyId:u}=ps(),{openNewAgent:h}=Yo(),{isMobile:p,setSidebarOpen:f,collapsed:x,peeking:b}=qa(),v=x&&!b,{pushToast:j}=da(),N=na(),{data:w}=ee({queryKey:P.agents.list(u),queryFn:r(()=>$t.list(u),"queryFn"),enabled:!!u}),{data:k}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:!!u}),S=k?.enableBuiltInAgents===!0,{data:C}=ee({queryKey:P.builtInAgents.list(u),queryFn:r(()=>Zh.list(u),"queryFn"),enabled:!!u&&S}),I=(0,m.useMemo)(()=>{const be=new Map;if(!S)return be;for(const Ie of C??[])Ie.agentId&&be.set(Ie.agentId,Ie.status);return be},[C,S]),{data:R}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),T=Yf(u),A=Rg(u),D=P.liveRuns(u),M=No({companyId:u,resourceKey:"live-runs",queryKey:D,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:B,dataUpdatedAt:E}=ee({queryKey:D,queryFn:r(()=>Jr.liveRunsForCompany(u),"queryFn"),enabled:M.enabled,refetchInterval:M.refetchInterval});So(M,B,E);const z=(0,m.useMemo)(()=>{const be=new Map;for(const Ie of B??[])be.set(Ie.agentId,(be.get(Ie.agentId)??0)+1);return be},[B]),$=(0,m.useMemo)(()=>{const be=new Set;for(const[Ie,Ue]of z)Ue>0&&be.add(Ie);return be},[z]),q=(0,m.useMemo)(()=>(w??[]).filter(be=>be.status!=="terminated"&&(!T.isSuccess||Of(T.data,"agent",be.id)!=="left")),[w,T.data,T.isSuccess]),U=R?.user?.id??R?.session?.userId??null,O=(0,m.useMemo)(()=>u?kye(u,U):null,[U,u]),[K,H]=(0,m.useState)(()=>O?mk(O):"top"),{orderedAgents:Z}=Cye({agents:q,companyId:u,userId:U}),se=(0,m.useMemo)(()=>Pse(Z,K),[Z,K]),ne=(0,m.useMemo)(()=>new Set(se.map(be=>be.id)),[se]);(0,m.useEffect)(()=>{const be=Date.now();for(const Ie of $)c.current.set(Ie,be);for(const Ie of c.current.keys())ne.has(Ie)||c.current.delete(Ie)},[$,ne]);const fe=(0,m.useMemo)(()=>{const be=Date.now(),Ie=c.current;return se.filter(Ue=>{if((z.get(Ue.id)??0)>0)return!0;const at=Ie.get(Ue.id);return at!==void 0&&be-at<=Ese})},[z,o,se]),X=fe.length>0,re=e?X?fe:se.slice(0,Clt):se,oe=e&&se.length>0,G=N.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=G?.[1]??null,Q=G?.[2]??null;(0,m.useEffect)(()=>{if(!O){H("top");return}H(mk(O))},[O]),(0,m.useEffect)(()=>{if(!O)return;const be=r(Ue=>{Ue.key===O&&H(mk(O))},"onStorage"),Ie=r(Ue=>{const at=Ue.detail;!at||at.storageKey!==O||H(at.sortMode)},"onCustomEvent");return window.addEventListener("storage",be),window.addEventListener(b_,Ie),()=>{window.removeEventListener("storage",be),window.removeEventListener(b_,Ie)}},[O]),(0,m.useEffect)(()=>{if(!e)return;const be=Date.now();let Ie=null;for(const at of se){if((z.get(at.id)??0)>0)continue;const dt=c.current.get(at.id);if(dt===void 0)continue;const de=dt+Ese;de<be||(Ie=Ie===null?de:Math.min(Ie,de))}if(Ie===null)return;const Ue=window.setTimeout(()=>{l(at=>at+1)},Math.max(0,Ie-be+1));return()=>{window.clearTimeout(Ue)}},[e,se,z,o]);const te=(0,m.useCallback)(be=>{const Ie=be==="alphabetical"||be==="recent"?be:"top";H(Ie),O&&Sye(O,Ie)},[O]),ae=je({mutationFn:r(({agent:be,action:Ie})=>Ie==="pause"?$t.pause(be.id,u??void 0):$t.resume(be.id,u??void 0),"mutationFn"),onMutate:r(({agent:be})=>{i(Ie=>{const Ue=new Set(Ie);return Ue.add(be.id),Ue})},"onMutate"),onSuccess:r(async(be,{agent:Ie,action:Ue})=>{u&&await Promise.all([d.invalidateQueries({queryKey:P.agents.list(u)}),d.invalidateQueries({queryKey:P.liveRuns(u)}),d.invalidateQueries({queryKey:P.dashboard(u)})]),await Promise.all([d.invalidateQueries({queryKey:P.agents.detail(Ie.id)}),d.invalidateQueries({queryKey:P.agents.detail(Xl(Ie))})]),j({title:Ue==="pause"?"Agent paused":"Agent resumed",body:Ie.name,tone:"success"})},"onSuccess"),onError:r((be,{agent:Ie,action:Ue})=>{j({title:Ue==="pause"?"Could not pause agent":"Could not resume agent",body:be instanceof Error?be.message:Ie.name,tone:"error"})},"onError"),onSettled:r((be,Ie,{agent:Ue})=>{i(at=>{const dt=new Set(at);return dt.delete(Ue.id),dt})},"onSettled")}),le=(0,m.useCallback)(be=>A.mutate({resourceType:"agent",resourceId:be.id,resourceName:be.name,state:"left"}),[A]),he=(0,m.useCallback)(be=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===be.id,[A.isPending,A.variables]),ce=(0,m.useCallback)((be,Ie)=>A.mutate({resourceType:"agent",resourceId:be.id,resourceName:be.name,starred:Ie}),[A]),ge=(0,m.useCallback)(be=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===be.id&&A.variables.starred!==void 0,[A.isPending,A.variables]),me=(0,m.useMemo)(()=>new Set(LM(T.data,"agent")),[T.data]),ie=(0,m.useMemo)(()=>Pse(q.filter(be=>me.has(be.id)),"alphabetical"),[q,me]),ue=(0,m.useMemo)(()=>re.filter(be=>!me.has(be.id)),[re,me]),ke=r((be,Ie)=>(0,t.jsx)(Alt,{activeAgentId:Y,activeTab:Q,agent:be,disabled:a.has(be.id),isMobile:p,leaving:he(be),onLeaveAgent:le,onPauseResume:r((Ue,at)=>ae.mutate({agent:Ue,action:at}),"onPauseResume"),rail:v,runCount:z.get(be.id)??0,setSidebarOpen:f,builtInStatus:I.get(be.id),starred:Ie||gb(T.data,"agent",be.id),onToggleStar:ce,starPending:ge(be)},be.id),"renderAgentRow");return(0,t.jsxs)(tg,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:yn,onClick:h},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Ho,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:_lt,radioValue:K,onRadioValueChange:te},children:[ie.map(be=>ke(be,!0)),ue.map(be=>ke(be,!1)),oe&&(()=>{const be=(0,t.jsxs)(Ke,{to:"/agents/all",state:Qf,"aria-label":v?"See all agents":void 0,onClick:r(()=>{p&&f(!1)},"onClick"),className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Ho,{className:"shrink-0 h-4 w-4"}),(0,t.jsx)("span",{className:v?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return v?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:be}),(0,t.jsx)(Un,{side:"right",children:"See all agents"})]}):be})()]})}r(Tlt,"SidebarAgents");var Rlt="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function Elt(){const{selectedCompanyId:e}=ps(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=qa(),o=a&&!i,l=na(),{data:c}=ee({queryKey:P.projects.list(e),queryFn:r(()=>pa.list(e),"queryFn"),enabled:!!e}),d=Yf(e),u=Rg(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(LM(d.data,"project"));if(v.size===0)return[];const j=new Map((c??[]).map(N=>[N.id,N]));return Array.from(v).map(N=>j.get(N)).filter(N=>!!N).sort((N,w)=>N.name.localeCompare(w.name,void 0,{sensitivity:"base"}))},[d.data,d.isSuccess,c]),f=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,starred:!1}),[u]),x=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,state:"left"}),[u]),b=(0,m.useCallback)(v=>u.isPending&&u.variables?.resourceType==="project"&&u.variables.resourceId===v.id,[u.isPending,u.variables]);return!d.isSuccess||p.length===0?null:(0,t.jsx)("div",{className:"flex flex-col gap-0.5","aria-label":"Starred projects",children:p.map(v=>{const j=cg(v),N=h===j||h===v.id,w=b(v),k=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=gb(d.data,"project",v.id),I=(0,t.jsxs)(hb,{to:`/projects/${j}/issues`,state:Qf,onClick:r(()=>{s&&n(!1)},"onClick"),className:W("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!o&&"pl-6",N?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(Em,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?By:"flex-1 truncate",children:v.name}),!o&&v.pauseReason==="budget"?(0,t.jsx)(XI,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:I})}),(0,t.jsx)(Un,{side:"right",children:v.name})]}):I,!o&&!s?(0,t.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:(0,t.jsx)(bb,{size:"row",quiet:!0,starred:C,pending:k,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:Rlt})}):null,!o&&s?(0,t.jsxs)(Zr,{children:[(0,t.jsx)(Xr,{asChild:!0,children:(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:"absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 opacity-100","aria-label":`Open actions for ${v.name}`,children:(0,t.jsx)(Ri,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(ea,{align:"end",className:"w-48",children:[(0,t.jsxs)(ls,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[k?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(yp,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:"Leave project"})]})]})]}):null]},v.id)})})}r(Elt,"SidebarStarredProjects");var Plt="size-5 shrink-0 rounded-md text-(length:--text-micro)",Mlt="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",Dlt="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",rO="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 YCe({company:e,inPopover:s=!1}){return(0,t.jsx)(tS,{companyName:e.name,logoUrl:e.logoUrl,className:s?Mlt:Plt})}r(YCe,"WorkspaceIcon");function Llt({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=UN({id:e.id,disabled:!s});return(0,t.jsxs)(ls,{ref:c,style:{transform:LN.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(Dlt,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(YCe,{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)(IM,{className:"size-4","aria-hidden":"true"})}):(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:n?(0,t.jsx)(gs,{className:"size-4 text-foreground"}):null})]})}r(Llt,"SortableCompanyItem");function $lt(e={}){return(0,t.jsx)(yje,{...e,children:(0,t.jsx)(Olt,{...e})})}r($lt,"SidebarCompanyMenu");function Olt({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}=Yo(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=qa(),j=b&&!v,N=na(),w=Mn(),k=e??n,S=s??a,C=BN(Mf(m7,{activationConstraint:{distance:8}}),Mf(Wfe,{activationConstraint:{delay:180,tolerance:6}})),I=(0,m.useMemo)(()=>l.filter(ne=>ne.status!=="archived"),[l]),{data:R}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),T=R?.user?.id??R?.session?.userId??null,{orderedCompanies:A,persistOrder:D}=vje({companies:I,userId:T}),{hidden:M,loaded:B}=cu(),E=B&&!dg(M,"company.members")&&!dg(M,"company.invites"),z="company",$=c?.name??null,q=!!$c(),U=eS({onSignedOut:K});function O(ne){ne||o(!1),S(ne)}r(O,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function H(ne){const fe=N.pathname.split("/")[1]?.toUpperCase(),X=I.some(oe=>oe.issuePrefix.toUpperCase()===fe),re=ne.id!==c?.id&&(N.pathname.startsWith("/instance/")||X);d(ne.id),S(!1),f&&x(!1),re&&w(`/${ne.issuePrefix}/dashboard`)}r(H,"selectCompany");function Z(){q||(S(!1),f&&x(!1),p({initialStep:1}))}r(Z,"addCompany");const se=(0,m.useCallback)(ne=>{const{active:fe,over:X}=ne;if(!X||fe.id===X.id)return;const re=A.map(Y=>Y.id),oe=re.indexOf(fe.id),G=re.indexOf(X.id);oe===-1||G===-1||D(gM(re,oe,G))},[A,D]);return(0,t.jsxs)(Zr,{open:k,onOpenChange:O,children:[(0,t.jsx)(Xr,{asChild:!0,children:(0,t.jsxs)(L,{variant:"ghost",className:"h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-accent/50 hover:text-foreground has-[>svg]:px-4 dark:hover:bg-accent/50","aria-label":$?`Open ${$} ${z} switcher`:`Open ${z} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(YCe,{company:c}):null,(0,t.jsx)("span",{className:W("min-w-0 truncate text-sm font-bold text-foreground",j&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),title:$??void 0,children:$??`Select ${z}`})]}),!j&&(0,t.jsx)(jM,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(ea,{align:"start",sideOffset:8,className:"ml-2 w-(--organization-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"flex h-(--organization-popover-header-height) items-center justify-between gap-2 px-3.5",children:[(0,t.jsx)(pb,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(ne=>{ne.preventDefault(),ne.stopPropagation(),o(fe=>!fe)},"onClick"),className:"rounded px-1.5 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:i?"Done":"Edit"})]}),(0,t.jsxs)("div",{className:"flex max-h-96 flex-col gap-0.5 overflow-y-auto px-2.5 pb-2 pt-1",children:[(0,t.jsx)(FN,{sensors:C,collisionDetection:MI,onDragEnd:se,children:(0,t.jsx)(zN,{items:A.map(ne=>ne.id),strategy:$I,children:A.map(ne=>(0,t.jsx)(Llt,{company:ne,isEditing:i,isSelected:ne.id===c?.id,onSelect:H},ne.id))})}),A.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ls,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(ls,{onSelect:r(ne=>{ne.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(_i,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(ls,{disabled:!0,children:"No companies"}):null]}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[!q&&(0,t.jsxs)(ls,{onClick:Z,className:rO,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(yn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),E?(0,t.jsx)(ls,{asChild:!0,disabled:i,className:rO,children:(0,t.jsxs)(Ke,{to:"/company/settings/invites",onClick:r(ne=>{if(i){ne.preventDefault();return}K()},"onClick"),children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Gf,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:$?`Invite people to ${$}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(ls,{className:rO,onClick:r(()=>U.mutate(),"onClick"),disabled:i||U.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Tp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:U.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(Olt,"BuiltinCompanyMenu");function Mse(){const{openNewIssue:e}=Yo(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=ps(),{collapsed:c,peeking:d}=qa(),u=c&&!d,h=BM(o),{data:p,isFetched:f}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}),x=P.liveRuns(o),b=No({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:j}=ee({queryKey:x,queryFn:r(()=>Jr.liveRunsForCompany(o),"queryFn"),enabled:b.enabled,refetchInterval:b.refetchInterval});So(b,v,j);const N=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,k=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,I=!f,R=p?.enableGoalsSidebarLink===!0,T=p?.enableDecisions===!0,{data:A}=ee({queryKey:P.attention(o),queryFn:r(()=>JN.list(o),"queryFn"),enabled:!!o&&T,refetchInterval:6e4}),D=Qye(A),M=p?.enableCases===!0,B=!0,E=p?.enableConferenceRoomChat===!0,z={companyId:o,companyPrefix:l?.issuePrefix??null};return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex items-center gap-1 px-3 h-12 shrink-0",children:(0,t.jsx)($lt,{})}),(0,t.jsxs)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 pointer-coarse:gap-3 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(()=>{const $=(0,t.jsxs)("button",{onClick:r(()=>e(),"onClick"),"data-slot":"icon-button","aria-label":u?"New Task":void 0,className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:bg-accent/50 hover:text-foreground transition-colors",children:[(0,t.jsx)(f_,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?By:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:$}),(0,t.jsx)(Un,{side:"right",children:"New Task"})]}):$})(),(0,t.jsx)(si,{to:"/search",label:"Search",icon:oa}),(0,t.jsx)(si,{to:"/dashboard",label:"Dashboard",icon:eg,liveCount:N}),(0,t.jsx)(si,{to:"/inbox",label:"Inbox",icon:hd,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),T?(0,t.jsx)(si,{to:"/decisions",label:"Decisions",icon:Hy,badge:D,badgeLabel:"decisions"}):null,C?(0,t.jsx)(si,{to:"/status",label:"Status",icon:QN,textBadge:"beta"}):null,E?(0,t.jsx)(si,{to:"/board-chat",label:"Conference Room",icon:pbe}):null]}),(0,t.jsxs)(tg,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(si,{to:"/issues",label:"Tasks",icon:Mu}),M?(0,t.jsx)(si,{to:"/cases",label:"Cases",icon:zl,textBadge:"beta"}):null,(0,t.jsx)(si,{to:"/routines",label:"Routines",icon:Ou}),S?(0,t.jsx)(si,{to:"/pipelines",label:"Pipelines",icon:io}):null,R?(0,t.jsx)(si,{to:"/goals",label:"Goals",icon:vp}):I?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(si,{to:"/artifacts",label:"Artifacts",icon:Th}),(0,t.jsx)(si,{to:"/skills",label:"Skills",icon:xc}),w?(0,t.jsx)(si,{to:"/workspaces",label:"Workspaces",icon:io}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(si,{to:"/projects",label:"Projects",icon:Go}),(0,t.jsx)(Elt,{})]}),(0,t.jsx)(Sp,{slotTypes:["sidebar"],context:z,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(ZN,{placementZones:["sidebar"],context:z,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(Tlt,{streamlined:B}),(0,t.jsxs)(tg,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(si,{to:"/org",label:"Org",icon:hy}),k?(0,t.jsx)(si,{to:"/apps",label:"Connectors",icon:H3}):null,(0,t.jsx)(si,{to:"/timeline",label:"Timeline",icon:b0}),(0,t.jsx)(si,{to:"/costs",label:"Costs",icon:mp}),(0,t.jsx)(si,{to:"/activity",label:"Activity",icon:Zl}),(0,t.jsx)(si,{to:"/company/settings",label:"Settings",icon:iu})]}),(0,t.jsx)(Sp,{slotTypes:["sidebarPanel"],context:z,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(Mse,"Sidebar");function Flt(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Flt,"isSandboxProviderOnly");function Blt(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),{hidden:i}=cu(),o=r(f=>!i.has(f),"showPage"),l=o("instance.plugins"),c=!!$c(),{slots:d}=gd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:u}=ee({queryKey:s?P.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await p9.get(s)}catch(f){if(f instanceof dn&&(f.status===401||f.status===403))return null;throw f}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:h}=ee({queryKey:P.plugins.all,queryFn:r(()=>Al.list(),"queryFn"),enabled:l}),p=(h??[]).filter(f=>!Flt(f));return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:(0,t.jsxs)(Ke,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Uu,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:e?.name??"Company"})]})}),(0,t.jsx)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2",children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(si,{to:"/company/settings",label:"General",icon:Ku,end:!0}),o("instance.profile")&&(0,t.jsx)(si,{to:"/company/settings/instance/profile",label:"Profile",icon:EM,end:!0}),o("company.members")&&(0,t.jsx)(si,{to:"/company/settings/members",label:"Members",icon:Ho,badge:u?.joinRequests??0,end:!0}),d.filter(f=>f.routePath).map(f=>(0,t.jsx)(si,{to:`/company/settings/${f.routePath}`,label:f.displayName,icon:Zx,end:!0},`${f.pluginKey}:${f.id}`)),o("company.invites")&&(0,t.jsx)(si,{to:"/company/settings/invites",label:"Invites",icon:Nqe,end:!0}),o("company.secrets")&&(0,t.jsx)(si,{to:"/company/settings/secrets",label:"Secrets",icon:Si,end:!0}),o("instance.environments")&&(0,t.jsx)(si,{to:"/company/settings/instance/environments",label:"Environments",icon:vbe,end:!0}),o("instance.access")&&(0,t.jsx)(si,{to:"/company/settings/instance/access",label:"Access",icon:EI,end:!0}),o("instance.heartbeats")&&(0,t.jsx)(si,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:au,end:!0}),o("company.export")&&(0,t.jsx)(si,{to:"/company/export",label:"Export",icon:po}),!c&&o("company.import")&&(0,t.jsx)(si,{to:"/company/import",label:"Import",icon:py,end:!0}),o("instance.experimental")&&(0,t.jsx)(si,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Dm}),l&&(0,t.jsx)(si,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Zx}),l&&p.length>0?(0,t.jsx)("div",{className:"ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3",children:p.map(f=>(0,t.jsx)(hb,{to:`${ep}/plugins/${f.id}`,state:Qf,className:r(({isActive:x})=>["rounded-md px-2 py-1.5 text-xs transition-colors",x?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),"className"),children:f.manifestJson.displayName??f.packageName},f.id))}):null,o("instance.adapters")&&(0,t.jsx)(si,{to:"/company/settings/instance/adapters",label:"Adapters",icon:ym})]})})]})}r(Blt,"CompanySettingsSidebar");function zlt(){const{pathname:e}=na(),{selectedCompany:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=Aje(),{enabled:o}=zM(),l=v9.filter(d=>!Ije(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(J7,{});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|reviews|conversations|activity|approvals|audit))?\/?$/);return c?(0,t.jsx)(_je,{endpointId:c[1],NavItem:si}):(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:[(0,t.jsxs)(Ke,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Uu,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:s?.name??"Company"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1",children:[(0,t.jsx)(uX,{className:"h-4 w-4 text-muted-foreground shrink-0"}),(0,t.jsx)("span",{className:"flex-1 truncate text-sm font-bold text-foreground",children:"Connectors"})]})]}),(0,t.jsxs)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2",children:[(0,t.jsx)("div",{className:"px-3 pb-1 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:"Connectors"}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(si,{to:"/apps",label:"Browse",icon:x_,end:!0}),(0,t.jsx)(si,{to:"/apps/review",label:"Review",icon:YN,badge:i>0?i:void 0,badgeTone:"warning",badgeLabel:"waiting for your OK"})]}),(0,t.jsx)("div",{className:"px-3 pb-1 pt-4 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:"Developer"}),(0,t.jsx)("p",{className:"px-3 pb-1.5 text-(length:--text-micro) leading-snug text-muted-foreground/70",children:"Advanced setup for developers. Most teams never open this."}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(si,{to:"/apps/connections",label:"Connections",icon:uX,end:!0}),l.map(d=>(0,t.jsx)(si,{to:F0(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(zlt,"AppsSidebar");function Dse(e){const{selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=ee({queryKey:P.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>Zt.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=ee({queryKey:P.tools.applications(s??"__none__"),queryFn:r(()=>Zt.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=ee({queryKey:P.tools.connections(s??"__none__"),queryFn:r(()=>Zt.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=ee({queryKey:P.apps.gallery(s??"__none__"),queryFn:r(()=>Zt.listGallery(s),"queryFn"),enabled:!!s}),d=ee({queryKey:P.apps.attention(s??"__none__"),queryFn:r(()=>Zt.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(N=>N.id===e.applicationId):null,p=Klt(e.kind==="application"?(l.data?.connections??[]).filter(N=>N.applicationId===e.applicationId):[]),f=u?$f(u):h?.name??"App",x=Ult(c.data?.apps??[],u,h??void 0),b=u?.id??p?.id??null,v=b?d.data?.apps.find(N=>N.connection.id===b):null,j=(v?.pendingActionRequestCount??0)+((v?.quarantinedCatalogEntryCount??0)>0?1:0);return(0,t.jsxs)("aside",{className:"flex h-full min-h-0 w-full flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 px-3 py-3",children:[(0,t.jsxs)(Ke,{to:"/apps/connections",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Uu,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:"All apps"})]}),(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 px-2 py-1",children:[(0,t.jsx)(al,{name:f,logoUrl:sA(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:qM.map(N=>(0,t.jsx)(si,{to:qlt(e,N.key),label:N.label,icon:N.icon,end:!0,badge:N.key==="review"&&j>0?j:void 0,badgeTone:"danger",badgeLabel:"needing review"},N.key))})})]})}r(Dse,"AppDetailSidebar");function qlt(e,s){return e.kind==="connection"?vm(e.connectionId,s):C1(e.applicationId,s)}r(qlt,"tabHref");function Ult(e,s,n){if(n?.applicationKey){const i=e.find(o=>mc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>sg(i).toLowerCase()===a)??e.find(i=>mc(i)===a)??null:null}r(Ult,"galleryEntryFor$1");function Klt(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(Klt,"latestArchivedConnection$1");function aO({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(aO,"CrumbIdentifier");function Wlt({context:e}){const{slots:s}=gd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=x9({placementZones:["globalToolbarButton"],companyId:e.companyId,enabled:!!e.companyId});return(0,t.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-1 pl-2 empty:hidden",children:[s.length>0?(0,t.jsx)(Sp,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)(ZN,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(Wlt,"GlobalToolbar");function Vlt(){const{breadcrumbs:e,mobileToolbar:s}=Bn(),{toggleSidebar:n,isMobile:a}=qa(),{selectedCompanyId:i,selectedCompany:o}=ps(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(Wlt,{context:l});if(a&&s)return(0,t.jsx)("div",{className:"border-b border-border px-2 h-12 shrink-0 flex items-center",children:s});if(e.length===0)return(0,t.jsx)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:c});const d=a&&(0,t.jsx)(L,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(abe,{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)(aO,{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)(y9,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(j9,{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)(r5,{}),(0,t.jsx)(_1,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(k_,{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)(aO,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(k_,{className:"truncate",children:u.label}):(0,t.jsx)(n5,{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)(aO,{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(Vlt,"BreadcrumbBar");var eT=240,k6=208,N6=420,Lse=16;function U5(e){return Math.min(N6,Math.max(k6,e))}r(U5,"clampSidebarWidth");function $se(e){if(typeof window>"u")return eT;try{const s=window.localStorage.getItem(e);if(!s)return eT;const n=Number.parseInt(s,10);return Number.isFinite(n)?U5(n):eT}catch{return eT}}r($se,"readStoredSidebarWidth");function Ose(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(U5(s)))}catch{}}r(Ose,"writeStoredSidebarWidth");function Hlt({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)(()=>$se(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=$se(o);v.current=E,f(E)},[o]);const N=s?p:0,w=s?n?64:N:0,k=s?n&&!a?64:N:0,S=k>w,C=i&&s&&!n,I=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),T=(0,m.useCallback)(E=>{const z=U5(E);v.current=z,f(z),Ose(o,z)},[o]),A=(0,m.useCallback)(E=>{C&&(E.preventDefault(),E.currentTarget.setPointerCapture(E.pointerId),j.current={startX:E.clientX,startWidth:v.current},b(!0))},[C]),D=(0,m.useCallback)(E=>{if(!j.current)return;const z=U5(j.current.startWidth+E.clientX-j.current.startX);v.current=z,f(z)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),Ose(o,v.current))},[o]),B=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),T(p-Lse)):E.key==="ArrowRight"?(E.preventDefault(),T(p+Lse)):E.key==="Home"?(E.preventDefault(),T(k6)):E.key==="End"&&(E.preventDefault(),T(N6)))},[C,T,p]);return(0,t.jsx)("div",{className:W("relative h-full shrink-0",l),style:I,children:(0,t.jsxs)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:[e,C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":k6,"aria-valuemax":N6,"aria-valuenow":p,tabIndex:0,className:W("absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none","before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors","hover:before:bg-border focus-visible:before:bg-ring",x&&"before:bg-ring"),onPointerDown:A,onPointerMove:D,onPointerUp:M,onPointerCancel:M,onLostPointerCapture:M,onKeyDown:B}):null]})})}r(Hlt,"SidebarShell");function Glt({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)(Nlt,{children:e})})}r(Glt,"SecondarySidebar");var Qlt="/company/settings/members?tab=invites",Ylt="https://docs.paperclip.ing/",Jlt="https://paperclip.ing/feedback";function Xlt(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(Xlt,"deriveInitials$1");function Fse({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(Fse,"MenuAction");function Bse({deploymentMode:e,open:s,onOpenChange:n}){const i=!!$c(),{hidden:o,loaded:l}=cu(),c=RCe(),d=ECe(!i),u=i?c:d?Qlt:null,h=l&&u!==null&&!dg(o,"company.members")&&!dg(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:b,collapsed:v,peeking:j}=qa(),N=v&&!j,w=s??p,k=PCe(w),S=n??f,{data:C}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),I=eS({onSignedOut:M}),R=C?.user.name?.trim()||"Board",T=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),A=Xlt(R),D=MCe(C?.user);function M(){S(!1),x&&b(!1)}r(M,"closeNavigationChrome");function B(){I.mutate()}return r(B,"handleSignOut"),(0,t.jsx)("div",{className:"border-t border-r border-border bg-background px-3 py-2",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!N&&"px-2"),children:[(0,t.jsxs)(br,{open:w,onOpenChange:S,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",N?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(Mo,{size:"sm",children:[C?.user.image?(0,t.jsx)(xd,{src:C.user.image,alt:R}):null,(0,t.jsx)(Do,{children:A})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",N&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:R})]})}),(0,t.jsxs)(dr,{side:"top",align:"start",sideOffset:10,className:"w-(--sz-277px) max-w-(--sz-calc-24) overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl",children:[(0,t.jsx)("div",{className:"h-24 bg-(image:--gradient-extract-25)"}),(0,t.jsxs)("div",{className:"-mt-8 px-4 pb-4",children:[(0,t.jsxs)("div",{className:"relative flex items-start gap-3",children:[(0,t.jsx)(Ke,{to:D,"aria-label":"View profile",onClick:M,className:"absolute inset-0 rounded-xl transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),(0,t.jsx)("div",{className:"pointer-events-none relative rounded-2xl border-4 border-popover bg-popover p-0.5 shadow-sm",children:(0,t.jsxs)(Mo,{size:"lg",children:[C?.user.image?(0,t.jsx)(xd,{src:C.user.image,alt:R}):null,(0,t.jsx)(Do,{children:A})]})}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1 pt-1",children:[(0,t.jsx)("h2",{className:"truncate text-base font-semibold text-foreground",children:R}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:T}),k?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${k}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${k} on GitHub`,title:k,children:["SHA ",k.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-1",children:[h&&u?(0,t.jsx)(Fse,{label:"Invite",description:"Invite people to your organization.",icon:Gf,href:u,topLevel:i,onClick:M}):null,(0,t.jsx)(Fse,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:GN,href:Ylt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(yk,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)($Ce,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",I.isPending&&"cursor-not-allowed opacity-60"),onClick:B,disabled:I.isPending,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(Tp,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:I.isPending?"Signing out...":"Sign out"}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:"End this browser session."})]})]}):null,(0,t.jsx)(OCe,{})]})]})]})]}),!N&&!i?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("a",{href:Jlt,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)(_g,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Un,{side:"top",children:"Share feedback"})]}):null]})})}r(Bse,"SidebarAccountMenu");function Zlt(e,s){return JCe(e,s)[0]?.toLowerCase()??null}r(Zlt,"getCompanyRouteSegment");function JCe(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r(JCe,"getCompanyPathSegments");var ect=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function tct(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(tct,"isSkillsStoreRoute");function sct(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=qa(),{openNewIssue:d,openOnboarding:u}=Yo(),{togglePanelVisible:h}=Jf(),p=Xc()?.pushToast??null,{companies:f,loading:x,selectedCompany:b,selectedCompanyId:v,selectionSource:j,setSelectedCompanyId:N}=ps(),{companyPrefix:w,pluginRoutePath:k}=va(),S=Mn(),C=na(),I=hM(),R=kje(C.pathname,w).isTaskDetail,T=["/company/settings","/company/export","/company/import"].some(vt=>C.pathname.includes(vt)),A=JCe(C.pathname,w),D=A[0]?.toLowerCase()==="tools",M=A[0]?.toLowerCase()==="apps",B=M&&A[1]&&!ect.has(A[1].toLowerCase())?A[1]:null,E=M&&A[1]?.toLowerCase()==="app"&&A[2]?A[2]:null,z=tct(C.pathname,w),$=(0,m.useRef)(!1),q=(0,m.useRef)(null),U=(0,m.useRef)(null),O=(0,m.useRef)(new hye),K=(0,m.useRef)(C.key),H=KCe(l&&!R,C.pathname),[Z,se]=(0,m.useState)(!1),ne=(0,m.useMemo)(()=>{if(!w)return null;const vt=w.toUpperCase();return f.find(Le=>Le.issuePrefix.toUpperCase()===vt)??null},[f,w]),fe=!!w&&!x&&f.length>0&&!ne,X=(0,m.useMemo)(()=>k?.toLowerCase()??Zlt(C.pathname,w),[w,C.pathname,k]),re=ne?.id??null,oe=ne?.issuePrefix??null,{slots:G}=gd({slotTypes:["page","routeSidebar"],companyId:re,enabled:!!(re&&X)}),Y=(0,m.useMemo)(()=>l9(G,X),[X,G]),Q=(0,m.useMemo)(()=>({companyId:re,companyPrefix:oe}),[re,oe]),te=T?(0,t.jsx)(Blt,{}):B?(0,t.jsx)(Dse,{kind:"connection",connectionId:B}):E?(0,t.jsx)(Dse,{kind:"application",applicationId:E}):M||D?(0,t.jsx)(zlt,{}):Y?(0,t.jsx)(Wu,{slot:Y,context:Q,className:"h-full w-full",missingBehavior:"placeholder"}):null,ae=te!=null,{data:le}=ee({queryKey:P.health,queryFn:r(()=>du.get(),"queryFn"),retry:!1,refetchInterval:r(vt=>vt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),he=ae||z;(0,m.useLayoutEffect)(()=>(c(he),()=>c(!1)),[he,c]),(0,m.useEffect)(()=>{x||$.current||le?.deploymentMode!=="authenticated"&&(le?.cloud||f.length===0&&($.current=!0,u()))},[f,x,u,le?.cloud,le?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!ne){const Le=(v?f.find(Qe=>Qe.id===v):null)??f[0]??null;Le&&v!==Le.id&&N(Le.id,{source:"route_sync"});return}if(w!==ne.issuePrefix){const Le=C.pathname.replace(/^\/[^/]+/,"");S(`/${ne.issuePrefix}${Le}${C.search}`,{replace:!0});return}const vt=WCe({matchedCompany:ne,selectedCompanyId:v,companies:f});if(vt){p?.({title:`${ne.name} is archived`,body:`Switched to ${vt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${ne.id}`}),N(vt.id,{source:"route_sync"}),S(`/${vt.issuePrefix}/dashboard`,{replace:!0});return}VCe({selectionSource:j,selectedCompanyId:v,routeCompanyId:ne.id})&&N(ne.id,{source:"route_sync"})},[w,f,x,ne,C.pathname,C.search,S,p,j,v,N]);const ce=h,ge=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),me=(0,m.useRef)(null),ie=(0,m.useRef)(!1),ue=(0,m.useRef)(!1),ke=(0,m.useCallback)(()=>{me.current!==null&&(window.clearTimeout(me.current),me.current=null)},[]),be=(0,m.useCallback)(()=>{ke(),me.current=window.setTimeout(()=>o(!0),50)},[ke,o]),Ie=(0,m.useCallback)(()=>{ke(),o(!0)},[ke,o]),Ue=(0,m.useCallback)(()=>{ke(),me.current=window.setTimeout(()=>o(!1),120)},[ke,o]),at=(0,m.useCallback)(()=>{ie.current=!0,a&&!ue.current&&be()},[a,be]),dt=(0,m.useCallback)(()=>{ie.current=!1,ue.current=!1,Ue()},[Ue]),de=(0,m.useCallback)(()=>{ue.current||Ie()},[Ie]),Be=(0,m.useCallback)(()=>{ie.current||Ue()},[Ue]);(0,m.useEffect)(()=>ke,[ke]);const pt=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==pt.current&&(a?(ke(),o(!1),ue.current=ie.current):ue.current=!1,pt.current=a)},[a,ke,o]),(0,m.useEffect)(()=>{if(!i)return;const vt=r(Le=>{Le.key==="Escape"&&(ke(),o(!1))},"onKeyDown");return window.addEventListener("keydown",vt),()=>window.removeEventListener("keydown",vt)},[i,ke,o]),UCe(),FCe({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ge,onToggleSidebar:n,onTogglePanel:ce,onShowShortcuts:r(()=>se(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const vt=30,Le=50,Qe=75;let ut=0,Ye=0;const it=r(tt=>{const Pe=tt.touches[0];ut=Pe.clientX,Ye=Pe.clientY},"onTouchStart"),kt=r(tt=>{const Pe=tt.changedTouches[0],Ce=Pe.clientX-ut;if(!(Math.abs(Pe.clientY-Ye)>Qe)){if(!e&&ut<vt&&Ce>Le){s(!0);return}e&&Ce<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",it,{passive:!0}),document.addEventListener("touchend",kt,{passive:!0}),()=>{document.removeEventListener("touchstart",it),document.removeEventListener("touchend",kt)}},[l,e,s]),(0,m.useEffect)(()=>{const vt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=vt}},[l]),(0,m.useEffect)(()=>{if(!l)return GCe()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const vt=U.current;return HCe(vt)},[C.pathname]),(0,m.useEffect)(()=>{const vt=U.current;if(!vt)return;const Le=r(()=>{O.current.remember(K.current,vt.scrollTop)},"recordScroll");return vt.addEventListener("scroll",Le,{passive:!0}),()=>vt.removeEventListener("scroll",Le)},[]),(0,m.useLayoutEffect)(()=>{const vt=U.current,Le=mye({previousPathname:q.current,pathname:C.pathname,navigationType:I,state:C.state});q.current=C.pathname;const Qe=I==="POP",ut=Qe?O.current.recall(C.key):0;if(K.current=C.key,Qe){Q3(vt,ut);const Ye=requestAnimationFrame(()=>Q3(vt,ut));return()=>cancelAnimationFrame(Ye)}Le&&pye(vt)},[C.key,C.pathname,C.state,I]),(0,t.jsx)(uye,{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)(bCe,{}),(0,t.jsx)(vCe,{devServer:le?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",l?"w-full":"flex overflow-clip"),children:[l&&e&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>s(!1),"onClick"),"aria-label":"Close sidebar"}),l?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",e?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ae?te:(0,t.jsx)(Mse,{})})}),(0,t.jsx)(Bse,{deploymentMode:le?.deploymentMode})]}):(0,t.jsxs)(Hlt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:at,onPanelMouseLeave:dt,onPanelFocusCapture:a?de:void 0,onPanelBlurCapture:a?Be:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(Mse,{})}),(0,t.jsx)(Bse,{deploymentMode:le?.deploymentMode})]}),!l&&ae?(0,t.jsx)(Glt,{children:te}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",l?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{className:W(l&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(g6,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Vlt,{}),l&&T?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(Cje,{})}):null]}),(0,t.jsxs)("div",{className:W(l?"block":"flex flex-1 min-h-0"),children:[(0,t.jsx)("main",{id:"main-content",ref:U,tabIndex:-1,style:l?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",l?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:fe?(0,t.jsx)(zu,{scope:"invalid_company_prefix",requestedPrefix:w??b?.issuePrefix}):(0,t.jsx)(kCe,{children:(0,t.jsx)(mb,{})})}),(0,t.jsx)(Oje,{})]})]})]}),l&&(0,t.jsx)(gCe,{visible:H}),(0,t.jsx)(Fje,{}),(0,t.jsx)(vwe,{}),(0,t.jsx)(cCe,{}),(0,t.jsx)(mCe,{}),(0,t.jsx)(hCe,{}),(0,t.jsx)(pCe,{open:Z,onOpenChange:se}),(0,t.jsx)(fCe,{}),(0,t.jsx)(xCe,{localTrusted:le?.deploymentMode==="local_trusted"})]})})}r(sct,"Layout");var zse=null;function nct(){return zse??=new qN,zse}r(nct,"getDetachedClient");function rct(){const e=(0,m.useContext)(CI),{data:s,isFetched:n}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:e!=null},e??nct());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(rct,"useConferenceRoomChatEnabled");function act(){const{enabled:e,loaded:s}=rct();return s?e?(0,t.jsx)(mb,{}):(0,t.jsx)(kn,{to:"/dashboard",replace:!0}):null}r(act,"ConferenceRoomChatGate");var ict=["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"],oct={"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 }"}},rcs=ict.map(e=>oct[e]);function XCe({browser:e,label:s="Browser",onOpen:n}){const a=e.status==="closed"||e.status==="failed";return(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2 py-1 text-sm","aria-label":`${s} session`,children:[(0,t.jsx)(Ap,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{children:s}),(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.status]}),n&&(0,t.jsx)(L,{variant:"ghost",size:"sm",onClick:r(()=>n(e.id),"onClick"),children:a?"View session":"Open browser"})]})}r(XCe,"TaskBrowserActivity");function ZCe({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)(gqe,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Project created"}),(0,t.jsx)(Ke,{to:`/projects/${e.projectId}`,className:"break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description&&(0,t.jsx)("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:e.description}),e.repositories.length>0&&(0,t.jsx)("ul",{className:"space-y-1 pt-1",children:e.repositories.map(s=>(0,t.jsxs)("li",{className:"flex min-w-0 items-center gap-2 text-xs text-muted-foreground",children:[(0,t.jsx)(io,{className:"size-3 shrink-0","aria-hidden":!0}),(0,t.jsx)("a",{className:"truncate hover:underline focus-visible:underline",href:s.url,target:"_blank",rel:"noreferrer",children:s.name})]},s.id))})]})]})})}r(ZCe,"TaskChatProjectCreatedCard");function lct({item:e,onOpen:s}){return(0,t.jsx)("article",{className:"rounded-lg border border-border bg-card p-3","aria-label":`Skill created: ${e.name}`,children:(0,t.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 text-left",onClick:r(()=>s?.(e.skillId,e.name),"onClick"),children:[(0,t.jsx)(Pf,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("span",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:"Skill created"}),(0,t.jsx)("span",{className:"block break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description?(0,t.jsx)("span",{className:"block line-clamp-3 text-sm text-muted-foreground",children:e.description}):null]})]})})}r(lct,"TaskChatSkillCreatedCard");function cct(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(cct,"McpIcon");var dct=new Set(["tool","tool call","tool_call","acp_tool"]);function Gd(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||dct.has(s)}r(Gd,"isGenericToolName");function JW(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(JW,"mcpToolIdentity");function XW(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(XW,"identifierWords");function e1e(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(e1e,"sentenceCase");function jk(e){const s=(e??"").trim();return Gd(s)?"Unnamed tool":e1e(XW(JW(s)?.name??s))}r(jk,"humanizeToolName");var Nd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),uct={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:Nd("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:Nd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Nd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Nd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Nd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Nd("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:Nd("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"}},mct={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:[]},hct={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function pct(e){return XW(e).join("_")}r(pct,"normalizedKey");function fct(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(mct))if(a.includes(s))return n;return null}r(fct,"inferredAction");function xct(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(xct,"actionFamily");var gct={terminal:hg,grep:Lqe,search:oa,read:GN,edit:CM,web:aqe,plan:Hy,question:Pc,agent:hy,safety:Di,image:QI,wait:au,mcp:cct,other:Pf};function bct(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(bct,"actionCopy");function vct(e){switch(e){case"run":return Nd("command","command","commands");case"read":case"list":return Nd("read","read","reads");case"search":return Nd("search","search","searches");case"update":case"create":case"delete":case"move":return Nd("file_change","file change","file changes");case"start":case"stop":return Nd("delegation","delegation","delegations");case"wait":return Nd("wait","wait","waits");default:return Nd("tool_action","tool action","tool actions")}}r(vct,"defaultSummaryGroup");function yct(e){return e==="read"||e==="list"?Nd("paperclip_read","Paperclip read","Paperclip reads"):Nd("task_operation","task operation","task operations")}r(yct,"paperclipSummaryGroup");function wy(e){const s=(e.name??"").trim(),n=JW(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=XW(o),c=pct(o),d=uct[c],u=hct[(e.operation??"").trim().toLowerCase()],h=fct(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":Gd(o)?"unnamed":"fallback",x=Gd(o)?"Unnamed tool":jk(o),b=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&b&&l.length>1?l.slice(1):[],j=v.length?e1e(v).replace(/^./,I=>I.toLowerCase()):void 0,N=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?Gd(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:bct(p,d?void 0:j),w=d?.family??xct(p),k=i==="mcp"?"mcp":w,S=a?jk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?yct(p):d?.group??vct(p);return{icon:gct[k],family:k,runningLabel:N.running,completedLabel:N.completed,failedLabel:`${N.completed} · failed`,interruptedLabel:`${N.running} · stopped`,displayName:x,sourceLabel:S,technicalName:s||void 0,confidence:f,summaryGroup:C}}r(wy,"toolActivityPresentation");function hN(e){const s=wy({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(hN,"toolTaxonomy");function t1e(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?Xx:s==="responding"||s.startsWith("responding (")?Sqe:null}r(t1e,"statusLabelIcon");var iO=["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"],oO=["Brewing","Tinkering","Distilling","Deliberating"],qse=(()=>{const e=[],s=Math.max(iO.length,oO.length);for(let n=0;n<s;n++)n<iO.length&&e.push(iO[n]),n<oO.length&&e.push(oO[n]);return e})(),jct=1e4;function wct(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(wct,"isGenericStatusLabel");function kct(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(kct,"fnv1a");function Nct(e,s=0){const n=Math.floor(Math.max(0,s)/jct);return qse[(kct(e)+n)%qse.length]}r(Nct,"whimsyWord");var Sct=[{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}],acs=Array.from(new Set(Sct.map(e=>e.group)));function s1e(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(s1e,"parseCssTimeMs");function Cct(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(Cct,"elapsedLabel");function _ct(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(_ct,"liveElapsedLabel");function Ict(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(Ict,"useLiveElapsedMs");function Act(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(Act,"lineScrollOffset");function NE(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=s1e(s);return Number.isFinite(n)?n:0}r(NE,"motionTokenMs");function Tct({text:e,streaming:s,leaving:n}){const a=(0,m.useRef)(null),[i,o]=(0,m.useState)(0),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1);(0,m.useLayoutEffect)(()=>{const p=a.current;if(!p)return;const f=r(()=>{const b=parseFloat(window.getComputedStyle(p).lineHeight);o(Act(p.scrollHeight,b))},"measure");if(f(),typeof ResizeObserver>"u")return;const x=new ResizeObserver(f);return x.observe(p),()=>x.disconnect()},[e,s]),(0,m.useEffect)(()=>{const p=requestAnimationFrame(()=>c(!0)),f=window.setTimeout(()=>u(!0),NE("--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(Tct,"LiveSelfTalkLine");function Rct(e,s){const[n,a]=(0,m.useState)(null),i=(0,m.useRef)(n),o=(0,m.useRef)(null),l=(0,m.useRef)(e),c=(0,m.useRef)(0),d=(0,m.useRef)(null),u=(0,m.useRef)(null),h=(0,m.useRef)(null);return l.current=e,(0,m.useEffect)(()=>{const p=r(j=>{j.current!=null&&(window.clearTimeout(j.current),j.current=null)},"clear"),f=r(j=>{i.current=j,a(j)},"show"),x=r(()=>{p(u),p(h),u.current=window.setTimeout(()=>{if(u.current=null,o.current!=null)return;const j=i.current;j==null||j.streaming||(f({...j,leaving:!0}),h.current=window.setTimeout(()=>{h.current=null,i.current?.leaving&&f(null)},NE("--motion-line-scroll")))},NE("--motion-interstitial-dwell"))},"scheduleLeave"),b=r((j,N)=>{p(u),p(h),c.current=Date.now(),f({text:j,streaming:N,swapKey:(i.current?.swapKey??0)+1}),N||x()},"swapIn");if(!s){p(d),p(u),p(h),o.current=null,i.current&&f(null);return}const v=i.current;if(e==null){v?.streaming&&(f({...v,streaming:!1}),x());return}if(v==null){b(e,!0);return}if(v.streaming){v.text!==e&&f({...v,text:e});return}if(o.current=e,d.current==null){const j=NE("--motion-interstitial-dwell"),N=Math.max(0,c.current+j-Date.now());d.current=window.setTimeout(()=>{d.current=null;const w=o.current;o.current=null,w!=null&&b(w,l.current!=null)},N)}},[e,s]),(0,m.useEffect)(()=>()=>{d.current!=null&&window.clearTimeout(d.current),u.current!=null&&window.clearTimeout(u.current),h.current!=null&&window.clearTimeout(h.current)},[]),n}r(Rct,"useHeldSelfTalk");var Ect={running:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:YN,spin:!1,tone:"text-primary"},interrupted:{Icon:F7,spin:!1,tone:"text-destructive"},refused:{Icon:jm,spin:!1,tone:"text-destructive"},truncated:{Icon:Dqe,spin:!1,tone:"text-(--status-agent-paused)"}};function n1e({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=Ect[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=Ict(e.startedAtMs,d),h=Rct(d?e.selfTalk:void 0,d),p=Cct(e.elapsedMs);if(d){const f=_ct(u??e.elapsedMs),x=e.selfTalk!=null,b=e.toolName?hN(e.toolName).icon:x?null:t1e(e.label),v=x||wct(e.label)?Nct(e.id,u??e.elapsedMs??0):e.label,j=(0,t.jsxs)("div",{className:"tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground",children:[n!==void 0?(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-caret-slot",children:(0,t.jsx)(En,{className:W("h-3 w-3 transition-transform",n?"rotate-90":null),"aria-hidden":!0})}):null,(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-dot-slot",children:(0,t.jsx)("span",{"aria-hidden":!0,className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"})}),b?(0,t.jsx)(b,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}):null,(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[(0,t.jsxs)("span",{className:"shimmer-text shimmer-text-muted shrink-0 font-medium",children:[v,"…"]}),f?(0,t.jsx)("span",{className:"shrink-0 font-mono tabular-nums text-(length:--text-micro)",children:f}):null,e.detail?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro)",children:e.detail}):null,e.tokens?(0,t.jsxs)("span",{className:"ml-auto shrink-0 font-mono text-(length:--text-micro)",children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]});return(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 py-0.5 text-xs text-muted-foreground","data-testid":"task-chat-interstitial-row",children:[(0,t.jsx)("span",{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0"}),h?(0,t.jsx)(Tct,{text:h.text,streaming:h.streaming,leaving:h.leaving},h.swapKey):(0,t.jsx)("span",{"aria-hidden":!0,className:"tc-line-scroll min-w-0 flex-1"})]}),a?(0,t.jsx)("button",{type:"button",onClick:a,"aria-expanded":n,className:"-mx-1.5 block w-full rounded-sm px-1.5 text-left transition-colors hover:bg-muted/60","data-testid":"task-chat-live-turn",children:j}):j]})}return(0,t.jsxs)("div",{className:W("tc-enter-status flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm",c?"tc-approval border-primary/40 bg-primary/5":"border-border bg-muted/40"),children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(i,{className:W("h-4 w-4 shrink-0",l,o&&"animate-spin")}),(0,t.jsx)("span",{className:"min-w-0 truncate font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[p?(0,t.jsx)("span",{children:p}):null,e.tokens?(0,t.jsxs)("span",{children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]}),e.detail?(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.detail}):null,c&&e.approval?(0,t.jsx)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:e.approval.options.map(f=>{const x=f.kind.startsWith("reject");return(0,t.jsx)("button",{type:"button",onClick:r(()=>s?.(f.id),"onClick"),className:W("rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",x?"border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground":"border-primary bg-primary text-primary-foreground hover:bg-primary/90"),children:f.label},f.id)})}):null]})}r(n1e,"TaskChatStatusPill");var Eg=(0,m.createContext)(null);function tj(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${Math.round(e)} B`;const s=["KB","MB","GB","TB"];let n=e/1024,a=0;for(;n>=1024&&a<s.length-1;)n/=1024,a+=1;const i=n.toFixed(1);return`${i.endsWith(".0")?i.slice(0,-2):i} ${s[a]}`}r(tj,"formatBytes$4");var K5=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),Pct=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],Mct=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],Dct=new Set(["application/wasm"]),Lct=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),r1e=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),$ct=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"]),Oct=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function fA(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(fA,"normalizeOutputContentType");function Fct(e){const s=(e??"").trim().toLowerCase();return s?Oct.some(n=>s.endsWith(n)):!1}r(Fct,"hasDocumentLikeFilename");function a1e(e){return Lct.has(e)||e.endsWith("+zip")}r(a1e,"isZipContentType");function Bct(e){return e?!!(e.startsWith("text/")||r1e.has(e)||$ct.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Bct,"isDocumentLikeOutputContentType");function zct(e,s){const n=fA(e);return!n||Bct(n)||K5.has(n)&&Fct(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||Dct.has(n)||a1e(n)||K5.has(n)}r(zct,"isOutputEligibleContentType");function qct(e){const s=fA(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"}:a1e(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:r1e.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(qct,"getOutputFileGlyph");function Vu(e,s){const n=fA(e);if(n.startsWith("video/"))return!0;if(!K5.has(n))return!1;const a=(s??"").trim().toLowerCase();return Pct.some(i=>a.endsWith(i))}r(Vu,"isVideoLikeOutput");function ky(e){const s=fA(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(ky,"isImageContentType");function f4(e,s){const n=fA(e);if(ky(n))return!0;if(n&&!K5.has(n))return!1;const a=(s??"").trim().toLowerCase();return Mct.some(i=>a.endsWith(i))}r(f4,"isImageLikeOutput");function Use(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(Use,"toTime");function x4(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=y$e.safeParse(n.metadata);return a.success&&!zct(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:Use(a.createdAt)-Use(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(x4,"getIssueOutputs");function ZW(e){return e.metadata?.originalFilename||e.title||"output"}r(ZW,"outputFilename");function i1e(e){return new Set(x4(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(i1e,"getPromotedOutputAttachmentIds");function Uct(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(Uct,"normalizedContentType");function vg(e){return e.originalFilename??e.id}r(vg,"attachmentFilename");function g4(e){return e.openPath??e.contentPath}r(g4,"attachmentOpenPath");function lS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(lS,"attachmentDownloadPath");function o1e(e){const s=Uct(e);return f4(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(o1e,"isImageAttachment$1");function l1e(e){return Vu(e.contentType,e.originalFilename)}r(l1e,"isVideoAttachment");function c1e(e){return nfe(e)}r(c1e,"isMarkdownAttachment");function sj(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return nfe(e)||s.startsWith("text/")||/^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(s)||["","application/octet-stream"].includes(s)&&/\.(txt|log|csv|json|yaml|yml|toml|ini|sh|ts|tsx|js|jsx|py|css|html)$/i.test(e.originalFilename??"")}r(sj,"isTextAttachment");function d1e(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(d1e,"downloadBlob$1");function Kct(e,s,n){d1e(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(Kct,"downloadTextFile");var lO="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 u1e({issueId:e,documentKey:s,title:n,format:a,body:i,className:o}){const[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(null),{copy:f,copied:x,failed:b}=Cp(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const j=(0,m.useCallback)(async(I,R)=>{c(I),p(null);try{await R(),u(I)}catch(T){u(null),p(T instanceof Error?T.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),N=(0,m.useCallback)(async()=>i??(await St.getDocument(e,s)).body,[i,s,e]),w=(0,m.useCallback)(()=>{c("copy"),p(null),(async()=>{try{await f(await N())==="failed"&&p("Copy failed")}catch(I){p(I instanceof Error?I.message:"Copy failed")}finally{c(null)}})()},[f,N]),k=b||h==="Copy failed"?"Copy failed":x?"Copied!":"Copy full content",S=d==="download"?"Downloaded!":"Download source",C=d==="pdf"?"Downloaded!":"Export to PDF";return(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:lO,disabled:l!==null,"aria-label":"Copy full content",title:k,"data-testid":"document-export-copy",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(gs,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(Ir,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:lO,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),j("download",async()=>{const R=OBe(a);Kct(iX(n,R),await N(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(po,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:lO,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),j("pdf",async()=>{d1e(iX(n,"pdf"),await St.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(fqe,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("span",{className:"sr-only",role:"status","aria-live":"polite",children:h??(x?"Copied!":b?"Copy failed":d?"Downloaded!":"")})]})}r(u1e,"DocumentExportActions");function K_({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(K_,"PreviewFrame");function W5({label:e}){return(0,t.jsx)(K_,{className:"flex items-center justify-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-1.5 text-muted-foreground/50",children:[(0,t.jsx)(Dc,{className:"h-7 w-7","aria-hidden":"true"}),e?(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide",children:e}):null]})})}r(W5,"PlaceholderPreview");function Wct({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(W5,{label:"Image"}):(0,t.jsx)(K_,{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(Wct,"ImagePreview");function Vct({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)(K_,{className:"flex items-center justify-center bg-black/80",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-white/15",children:(0,t.jsx)(oo,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})});const c=r(()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null),i(!0)},"markFrameReady"),d=r(()=>{l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(c,3e3)},"scheduleFrameReadyFallback"),u=r(p=>{if(o.current)return;o.current=!0;const f=p.currentTarget,x=Number.isFinite(f.duration)&&f.duration>0?f.duration:0,b=x>0?Math.min(1,x/4):.05;try{Math.abs(f.currentTime-b)>.001?(f.currentTime=b,d()):c()}catch{c()}},"loadThumbnailFrame"),h=r(p=>{(o.current||p.currentTarget.currentTime>0)&&c()},"handleLoadedData");return(0,t.jsxs)(K_,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:W("h-full w-full object-contain transition-opacity",a?"opacity-100":"opacity-0"),onLoadedMetadata:u,onLoadedData:h,onSeeked:c,onError:r(()=>n(!0),"onError")}),(0,t.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-black/55",children:(0,t.jsx)(oo,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(Vct,"VideoPreview");function Hct({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(K_,{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)(W5,{label:e.source==="document"?"Document":"Text"})}r(Hct,"TextPreview");function xA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(Wct,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(Vct,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(Hct,{artifact:e});case"file":return(0,t.jsx)(W5,{label:"File"});default:return(0,t.jsx)(W5,{})}}r(xA,"ArtifactPreview");function Kse({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(Kse,"SecondaryAction");function Gct({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)(xA,{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)(u1e,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Kse,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)(Vn,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Kse,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(po,{className:"h-3.5 w-3.5"})}):null]})]}),(0,t.jsxs)("div",{className:"mt-0.5 flex items-center gap-1.5 text-(length:--text-micro) text-muted-foreground/65",children:[(0,t.jsxs)("span",{children:["Last edited ",Id(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(Gct,"ArtifactCard");var Ql={credentials:r(e=>Te.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>Te.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>Te.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>Te.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>Te.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>Te.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>Te.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>Te.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>Te.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>Te.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>Te.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>Te.post(`/companies/${e}/email/send`,s),"send")};function m1e(e,s){return ee({queryKey:["email-thread",e,s],queryFn:r(()=>Ql.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(m1e,"useEmailThread");var h1e=(0,m.createContext)(null);function Qct({companyId:e,issueId:s,children:n}){const a=m1e(e,s);return(0,t.jsx)(h1e.Provider,{value:a.data??null,children:n})}r(Qct,"EmailThreadProvider");function p1e(e){const s=(0,m.useContext)(h1e),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(f1e,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(p1e,"useEmailComment");function f1e({message:e,publication:s,issueId:n}){const a=ee({queryKey:["email-attachments",n],queryFn:r(()=>St.listAttachments(n),"queryFn"),enabled:e.attachmentIds.length>0});return(0,t.jsxs)("article",{"aria-label":e.direction==="inbound"?"Email received":"Email sent",className:"space-y-4 rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"flex items-center gap-2 text-sm font-semibold",children:[(0,t.jsx)(c7,{className:"size-4"}),e.direction==="inbound"?"Email received":"Email sent"]}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:new Date(e.timestamp).toLocaleString()})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("p",{className:"text-sm font-medium",children:[e.from,e.direction==="inbound"&&(0,t.jsx)("span",{className:"ml-2 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground",children:"External"})]}),(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["To: ",e.to.join(", ")]}),!!e.cc?.length&&(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["Cc: ",e.cc.join(", ")]}),(0,t.jsx)("p",{className:"text-sm font-semibold",children:e.subject})]}),(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words text-sm",children:e.text||"(No text body)"}),!!e.attachmentIds.length&&(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.attachmentIds.map(i=>{const o=a.data?.find(l=>l.id===i);return(0,t.jsxs)("a",{href:`/api/attachments/${i}/content`,target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[(0,t.jsx)(Dc,{className:"size-3.5"}),o?.originalFilename??"Open attachment"]},i)})}),(0,t.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,t.jsx)("summary",{className:"cursor-pointer",children:"Email details"}),(0,t.jsxs)("div",{className:"space-y-2 pt-3",children:[!!e.bcc?.length&&(0,t.jsxs)("p",{children:["Bcc: ",e.bcc.join(", ")]}),(0,t.jsxs)("p",{className:"break-all",children:["Message ID: ",e.providerMessageId]}),e.fullText!==e.text&&(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words",children:e.fullText})]})]}),s&&(0,t.jsxs)("p",{className:"border-t border-border pt-3 text-xs text-muted-foreground",children:[s.outcome==="delivered"?"Delivered":s.outcome==="failed"?"Delivery failed":s.outcome==="uncertain"?"Delivery uncertain":s.outcome==="queued"?"Queued":"Sent",s.error?` · ${s.error}`:""]}),a.error&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Attachments could not be loaded."})]})}r(f1e,"EmailMessageCard");var Xv=(0,m.createContext)(null);function nj({items:e,initialIndex:s,open:n,onOpenChange:a}){const[i,o]=(0,m.useState)(s),l=(0,m.useRef)(null),c=(0,m.useCallback)(b=>{l.current=b},[]);(0,m.useEffect)(()=>{n&&o(s)},[n,s]);const d=(0,m.useCallback)(()=>{o(b=>(b+1)%e.length)},[e.length]),u=(0,m.useCallback)(()=>{o(b=>(b-1+e.length)%e.length)},[e.length]);(0,m.useEffect)(()=>{i<e.length||o(0)},[i,e.length]),(0,m.useEffect)(()=>{if(!n)return;const b=r(v=>{v.key==="ArrowRight"?d():v.key==="ArrowLeft"?u():v.key==="Escape"&&a(!1)},"handler");return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[n,d,u,a]);const h=(0,m.useCallback)(b=>{const v=b.target;v.closest("button")||v.closest("a")||v===l.current||a(!1)},[a]);if(e.length===0)return null;const p=e[i];if(!p)return null;const f=vg(p),x=Vu(p.contentType,p.originalFilename);return(0,t.jsx)(LFe,{open:n,onOpenChange:a,children:(0,t.jsxs)(MFe,{children:[(0,t.jsx)(DFe,{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)(BFe,{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(b=>b.stopPropagation(),"onClick"),children:(0,t.jsx)(po,{className:"h-4.5 w-4.5"})}),(0,t.jsx)("button",{type:"button",onClick:r(()=>a(!1),"onClick"),className:"text-white/50 hover:text-white transition-colors",title:"Close",children:(0,t.jsx)(Fn,{className:"h-5 w-5"})})]})]}),(0,t.jsxs)("div",{className:"flex-1 flex items-center min-h-0",children:[(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:u,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Previous",children:(0,t.jsx)(Uu,{className:"h-7 w-7"})})}),(0,t.jsx)("div",{className:"flex-1 flex items-center justify-center min-w-0 min-h-0 h-full px-2",children:x?(0,t.jsx)("video",{ref:c,src:p.contentPath,className:"max-w-full max-h-full rounded-lg",controls:!0,playsInline:!0}):(0,t.jsx)("img",{ref:c,src:p.contentPath,alt:f,className:"max-w-full max-h-full object-contain select-none rounded-lg",draggable:!1})}),(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:d,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Next",children:(0,t.jsx)(En,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(nj,"ImageGalleryModal");var eV=(0,m.createContext)(null);function Yct({value:e,children:s}){return(0,t.jsx)(eV.Provider,{value:e,children:s})}r(Yct,"DispositionRecoveryProvider");function Jct(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(Jct,"readDispositionRecoverySnapshot");function x1e(e){return Jct(e,(0,m.useContext)(eV)?.issue.activeRecoveryAction)}r(x1e,"useDispositionRecoverySnapshot");function Xct(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(Xct,"dispositionRetryUnavailableReason");function Zct(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(Zct,"descriptionFor");function tV({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(eV),[i,o]=(0,m.useState)(n),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(null),f=(0,m.useRef)(!1),x=(0,m.useId)(),b=(0,m.useId)(),v=(0,m.useId)(),j=Xct(e,a),N=!!(a&&a.issue.activeRecoveryAction?.id!==e.actionId),w=e.assigneeAgentId&&a?.agentMap?.get(e.assigneeAgentId)?.name||"the assigned agent",k=d||N?gs:Es;async function S(){if(!(!a||j||f.current)){f.current=!0,c(!0),p(null);try{await a.onRetry(e.actionId),u(!0)}catch(C){p(C instanceof Error?C.message:"Refresh the task to check its current state, then try again.")}finally{f.current=!1,c(!1)}}}return r(S,"retry"),(0,t.jsxs)("section",{"aria-labelledby":b,className:"flex min-w-0 gap-2.5 py-3","data-testid":"disposition-recovery-notice",children:[(0,t.jsx)(k,{"aria-hidden":"true",className:W("mt-0.5 size-4 shrink-0",d||N?"text-muted-foreground":"text-(--status-task-icon-todo)")}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:b,className:"break-words text-sm font-medium text-foreground",children:d?"Retry requested":N?"Agent needed attention":"Agent needs attention"}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:d?`The task was returned to To do for ${w}.`:Zct(e)})]}),j&&!d?(0,t.jsxs)("p",{id:v,className:"text-xs leading-relaxed text-muted-foreground",children:[!N&&(0,t.jsx)("span",{className:"font-medium text-foreground",children:"Retry unavailable. "}),j]}):null,h?(0,t.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:["Couldn’t confirm the retry. ",h]}):null,(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[!d&&!N?(0,t.jsxs)(L,{size:"xs",variant:"outline",disabled:l||!!j,"aria-describedby":j?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(rt,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ci,{"aria-hidden":"true",className:"size-3"}),l?"Requesting retry…":"Retry agent"]}):null,(0,t.jsxs)(L,{size:"xs",variant:"ghost",className:"text-muted-foreground","aria-expanded":i,"aria-controls":x,onClick:r(()=>o(C=>!C),"onClick"),children:[i?"Hide details":"View details",(0,t.jsx)(nn,{"aria-hidden":"true",className:W("size-3",i&&"rotate-180")})]}),s?(0,t.jsx)("time",{dateTime:s,className:"font-mono text-xs text-muted-foreground sm:ml-auto",children:ao(s)}):null]}),i?(0,t.jsxs)("div",{id:x,className:"flex flex-col gap-3 rounded-lg border border-border bg-muted/20 p-3",children:[(0,t.jsxs)("dl",{className:"flex flex-col gap-2 text-xs",children:[(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Assigned when recovery stopped"}),(0,t.jsx)("dd",{children:w})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Automatic attempts"}),(0,t.jsxs)("dd",{className:"font-mono",children:[e.attemptCount," of ",e.maxAttempts]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Automatic retries for this recovery"}),(0,t.jsx)("dd",{children:"Stopped"})]})]}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"Recovery asked the assigned agent to record an outcome or a next step. Retrying keeps the same task and agent, and checks the task’s current controls before continuing."}),(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Technical reason"}),(0,t.jsx)("code",{className:"break-all font-mono text-xs",children:e.reason})]})]}):null]})]})}r(tV,"DispositionRecoveryNotice");var g1e={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:Df,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:Df,iconClass:"text-sky-700 dark:text-sky-300",label:"text-sky-800 dark:text-sky-200",divider:"border-sky-300/50 dark:border-sky-500/30"},success:{container:"border-emerald-300/70 bg-emerald-50/70 dark:border-emerald-500/30 dark:bg-emerald-500/10",iconWrap:"bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-200",icon:ca,iconClass:"text-emerald-700 dark:text-emerald-300",label:"text-emerald-800 dark:text-emerald-200",divider:"border-emerald-300/50 dark:border-emerald-500/30"},warning:{container:"border-amber-300/70 bg-amber-50/80 dark:border-amber-500/30 dark:bg-amber-500/10",iconWrap:"bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-200",icon:Es,iconClass:"text-amber-700 dark:text-amber-300",label:"text-amber-900 dark:text-amber-200",divider:"border-amber-300/60 dark:border-amber-500/30"},danger:{container:"border-red-400/60 bg-red-50/80 dark:border-red-500/35 dark:bg-red-500/10",iconWrap:"bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-200",icon:Hk,iconClass:"text-red-700 dark:text-red-300",label:"text-red-900 dark:text-red-200",divider:"border-red-400/50 dark:border-red-500/30"}};function edt(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(edt,"formatTimestamp$1");function tdt({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(tdt,"MetadataRow$1");function b1e({sections:e,tone:s="neutral"}){const n=g1e[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)(tdt,{row:o,tone:n},l))})]},i))})}r(b1e,"SystemNoticeMetadataSections");function sV({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=g1e[e],u=d.icon,[h,p]=(0,m.useState)(o),f=(0,m.useId)(),x=!!(i&&i.length>0),b=s??{neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"}[e];return(0,t.jsxs)("section",{role:"status","aria-label":b,className:W("relative w-full overflow-hidden rounded-lg border text-sm shadow-(--shadow-extract-8)",d.container,c),children:[(0,t.jsxs)("header",{className:"flex items-start gap-3 px-3 py-2.5 sm:px-4",children:[(0,t.jsx)("span",{className:W("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",d.iconWrap),"aria-hidden":!0,children:(0,t.jsx)(u,{className:W("h-4 w-4",d.iconClass)})}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-eyebrow)",children:[(0,t.jsx)("span",{className:d.label,children:b}),a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),a.href?(0,t.jsx)("a",{href:a.href,className:"rounded-sm font-medium normal-case tracking-normal text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",children:a.label}):(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:a.label})]}):null,l?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:edt(l)})]}):null]}),(0,t.jsx)("div",{className:"mt-1 break-words text-sm leading-6 text-foreground",children:n})]}),x?(0,t.jsxs)("button",{type:"button",onClick:r(()=>p(v=>!v),"onClick"),"aria-expanded":h,"aria-controls":f,className:W("ml-1 inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-transparent px-2 text-(length:--text-micro) font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground transition-(--tp-background-color-border-color-color)","hover:border-border/70 hover:bg-background/70 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)("span",{children:h?"Hide details":"Details"}),(0,t.jsx)(nn,{className:W("h-3.5 w-3.5 transition-transform duration-150",h&&"rotate-180")})]}):null]}),x&&h?(0,t.jsx)("div",{id:f,className:W("border-t bg-background/50 dark:bg-background/30",d.divider),children:(0,t.jsx)(b1e,{sections:i,tone:e})}):null]})}r(sV,"SystemNotice");var sdt="System update",ndt=80;function rdt(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(rdt,"retryFailureCode");function adt(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(adt,"recoveryOwnerName");function idt(e){const s=e.split(`
|
|
355
|
+
`)}`:void 0}r(Pot,"sanitizeComponentStack");function jCe(){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(jCe,"readBrowserErrorState");function Mot(e){const s=Pot(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:jCe()}}}r(Mot,"buildBrowserErrorContext");var Sse=Promise.resolve();function YW(e){const s=Sse.then(e);return Sse=s.catch(()=>{}),s}r(YW,"enqueue");var mN=null;function Dot(e,s){return YW(async()=>{if(!mN)try{const n=await Jc(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init($ot(e,s)),mN=n}catch{}})}r(Dot,"initBrowserErrorMonitoring");function Lot(){return YW(async()=>{const e=mN;if(mN=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(Lot,"teardownBrowserErrorMonitoring");function wCe(e,s){let n;try{s&&(n=Mot(s))}catch{}YW(async()=>{try{n?mN?.captureException(e,n):mN?.captureException(e)}catch{}})}r(wCe,"captureBrowserException");function $ot(e,s){return{dsn:e,environment:s??void 0,release:"c82c9f130681d085384e18b3aea525a24028d02c",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??jCe()},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($ot,"buildBrowserSentryInitOptions");var Oot=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){wCe(e,{boundary:"route",componentStack:s.componentStack})}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){const{error:e}=this.state;return e?(0,t.jsxs)("div",{className:"mx-auto max-w-2xl space-y-4 px-4 py-10",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"This page hit an error"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Something went wrong while rendering this page. You can go back and try again, or reload."})]}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive whitespace-pre-wrap",children:e.message}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:this.props.onReset,children:"Go back"}),(0,t.jsx)(L,{size:"sm",onClick:r(()=>window.location.reload(),"onClick"),children:"Reload page"})]})]}):this.props.children}};function kCe({children:e}){const s=na(),n=Mn(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(Oot,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(kCe,"RouteErrorBoundary");var Cse={bot:no,cpu:ym,brain:Xx,zap:A3,rocket:B$e,code:Sxe,terminal:hg,shield:EI,eye:Ed,search:oa,wrench:Pf,hammer:mM,lightbulb:RI,sparkles:Np,star:yp,heart:FC,flame:mOe,bug:Kv,cog:wfe,database:PI,globe:Ap,lock:pd,mail:c7,"message-square":Sf,"file-code":Ll,"git-branch":io,package:Th,puzzle:Zx,target:vp,wand:H7,atom:iOe,"circuit-board":lqe,radar:O$e,swords:qqe,telescope:V$e,microscope:Cqe,crown:jfe,gem:Cxe,hexagon:Ad,pentagon:Tqe,fingerprint:Oz},Fot="bot";function Bot(e){return e&&HLe.includes(e)?Cse[e]:Cse[Fot]}r(Bot,"getAgentIcon");function F5({icon:e,className:s}){const n=Bot(e);return(0,t.jsx)(n,{className:s})}r(F5,"AgentIcon");function NCe({open:e,onOpenChange:s,...n}){return(0,t.jsx)(Ys,{open:e,onOpenChange:s,children:(0,t.jsxs)(Js,{"aria-describedby":void 0,className:"gap-0 overflow-hidden p-0 sm:max-w-md",children:[(0,t.jsxs)("div",{className:"px-4 pt-4 pb-3",children:[(0,t.jsx)(Xs,{children:"Chat with an agent"}),n.existingChatAgentIds&&(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"One conversation per agent. Pick up where you left off."})]}),(0,t.jsx)(zot,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(NCe,"AgentChatPicker");function zot({agents:e,onSelect:s,onComplete:n,loading:a,error:i,onRetry:o,existingChatAgentIds:l,renderAgentIcon:c}){const d=(0,m.useRef)(!1),u=(0,m.useRef)(null);(0,m.useEffect)(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null),[b,v]=(0,m.useState)(null);async function j(N){if(f)return;x(N.id),v(null);const w=new AbortController;u.current=w;try{await s(N,w.signal),d.current&&n()}catch(k){v(k instanceof Error?k.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(j,"selectAgent"),(0,t.jsxs)(OI,{children:[(0,t.jsx)(VN,{"aria-label":"Search agents by name or role",placeholder:"Search by name or role…",value:h,onValueChange:p}),b&&(0,t.jsx)("p",{role:"alert",className:"px-4 py-3 text-sm text-destructive",children:b}),f&&(0,t.jsx)("p",{role:"status",className:"sr-only",children:"Opening conversation…"}),i?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 p-4 text-sm",children:[(0,t.jsx)("p",{children:"Couldn’t load agents. Try again."}),o&&(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:o,children:"Retry"})]}):a?(0,t.jsx)("p",{role:"status",className:"p-4 text-sm text-muted-foreground",children:"Loading agents…"}):(0,t.jsxs)(WN,{children:[(0,t.jsx)(KN,{children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4",children:[(0,t.jsx)("span",{children:e.length?`No agents match “${h}”`:"No agents yet."}),e.length?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Try another name or role."}),(0,t.jsx)(L,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(Au,{children:e.map(N=>(0,t.jsxs)(Ko,{value:N.id,keywords:[N.name,N.title??"",N.role],onSelect:r(()=>{j(N)},"onSelect"),disabled:f!==null,className:"gap-3 px-3 py-3",children:[c?c(N):(0,t.jsx)(F5,{icon:N.icon,className:"size-4 shrink-0"}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate font-medium",children:N.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:N.title??N.role})]}),l&&(0,t.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:l.includes(N.id)?"Open chat":"New chat"}),N.status==="paused"&&(0,t.jsx)("span",{className:"text-xs text-(--status-agent-paused)",children:"Paused"}),N.status==="terminated"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Terminated"}),N.status==="pending_approval"&&(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Awaiting approval"})]},N.id))})]})]})}r(zot,"AgentChatPickerResults");function kE({agents:e,existingChatAgentIds:s,availableAgents:n=e,activeId:a,previews:i={},loading:o=!1,error:l,onRetry:c,initialSearch:d="",onSelect:u,onBrowse:h,onAddChat:p,historyLoading:f,historyError:x,onRetryHistory:b}){const v=Mn(),[j,N]=(0,m.useState)(!1),[w,k]=(0,m.useState)(d),S=(0,m.useRef)(null),C=(0,m.useId)(),I=w.trim().toLocaleLowerCase(),R=e.filter(A=>`${A.name} ${A.title??""} ${A.role}`.toLocaleLowerCase().includes(I));function T(){k(""),S.current?.focus()}return r(T,"focusSearch"),(0,t.jsxs)("aside",{"aria-labelledby":C,className:"flex h-full min-h-0 flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-4 px-3 pb-4 pt-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("h2",{id:C,className:"text-sm font-semibold",children:"Chat"}),(0,t.jsx)(L,{variant:"outline",size:"icon-sm","aria-label":"Add chat",title:"Add chat",onClick:r(()=>N(!0),"onClick"),children:(0,t.jsx)(yn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(oa,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(ht,{ref:S,"aria-label":"Search agents",placeholder:"Find an agent",value:w,onChange:r(A=>k(A.target.value),"onChange"),onKeyDown:r(A=>{A.key==="Escape"&&(A.stopPropagation(),k(""))},"onKeyDown"),className:"h-8 pl-8 pr-8 text-xs md:text-xs"}),w&&(0,t.jsx)(L,{variant:"ghost",size:"icon-xs","aria-label":"Clear search",className:"absolute right-1 top-1/2 -translate-y-1/2",onClick:T,children:(0,t.jsx)(Fn,{className:"size-3"})})]})]}),(0,t.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-3 pb-3 scrollbar-auto-hide",children:[(0,t.jsx)("p",{className:"px-2 text-(length:--text-micro) font-medium uppercase tracking-widest text-muted-foreground",children:I?"Search results":"Teammates"}),(0,t.jsx)("span",{role:"status",className:"sr-only",children:o?"Loading agents":`${R.length} ${R.length===1?"agent":"agents"}`}),f&&(0,t.jsx)("p",{role:"status",className:"px-2 text-xs text-muted-foreground",children:"Loading chat history…"}),x&&(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-3",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Some chat history couldn’t load."}),(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:b,children:"Retry chat history"})]}),l?(0,t.jsxs)("div",{role:"alert",className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm",children:"Couldn’t load your chats."}),(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:c,children:"Try again"})]}):o?(0,t.jsx)("div",{"aria-hidden":"true",className:"flex flex-col gap-1",children:[0,1,2,3].map(A=>(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-md px-2 py-3 motion-safe:animate-pulse",children:[(0,t.jsx)("div",{className:"size-8 shrink-0 rounded-lg bg-muted"}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-2",children:[(0,t.jsx)("div",{className:"h-3 w-2/3 rounded-sm bg-muted"}),(0,t.jsx)("div",{className:"h-2 w-full rounded-sm bg-muted"})]})]},A))}):R.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:R.map(A=>(0,t.jsxs)(Ke,{to:`/chats/${encodeURIComponent(A.status==="terminated"?A.id:Xl(A))}`,"aria-current":a===A.id?"page":void 0,title:`${A.name}${A.title?` · ${A.title}`:""}`,onClick:r(D=>{u&&(D.preventDefault(),u(A))},"onClick"),className:W("flex min-w-0 items-center gap-3 rounded-md px-2 py-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",a===A.id&&"bg-accent text-accent-foreground"),children:[(0,t.jsx)(gr,{agent:A,size:32}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[(0,t.jsx)("span",{className:"truncate text-sm font-medium",children:A.name}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:A.status==="terminated"?"Terminated":A.status==="paused"?"Paused":i[A.id]??A.title??"Start a conversation"})]})]},A.id))}):!e.length&&(f||x)?null:(0,t.jsxs)("div",{className:"flex flex-col items-start gap-2 px-2 py-6",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:e.length?"No agents found":"No chats yet"}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:e.length?"Try another name or role.":"Choose an agent to start a conversation."}),!e.length&&(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:r(()=>N(!0),"onClick"),children:"Choose an agent"}),e.length>0&&(0,t.jsx)(L,{variant:"outline",size:"sm",onClick:T,children:"Clear search"})]})]}),(0,t.jsx)("div",{className:"shrink-0 px-3 py-4",children:(0,t.jsx)(L,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2 text-muted-foreground",asChild:!h,onClick:h,children:h?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(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)(NCe,{agents:n,open:j,onOpenChange:N,existingChatAgentIds:s??e.map(A=>A.id),loading:o,error:l,onRetry:c,renderAgentIcon:r(A=>(0,t.jsx)(gr,{agent:A,size:32}),"renderAgentIcon"),onSelect:r(async(A,D)=>{p?await p(A,D):u?await u(A,D):v(`/chats/${encodeURIComponent(Xl(A))}`),D?.aborted||k("")},"onSelect")})]})}r(kE,"AgentConversationSidebar");var B5={list:r(e=>Te.get(`/companies/${e}/chats`),"list"),get:r((e,s)=>Te.get(`/companies/${e}/chats/${encodeURIComponent(s)}`),"get"),ensure:r((e,s)=>Te.post(`/companies/${e}/chats/${encodeURIComponent(s)}`,{}),"ensure")};function SCe(){const{selectedCompanyId:e}=ps(),{enabled:s,loaded:n}=Yy(),a=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:ee({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn"),enabled:s&&!!e}),chats:ee({queryKey:P.agentChats.list(e,i),queryFn:r(()=>B5.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(SCe,"useAgentChatNavigation");function CCe(e,s){const n=Pt(),a=Mn(),{isMobile:i,setSidebarOpen:o}=qa(),l=(0,m.useRef)({companyId:e,userId:s,mounted:!0});return(0,m.useEffect)(()=>{const c={companyId:e,userId:s,mounted:!0};return l.current=c,()=>{c.mounted=!1}},[e,s]),(0,m.useCallback)(async(c,d)=>{if(!e||c.companyId!==e)throw new Error("Choose an agent from this company.");const u=l.current,h=await B5.ensure(e,c.id);n.setQueryData(P.agentChats.detail(e,s,c.id),h),n.setQueryData(P.issues.detail(h.id),h),n.setQueryData(P.agentChats.list(e,s),p=>[h,...(p??[]).filter(f=>f.id!==h.id)].sort((f,x)=>new Date(x.updatedAt).getTime()-new Date(f.updatedAt).getTime()||x.id.localeCompare(f.id))),!(!u.mounted||l.current!==u||d?.aborted)&&(a(`/chats/${encodeURIComponent(Xl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(CCe,"useOpenAgentChat");function qot(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=SCe(),o=CCe(e,s),l=Mn(),c=Yf(e),{isMobile:d,setSidebarOpen:u}=qa(),{pathname:h}=na(),p=h.split("/chats/")[1]?.split("/")[0],f=n.data??[],x=n.isSuccess?[...new Set((a.data??[]).flatMap(C=>C.conversationAgentId&&!f.some(I=>I.id===C.conversationAgentId)?[C.conversationAgentId]:[]))]:[],b=Rh({queries:x.map(C=>({queryKey:P.agents.detail(C),queryFn:r(()=>$t.get(C,e),"queryFn")}))}),v=new Map(f.map(C=>[C.id,C]));for(const C of b)C.data&&v.set(C.data.id,C.data);const j=[...v.values()].find(C=>C.id===p||C.status!=="terminated"&&encodeURIComponent(Xl(C))===p),N=(a.data??[]).flatMap(C=>{const I=C.conversationAgentId?v.get(C.conversationAgentId):void 0;return I?[I]:[]});j&&!N.some(C=>C.id===j.id)&&N.unshift(j);const w=new Set(N.map(C=>C.id)),k=f.filter(C=>!w.has(C.id)&&C.status!=="terminated"&&(!c.isSuccess||Of(c.data,"agent",C.id)!=="left")).sort((C,I)=>C.name.localeCompare(I.name,void 0,{sensitivity:"base"})),S=Object.fromEntries((a.data??[]).filter(C=>C.conversationState==="active").map(C=>[C.conversationAgentId,"Working…"]));return(0,t.jsx)(kE,{agents:[...N,...k],availableAgents:f,existingChatAgentIds:N.map(C=>C.id),activeId:j?.id,previews:S,loading:n.isPending||a.isPending||i.isPending,error:n.error??a.error??i.error,onRetry:r(()=>{n.refetch(),a.refetch(),i.refetch()},"onRetry"),historyLoading:b.some(C=>C.isPending),historyError:b.find(C=>C.error)?.error,onRetryHistory:r(()=>{b.filter(C=>C.isError).forEach(C=>{C.refetch()})},"onRetryHistory"),onAddChat:o,onSelect:r(C=>{l(`/chats/${encodeURIComponent(C.status==="terminated"?C.id:Xl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(qot,"AgentConversationsSidebar");var X2=240,b6=208,v6=420,_se=16;function z5(e){return Math.min(v6,Math.max(b6,e))}r(z5,"clampSidebarWidth$1");function Ise(e){if(typeof window>"u")return X2;try{const s=window.localStorage.getItem(e);if(!s)return X2;const n=Number.parseInt(s,10);return Number.isFinite(n)?z5(n):X2}catch{return X2}}r(Ise,"readStoredSidebarWidth$1");function Ase(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(z5(s)))}catch{}}r(Ase,"writeStoredSidebarWidth$1");function Uot({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)(()=>Ise(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=Ise(o);v.current=E,f(E)},[o]);const N=s?p:0,w=s?n?64:N:0,k=s?n&&!a?64:N:0,S=k>w,C=i&&s&&!n,I=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),T=(0,m.useCallback)(E=>{const z=z5(E);v.current=z,f(z),Ase(o,z)},[o]),A=(0,m.useCallback)(E=>{C&&(E.preventDefault(),E.currentTarget.setPointerCapture(E.pointerId),j.current={startX:E.clientX,startWidth:v.current},b(!0))},[C]),D=(0,m.useCallback)(E=>{if(!j.current)return;const z=z5(j.current.startWidth+E.clientX-j.current.startX);v.current=z,f(z)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),Ase(o,v.current))},[o]),B=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),T(p-_se)):E.key==="ArrowRight"?(E.preventDefault(),T(p+_se)):E.key==="Home"?(E.preventDefault(),T(b6)):E.key==="End"&&(E.preventDefault(),T(v6)))},[C,T,p]);return(0,t.jsxs)("div",{className:W("relative h-full shrink-0",l),style:I,children:[(0,t.jsx)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:e}),C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":b6,"aria-valuemax":v6,"aria-valuenow":p,tabIndex:0,"data-dragging":x?"":void 0,className:"group absolute inset-y-0 z-20 cursor-col-resize touch-none outline-none",style:{right:-4,width:8},onPointerDown:A,onPointerMove:D,onPointerUp:M,onPointerCancel:M,onLostPointerCapture:M,onKeyDown:B,children:(0,t.jsx)("div",{className:W("mx-auto h-full w-0.5 transition-colors",x?"bg-ring":"bg-transparent group-hover:bg-ring group-focus-visible:bg-ring")})}):null]})}r(Uot,"SidebarShell$1");function Z2({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)(xye,{children:e})})}r(Z2,"SecondarySidebar$1");var _Ce={listStacks:r(()=>Te.get("/cloud/stacks"),"listStacks")};function p4(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(p4,"cloudAppUrl");function ICe(e){return p4(e,"/stacks/new")}r(ICe,"cloudStackCreateUrl");function ACe(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(ACe,"tenantSignInReturnPath");function Kot(e,s,n){const a=s?.trim();if(!a)return null;const i=p4(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",ACe(n)),o.toString()}r(Kot,"cloudStackEntryUrl");function TCe(e,s){const n=s?.trim();return n?p4(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(TCe,"cloudStackInviteUrl");function Wot(e){return p4(e,"/orgs?manage=1")}r(Wot,"cloudPortfolioManageUrl");function RCe(){const e=$c(),s=!!e,n=ee({queryKey:P.cloud.stacks,queryFn:r(()=>_Ce.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:TCe(e.cloudBaseUrl,a.stackSlug)}r(RCe,"useCloudInviteUrl");function Vot(e,s){if(!s)return!1;if(s.source==="local_implicit"||s.isInstanceAdmin)return!0;if(!e)return!1;const n=s.memberships?.find(a=>a.companyId===e&&a.status==="active");return n?.membershipRole==="owner"||n?.membershipRole==="admin"}r(Vot,"canInviteCompanyMembers");function ECe(e=!0){const s=mLe(),n=ee({queryKey:P.access.currentBoardAccess,queryFn:r(()=>pr.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&Vot(s?.selectedCompanyId,n.data)}r(ECe,"useCanInviteCompanyMembers");function PCe(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=ee({queryKey:P.stagingCommit,queryFn:r(()=>du.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(PCe,"useStagingCommit");function Hot(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(Hot,"slugifyUserPart");function MCe(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=Hot(n);if(a)return`/u/${a}`}return"/u/me"}r(MCe,"userProfilePath");var Got="Toggle the app appearance.";function yk({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=mBe(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?wve:wbe;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:Got})]})]}):(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm",onClick:d,"aria-label":l,title:l,className:W("text-muted-foreground",e),children:(0,t.jsx)(c,{})})}r(yk,"ThemeToggle");var U_=null,DCe=!1,y6=!1,j6=new Set;function q5(){for(const e of j6)e()}r(q5,"emit");function Qot(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(Qot,"isIosSafariLike");function Yot(e=window){const s=r(a=>{a.preventDefault(),U_=a,q5()},"onPrompt"),n=r(()=>{U_=null,DCe=!0,q5()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(Yot,"captureInstallPrompt");function Jot(){return DCe||x6()?"installed":U_?"prompt":Qot()?"ios-manual":"unavailable"}r(Jot,"installAvailability");async function Xot(){const e=U_;if(!e)return"unavailable";U_=null,q5(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(Xot,"promptInstall");function w6(e){y6!==e&&(y6=e,q5())}r(w6,"setIosInstallHelpOpen");function Zot(){return y6}r(Zot,"iosInstallHelpOpen");function elt(){return(0,m.useSyncExternalStore)(LCe,Zot,()=>!1)}r(elt,"useIosInstallHelpOpen");function LCe(e){return j6.add(e),()=>{j6.delete(e)}}r(LCe,"subscribe$1");function tlt(){return(0,m.useSyncExternalStore)(LCe,Jot,()=>"unavailable")}r(tlt,"useInstallAvailability");var Tse="Install app",slt="Add Paperclip to your home screen or dock.";function $Ce({variant:e,onAfterAction:s}){const n=tlt();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?w6(!0):Xot(),s?.()},"handleClick");return e==="compact-menu-action"?(0,t.jsxs)("button",{type:"button",className:"flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",onClick:a,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(po,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:Tse})]}):(0,t.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",onClick:a,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(po,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:Tse}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:slt})]})]})}r($Ce,"InstallAppMenuAction");function nlt(){const e=elt();return(0,t.jsx)(Ys,{open:e,onOpenChange:w6,children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Install Paperclip"}),(0,t.jsx)(jn,{children:"Add Paperclip to your Home Screen from Safari."})]}),(0,t.jsxs)("ol",{className:"space-y-3 text-sm text-foreground",children:[(0,t.jsxs)(tO,{index:1,icon:(0,t.jsx)(Fqe,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(tO,{index:2,icon:(0,t.jsx)(zqe,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(tO,{index:3,children:["Keep ",(0,t.jsx)("strong",{children:"Open as Web App"})," on, then tap ",(0,t.jsx)("strong",{children:"Add"}),"."]})]}),(0,t.jsx)(hr,{children:(0,t.jsx)(L,{type:"button",onClick:r(()=>w6(!1),"onClick"),children:"Done"})})]})})}r(nlt,"IosInstallHelpDialog");function tO({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(tO,"InstallStep");function rlt(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(rlt,"formatTimestamp$2");function alt(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(alt,"isValidTimestamp");function ilt(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(ilt,"restartTimestamp");function olt(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(olt,"commitLabel");function llt(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(llt,"localChangesLabel");function sO({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(sO,"ServerInfoRow");function OCe(){const e=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=ee({queryKey:P.health,queryFn:r(()=>du.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=ilt(n),l=alt(o),c=i?"Health unavailable":a?"Loading...":rlt(o),d=i?"Health unavailable":a?"Loading...":olt(n),u=i?"Health unavailable":a?"Loading...":llt(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)(sO,{icon:au,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(sO,{icon:D7,label:"Running commit",value:d}),(0,t.jsx)(sO,{icon:pqe,label:"Checkout state",value:u})]})}r(OCe,"SidebarServerInfo");var clt="/company/settings/members?tab=invites",dlt="https://docs.paperclip.ing/",ult="https://paperclip.ing/feedback";function mlt(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(mlt,"deriveInitials$2");function nO({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(nO,"MenuAction$1");function Rse({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!$c(),{hidden:l,loaded:c}=cu(),d=RCe(),u=ECe(!o),h=o?d:u?clt:null,p=c&&h!==null&&!dg(l,"company.members")&&!dg(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:b,setSidebarOpen:v,collapsed:j,peeking:N}=qa(),w=j&&!N&&!a,k=s??f,S=PCe(k),C=n??x,{data:I}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),R=eS({onSignedOut:B}),T=I?.user.name?.trim()||"Board",A=I?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),D=mlt(T),M=MCe(I?.user);function B(){C(!1),b&&v(!1)}r(B,"closeNavigationChrome");function E(){R.mutate()}return r(E,"handleSignOut"),(0,t.jsx)("div",{className:"bg-border/50 px-3 py-2 dark:bg-muted",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!w&&"px-2"),children:[(0,t.jsxs)(br,{open:k,onOpenChange:C,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",w?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(Mo,{size:"sm",children:[I?.user.image?(0,t.jsx)(xd,{src:I.user.image,alt:T}):null,(0,t.jsx)(Do,{children:D})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",w&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:T})]})}),(0,t.jsxs)(dr,{side:"top",align:"start",sideOffset:10,className:"min-h-(--profile-popover-min-height) w-(--profile-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"relative flex h-(--profile-popover-header-height) shrink-0 items-center gap-2.5 px-3.5",children:[(0,t.jsx)(Ke,{to:M,"aria-label":"View profile",onClick:B,className:"absolute inset-0 transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"}),(0,t.jsxs)(Mo,{className:"pointer-events-none relative size-9",children:[I?.user.image?(0,t.jsx)(xd,{src:I.user.image,alt:T}):null,(0,t.jsx)(Do,{className:"text-xs text-foreground",children:D})]}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1",children:[(0,t.jsx)("h2",{className:"truncate text-sm font-semibold leading-(--profile-popover-label-line-height) text-foreground",children:T}),(0,t.jsx)("p",{className:"truncate text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground",children:A}),S?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${S}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${S} on GitHub`,title:S,children:["SHA ",S.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"flex flex-1 flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[(0,t.jsx)(nO,{label:"Settings",icon:iu,href:"/company/settings",onClick:B}),p&&h?(0,t.jsx)(nO,{label:"Invite",icon:Gf,href:h,topLevel:o,onClick:B}):null,(0,t.jsx)(nO,{label:"Documentation",icon:GN,href:dlt,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(yk,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)($Ce,{variant:"compact-menu-action",onAfterAction:r(()=>C(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-destructive/10",R.isPending&&"cursor-not-allowed opacity-60"),onClick:E,disabled:R.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Tp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:R.isPending?"Signing out...":"Sign out"})]}):null,(0,t.jsx)(OCe,{})]})]})]}),!w&&!o?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("a",{href:ult,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)(_g,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Un,{side:"top",children:"Share feedback"})]}):null]})})}r(Rse,"SidebarAccountMenu$1");function FCe({onNewIssue:e,onSearch:s,onToggleSidebar:n,onTogglePanel:a,onShowShortcuts:i,onGoToInbox:o}){(0,m.useEffect)(()=>{let l=!1,c=null;const d=r(()=>{c!==null&&(window.clearTimeout(c),c=null)},"clearGoChordTimeout"),u=r(()=>{l=!1,d()},"disarmGoChord"),h=r(()=>{l=!0,d(),c=window.setTimeout(()=>{l=!1,c=null},1200)},"armGoChord");function p(b){if(b.defaultPrevented){u();return}if(o){const v=exe({armed:l,defaultPrevented:b.defaultPrevented,key:b.key,metaKey:b.metaKey,ctrlKey:b.ctrlKey,altKey:b.altKey,target:b.target,hasOpenDialog:wp()});if(v==="arm"){h();return}if(v==="navigate_inbox"){u(),b.preventDefault(),o();return}if(v==="focus_comment"||v==="open_file_viewer"){u(),b.preventDefault();return}v==="disarm"&&u()}if(!LI(b.target)&&!wp()){if(b.key==="/"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),oFe()||s?.();return}if(b.key==="?"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),i?.();return}b.key==="c"&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&(b.preventDefault(),e?.()),b.key==="["&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),n?.()),b.key==="]"&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(b=>{b.target instanceof HTMLElement&&b.target!==document.body&&u()},"handleFocusIn");return document.addEventListener("pointerdown",f,!0),document.addEventListener("focusin",x,!0),document.addEventListener("keydown",p),()=>{u(),document.removeEventListener("pointerdown",f,!0),document.removeEventListener("focusin",x,!0),document.removeEventListener("keydown",p)}},[e,s,n,a,i,o])}r(FCe,"useKeyboardShortcuts");var hlt=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function BCe(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!hlt.has(n)}r(BCe,"isRememberableCompanyPath");function plt(e){const s=ly(e.companyPrefix);return e.companies.find(n=>ly(n.issuePrefix)===s)??null}r(plt,"findCompanyByPrefix");function flt(e){const s=d7(e.pathname);return s?plt({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(flt,"getRememberedPathOwnerCompanyId");function xlt(e){const s=e.path?pM(e.path):"/dashboard";if(!BCe(s))return"/dashboard";const[n,a]=(s.split("?")[0]??"").split("/").filter(Boolean);if(n==="issues"&&a){const i=/^([A-Za-z]+)-\d+$/.exec(a);if(i&&ly(i[1]??"")!==ly(e.companyPrefix))return"/dashboard"}return s}r(xlt,"sanitizeRememberedPathForCompany");var zCe="paperclip.companyPaths";function qCe(){try{const e=localStorage.getItem(zCe);if(e)return JSON.parse(e)}catch{}return{}}r(qCe,"getCompanyPaths");function glt(e,s){const n=qCe();n[e]=s,localStorage.setItem(zCe,JSON.stringify(n))}r(glt,"saveCompanyPath");function UCe(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=ps(),i=na(),o=Mn(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>flt({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=pM(d);u&&BCe(h)&&glt(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=qCe(),h=xlt({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(UCe,"useCompanyPageMemory");var blt=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 KCe(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 blt({topZone:o("--mobile-nav-scroll-top-zone"),hideDistance:o("--mobile-nav-scroll-hide-distance"),showDistance:o("--mobile-nav-scroll-show-distance")},c.top,c.max);let u=null;const h=r(()=>{u===null&&(u=requestAnimationFrame(()=>{u=null;const{top:p,max:f}=l(),x=d.visible,b=d.update(p,f);b!==x&&a(b)}))},"onScroll");return window.addEventListener("scroll",h,{passive:!0}),()=>{window.removeEventListener("scroll",h),u!==null&&cancelAnimationFrame(u)}},[e,s]),n}r(KCe,"useMobileNavVisibility");function WCe(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(WCe,"resolveArchivedCompanyBounce");function vlt(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(vlt,"resolveCompanyArchiveDeparture");function VCe(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(VCe,"shouldSyncCompanySelectionFromRoute");function ylt(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(ylt,"shouldFocusMainContentAfterNavigation");function HCe(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{ylt(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(HCe,"scheduleMainContentFocus");function GCe(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(GCe,"pinDocumentScrollToZero");function zu({scope:e="global",requestedPrefix:s}){const n=na(),{setBreadcrumbs:a}=Bn(),{companies:i,selectedCompany:o}=ps();(0,m.useEffect)(()=>{a([{label:"Not Found"}])},[a]);const l=o??i[0]??null,c=l?`/${l.issuePrefix}/dashboard`:"/",d=`${n.pathname}${n.search}${n.hash}`,u=s?.toUpperCase(),h=e==="invalid_company_prefix"?"Organization not found":"Page not found",p=e==="invalid_company_prefix"?`No organization matches prefix "${u??"unknown"}".`:"This route does not exist.";return(0,t.jsx)("div",{className:"mx-auto max-w-2xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Es,{className:"h-5 w-5 text-destructive"})}),(0,t.jsxs)("div",{children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:p})]})]}),(0,t.jsxs)("div",{className:"mt-4 rounded-md border border-border bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:["Requested path: ",(0,t.jsx)("code",{className:"font-mono",children:d})]}),(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{asChild:!0,children:(0,t.jsxs)(Ke,{to:c,children:[(0,t.jsx)(_3,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)(L,{variant:"outline",asChild:!0,children:(0,t.jsx)(Ke,{to:"/",children:"Go home"})})]})]})})}r(zu,"NotFoundPage");function jlt(e,s){return wje(e,s)[0]?.toLowerCase()??null}r(jlt,"getCompanyRouteSegment$1");var wlt=new Set(["browse","connections","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function klt({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=qa(),{openNewIssue:u,openOnboarding:h}=Yo(),{togglePanelVisible:p}=Jf(),f=Xc()?.pushToast??null,{companies:x,loading:b,selectedCompany:v,selectedCompanyId:j,selectionSource:N,setSelectedCompanyId:w}=ps(),{companyPrefix:k,pluginRoutePath:S,agentId:C,routineId:I}=va(),R=Mn(),T=na(),A=hM(),{enabled:D}=yc(),M=kje(T.pathname,k),B=M.builtInContextualSurface==="settings",E=M.companySegments,z=M.isTaskDetail,{enabled:$}=Yy(),q=$&&E[0]?.toLowerCase()==="chats",U=D&&(z||q),O=E[0]?.toLowerCase()==="tools",K=E[0]?.toLowerCase()==="apps",H=K&&E[1]&&!wlt.has(E[1].toLowerCase())?E[1]:null,Z=K&&E[1]?.toLowerCase()==="app"&&E[2]?E[2]:null,se=(0,m.useRef)(!1),ne=(0,m.useRef)(null),fe=(0,m.useRef)(null),X=(0,m.useRef)(new hye),re=(0,m.useRef)(T.key),oe=KCe(c&&!z,T.pathname),[G,Y]=(0,m.useState)(!1),Q=(0,m.useMemo)(()=>{if(!k)return null;const lt=k.toUpperCase();return x.find(Ee=>Ee.issuePrefix.toUpperCase()===lt)??null},[x,k]),te=!!k&&!b&&x.length>0&&!Q,ae=(0,m.useMemo)(()=>S?.toLowerCase()??jlt(T.pathname,k),[k,T.pathname,S]),le=Q?.id??null,he=Q?.issuePrefix??null,{slots:ce}=gd({slotTypes:["page","routeSidebar"],companyId:le,enabled:!!(le&&ae)}),ge=(0,m.useMemo)(()=>l9(ce,ae),[ae,ce]),me=(0,m.useMemo)(()=>({companyId:le,companyPrefix:he}),[le,he]),ie=B?(0,t.jsx)(U9e,{}):!D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(hZ,{}):H?(0,t.jsx)(uZ,{kind:"connection",connectionId:H}):Z?(0,t.jsx)(uZ,{kind:"application",applicationId:Z}):K||O?(0,t.jsx)(J9e,{}):ge?D?(0,t.jsx)(tA,{surface:`plugin:${ge.id}`,title:ge.displayName,children:(0,t.jsx)(Wu,{slot:ge,context:me,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(Wu,{slot:ge,context:me,className:"h-full w-full",missingBehavior:"placeholder"}):null,ue=q?(0,t.jsx)(qot,{}):M.builtInContextualSurface==="agent"&&C?(0,t.jsx)(uWe,{agentRef:C}):D&&M.builtInContextualSurface==="routine"&&I?(0,t.jsx)(NKe,{children:(0,t.jsx)(pWe,{routineId:I})}):D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(hZ,{}):ie,ke=ue!=null,be=D&&ke&&(q||M.builtInContextualSurface==="skills"||M.builtInContextualSurface==="agent"||M.builtInContextualSurface==="routine"||K||O),Ie=D&&ke&&!be,Ue=ke&&(!D||be),at=!D||!ke?null:ge&&!M.builtInContextualSurface?`plugin:${ge.id}`:M.builtInContextualSurface,dt=(0,m.useRef)(null),{data:de}=ee({queryKey:P.health,queryFn:r(()=>du.get(),"queryFn"),retry:!1,refetchInterval:r(lt=>lt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!D&&ke),()=>d(!1)),[ke,d,D]),(0,m.useEffect)(()=>{const lt=dt.current;at&&k&<&<.surface!==at&<.pathname!==T.pathname&&B9e({surface:at,companyPrefix:k,previousPathname:lt.pathname}),dt.current={pathname:T.pathname,surface:at}},[k,at,T.pathname]),(0,m.useEffect)(()=>{b||se.current||de?.deploymentMode!=="authenticated"&&(de?.cloud||x.length===0&&(se.current=!0,h()))},[x,b,h,de?.cloud,de?.deploymentMode]),(0,m.useEffect)(()=>{if(!k||b||x.length===0)return;if(!Q){const Ee=(j?x.find(Xe=>Xe.id===j):null)??x[0]??null;Ee&&j!==Ee.id&&w(Ee.id,{source:"route_sync"});return}if(k!==Q.issuePrefix){const Ee=T.pathname.replace(/^\/[^/]+/,"");R(`/${Q.issuePrefix}${Ee}${T.search}`,{replace:!0});return}const lt=WCe({matchedCompany:Q,selectedCompanyId:j,companies:x});if(lt){f?.({title:`${Q.name} is archived`,body:`Switched to ${lt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Q.id}`}),w(lt.id,{source:"route_sync"}),R(`/${lt.issuePrefix}/dashboard`,{replace:!0});return}VCe({selectionSource:N,selectedCompanyId:j,routeCompanyId:Q.id})&&w(Q.id,{source:"route_sync"})},[k,x,b,Q,T.pathname,T.search,R,f,N,j,w]);const Be=p,pt=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),vt=(0,m.useRef)(null),Le=(0,m.useRef)(!1),Qe=(0,m.useRef)(!1),ut=(0,m.useCallback)(()=>{vt.current!==null&&(window.clearTimeout(vt.current),vt.current=null)},[]),Ye=(0,m.useCallback)(()=>{ut(),vt.current=window.setTimeout(()=>l(!0),50)},[ut,l]),it=(0,m.useCallback)(()=>{ut(),l(!0)},[ut,l]),kt=(0,m.useCallback)(()=>{ut(),vt.current=window.setTimeout(()=>l(!1),120)},[ut,l]),tt=(0,m.useCallback)(()=>{Le.current=!0,i&&!Qe.current&&Ye()},[i,Ye]),Pe=(0,m.useCallback)(()=>{Le.current=!1,Qe.current=!1,kt()},[kt]),Ce=(0,m.useCallback)(()=>{Qe.current||it()},[it]),He=(0,m.useCallback)(()=>{Le.current||kt()},[kt]);(0,m.useEffect)(()=>ut,[ut]);const Je=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Je.current&&(i?(ut(),l(!1),Qe.current=Le.current):Qe.current=!1,Je.current=i)},[i,ut,l]),(0,m.useEffect)(()=>{if(!o)return;const lt=r(Ee=>{Ee.key==="Escape"&&(ut(),l(!1))},"onKeyDown");return window.addEventListener("keydown",lt),()=>window.removeEventListener("keydown",lt)},[o,ut,l]),UCe(),FCe({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:pt,onToggleSidebar:a,onTogglePanel:Be,onShowShortcuts:r(()=>Y(!0),"onShowShortcuts"),onGoToInbox:r(()=>R("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const lt=30,Ee=50,Xe=75;let Ae=0,De=0;const _t=r(gt=>{const We=gt.touches[0];Ae=We.clientX,De=We.clientY},"onTouchStart"),ye=r(gt=>{const We=gt.changedTouches[0],Ot=We.clientX-Ae;if(!(Math.abs(We.clientY-De)>Xe)){if(!s&&Ae<lt&&Ot>Ee){n(!0);return}s&&Ot<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",_t,{passive:!0}),document.addEventListener("touchend",ye,{passive:!0}),()=>{document.removeEventListener("touchstart",_t),document.removeEventListener("touchend",ye)}},[c,s,n]),(0,m.useEffect)(()=>{const lt=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=lt}},[c]),(0,m.useEffect)(()=>{if(!c)return GCe()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const lt=fe.current;return HCe(lt)},[T.pathname]),(0,m.useEffect)(()=>{const lt=fe.current;if(!lt)return;const Ee=r(()=>{X.current.remember(re.current,lt.scrollTop)},"recordScroll");return lt.addEventListener("scroll",Ee,{passive:!0}),()=>lt.removeEventListener("scroll",Ee)},[]),(0,m.useLayoutEffect)(()=>{const lt=fe.current,Ee=mye({previousPathname:ne.current,pathname:T.pathname,navigationType:A,state:T.state});ne.current=T.pathname;const Xe=A==="POP",Ae=Xe?X.current.recall(T.key):0;if(re.current=T.key,Xe){Q3(lt,Ae);const De=requestAnimationFrame(()=>Q3(lt,Ae));return()=>cancelAnimationFrame(De)}Ee&&pye(lt)},[T.key,T.pathname,T.state,A]),(0,t.jsx)(uye,{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)(bCe,{}),(0,t.jsx)(vCe,{devServer:de?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",c?"w-full":"flex overflow-clip"),children:[c&&s&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>n(!1),"onClick"),"aria-label":"Close sidebar"}),c?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",s?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ke?(0,t.jsx)(Z2,{children:ue}):(0,t.jsx)(oZ,{children:e})})}),(0,t.jsx)(Rse,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}):(0,t.jsxs)(Uot,{open:s,collapsed:Ie?!1:i,peeking:Ie?!1:o,resizable:!0,onPanelMouseEnter:Ie?void 0:tt,onPanelMouseLeave:Ie?void 0:Pe,onPanelFocusCapture:!Ie&&i?Ce:void 0,onPanelBlurCapture:!Ie&&i?He:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Ie?(0,t.jsx)(Z2,{children:ue}):(0,t.jsx)(oZ,{children:e})}),(0,t.jsx)(Rse,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}),!c&&Ue&&!be?(0,t.jsx)(Z2,{className:"w-60 shrink-0",children:ue}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",c?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{"data-slot":c?"mobile-topbar":void 0,className:W(!c&&U&&"hidden",c&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(g6,{mobile:c,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(fZ,{}),c&&B?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(Cje,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&U&&"streamlined-task-detail-surface"),children:[!c&&be?(0,t.jsx)(Z2,{className:"w-60 shrink-0 bg-background",children:ue}):null,(0,t.jsxs)("div",{className:W(!c&&U?"flex min-w-0 flex-1 flex-col":"contents"),children:[!c&&U?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(g6,{mobile:!1,onNavigateHome:r(()=>R("/dashboard"),"onNavigateHome")}),(0,t.jsx)(fZ,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:fe,tabIndex:-1,style:c?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",!c&&U&&"pt-0 md:pt-0",c?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:te?(0,t.jsx)(zu,{scope:"invalid_company_prefix",requestedPrefix:k??v?.issuePrefix}):(0,t.jsx)(kCe,{children:(0,t.jsx)(mb,{})})})]}),(0,t.jsx)(Oje,{taskDetailLayout:!c&&U})]})]})]}),c&&(0,t.jsx)(gCe,{visible:oe}),(0,t.jsx)(Fje,{}),(0,t.jsx)(vwe,{}),(0,t.jsx)(cCe,{}),(0,t.jsx)(mCe,{}),(0,t.jsx)(hCe,{}),(0,t.jsx)(pCe,{open:G,onOpenChange:Y}),(0,t.jsx)(fCe,{}),(0,t.jsx)(mot,{health:de}),(0,t.jsx)(xCe,{localTrusted:de?.deploymentMode==="local_trusted"})]})})}r(klt,"Layout$1");var QCe=(0,m.createContext)(!1);function Nlt({children:e}){return(0,t.jsx)(QCe.Provider,{value:!0,children:e})}r(Nlt,"SidebarNavExpandedProvider");function Slt(){return(0,m.useContext)(QCe)}r(Slt,"useSidebarNavExpanded");function si({to:e,label:s,icon:n,iconNode:a,end:i,className:o,labelClassName:l,badge:c,badgeTone:d="default",badgeLabel:u,textBadge:h,textBadgeTone:p="default",alert:f=!1,liveCount:x,active:b,trailing:v,trailingLabel:j,liveAccessory:N}){const{isMobile:w,setSidebarOpen:k,collapsed:S,peeking:C}=qa(),I=Slt(),R=S&&!C&&!I,T=c!=null&&c>0,A=x!=null&&x>0,D=A?`${x} live`:T?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,M=!R||!D&&!j?void 0:`${s}${D?`, ${D}`:""}${j?`, ${j}`:""}`,B=(0,t.jsxs)(hb,{to:e,state:Qf,end:i,"aria-label":M,onClick:r(()=>{w&&k(!1)},"onClick"),className:r(({isActive:E})=>W("flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium transition-colors",b??E?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground",o),"className"),children:[(0,t.jsxs)("span",{className:"relative shrink-0",children:[a??(n?(0,t.jsx)(n,{className:"h-4 w-4"}):null),f&&(0,t.jsx)("span",{className:"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-(--shadow-extract-12)","aria-hidden":"true"}),R&&!f&&A&&(0,t.jsxs)("span",{className:"absolute -right-0.5 -top-0.5 flex h-2 w-2","aria-hidden":"true",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-blue-600 dark:bg-blue-400 shadow-(--shadow-extract-12)"})]}),R&&!f&&!A&&T&&(0,t.jsx)("span",{className:W("absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full shadow-(--shadow-extract-12)",d==="danger"?"bg-red-600":d==="warning"?"bg-amber-500":"bg-primary"),"aria-hidden":"true"})]}),(0,t.jsx)("span",{className:R?By:W("min-w-0 flex-1 truncate",l),children:s}),!R&&v,!R&&h&&(0,t.jsx)(ct,{variant:"ghost",className:W("ml-auto px-1.5 text-(length:--text-nano) leading-none",p==="amber"?"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground"),children:h}),!R&&(A||N)&&(0,t.jsxs)("span",{className:"ml-auto flex items-center gap-1.5",children:[N,A&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("span",{className:"relative flex h-2 w-2",children:[(0,t.jsx)("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-600 dark:bg-blue-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-600 dark:bg-blue-400"})]}),(0,t.jsxs)("span",{className:"text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400",children:[x," live"]})]})]}),!R&&T&&(0,t.jsx)(ct,{variant:"ghost",className:W("ml-auto px-1.5 leading-none",d==="danger"?"bg-red-600/90 text-red-50":d==="warning"?"bg-amber-500/90 text-amber-50":"bg-primary text-primary-foreground"),children:c})]});return R?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("div",{children:B})}),(0,t.jsx)(Un,{side:"right",children:s})]}):B}r(si,"SidebarNavItem");var Clt=3,Ese=12e4,_lt=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Yj(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Yj,"agentTimestamp");function Pse(e,s){if(s==="top")return e;const n=[...e];return s==="alphabetical"?(n.sort((a,i)=>a.name.localeCompare(i.name,void 0,{sensitivity:"base"})),n):(n.sort((a,i)=>{const o=Yj(i,"lastHeartbeatAt")-Yj(a,"lastHeartbeatAt");if(o!==0)return o;const l=Yj(i,"updatedAt")-Yj(a,"updatedAt");if(l!==0)return l;const c=Yj(i,"createdAt")-Yj(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r(Pse,"sortAgents");var Ilt="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function Alt({activeAgentId:e,activeTab:s,agent:n,disabled:a,isMobile:i,leaving:o,onLeaveAgent:l,onPauseResume:c,rail:d,runCount:u,setSidebarOpen:h,builtInStatus:p,starred:f=!1,onToggleStar:x,starPending:b=!1}){const v=Xl(n),j=s?`${Cm(n)}/${s}`:Cm(n),N=`${Cm(n)}/configuration`,w=e===v,k=n.status==="paused",S=k&&n.pauseReason==="budget",C=n.orgChainHealth?.status==="invalid_org_chain",I=k?"Resume agent":"Pause agent",R=a||n.status==="pending_approval"||S||k&&C,T=a?"Updating...":S?"Budget paused":k&&C?"Invalid org chain":I,A=p==="needs_setup"||p==="pending_approval",D=[A?`Built-in agent ${p.replace(/_/g," ")}`:null,C?"Invalid reporting chain":null].filter(Boolean).join(", ")||void 0,M=(0,t.jsx)(si,{to:j,label:n.name,iconNode:(0,t.jsx)(gr,{agent:n,size:16,className:"shrink-0 h-4 w-4"}),active:w,liveCount:u,labelClassName:A?"min-w-(--sz-4_5rem) flex-initial":void 0,className:W("min-w-0 flex-1",f&&!i?"pr-14":"pr-8"),trailing:A||C?(0,t.jsxs)("span",{className:"ml-1 flex shrink-0 items-center gap-1",children:[A?(0,t.jsx)(uk,{status:p,compact:!0}):null,C?(0,t.jsx)(Es,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):null]}):void 0,trailingLabel:D,liveAccessory:n.pauseReason==="budget"?(0,t.jsx)(XI,{title:"Agent paused by budget"}):void 0});return d?M:(0,t.jsxs)("div",{className:"group/agent relative flex items-center",children:[M,f&&!i&&x?(0,t.jsx)("span",{className:"absolute right-10 top-1/2 -translate-y-1/2",children:(0,t.jsx)(bb,{size:"row",quiet:!0,starred:!0,pending:b,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:Ilt})}):null,(0,t.jsxs)(Zr,{children:[(0,t.jsx)(Xr,{asChild:!0,children:(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:W("absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 transition-opacity data-[state=open]:pointer-events-auto data-[state=open]:opacity-100",i?"opacity-100":"pointer-events-none opacity-0 group-hover/agent:pointer-events-auto group-hover/agent:opacity-100 group-focus-within/agent:pointer-events-auto group-focus-within/agent:opacity-100"),"aria-label":`Open actions for ${n.name}`,children:(0,t.jsx)(Ri,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(ea,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ls,{onClick:r(()=>{b||x(n,!f)},"onClick"),disabled:b,children:[b?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(yp,{className:W("size-4",f&&"fill-amber-500 text-amber-500")}),(0,t.jsx)("span",{children:f?"Remove from starred":"Star agent"})]}),(0,t.jsx)(ni,{})]}):null,(0,t.jsx)(ls,{asChild:!0,children:(0,t.jsxs)(Ke,{to:N,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(gc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{R||c(n,k?"resume":"pause")},"onClick"),disabled:R,title:S?"Agent was paused by budget limits":void 0,children:[k?(0,t.jsx)(HI,{className:"size-4"}):(0,t.jsx)(Td,{className:"size-4"}),(0,t.jsx)("span",{children:T})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(Alt,"SidebarAgentItem");function Tlt({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=Pt(),{selectedCompanyId:u}=ps(),{openNewAgent:h}=Yo(),{isMobile:p,setSidebarOpen:f,collapsed:x,peeking:b}=qa(),v=x&&!b,{pushToast:j}=da(),N=na(),{data:w}=ee({queryKey:P.agents.list(u),queryFn:r(()=>$t.list(u),"queryFn"),enabled:!!u}),{data:k}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:!!u}),S=k?.enableBuiltInAgents===!0,{data:C}=ee({queryKey:P.builtInAgents.list(u),queryFn:r(()=>Zh.list(u),"queryFn"),enabled:!!u&&S}),I=(0,m.useMemo)(()=>{const be=new Map;if(!S)return be;for(const Ie of C??[])Ie.agentId&&be.set(Ie.agentId,Ie.status);return be},[C,S]),{data:R}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),T=Yf(u),A=Rg(u),D=P.liveRuns(u),M=No({companyId:u,resourceKey:"live-runs",queryKey:D,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:B,dataUpdatedAt:E}=ee({queryKey:D,queryFn:r(()=>Jr.liveRunsForCompany(u),"queryFn"),enabled:M.enabled,refetchInterval:M.refetchInterval});So(M,B,E);const z=(0,m.useMemo)(()=>{const be=new Map;for(const Ie of B??[])be.set(Ie.agentId,(be.get(Ie.agentId)??0)+1);return be},[B]),$=(0,m.useMemo)(()=>{const be=new Set;for(const[Ie,Ue]of z)Ue>0&&be.add(Ie);return be},[z]),q=(0,m.useMemo)(()=>(w??[]).filter(be=>be.status!=="terminated"&&(!T.isSuccess||Of(T.data,"agent",be.id)!=="left")),[w,T.data,T.isSuccess]),U=R?.user?.id??R?.session?.userId??null,O=(0,m.useMemo)(()=>u?kye(u,U):null,[U,u]),[K,H]=(0,m.useState)(()=>O?mk(O):"top"),{orderedAgents:Z}=Cye({agents:q,companyId:u,userId:U}),se=(0,m.useMemo)(()=>Pse(Z,K),[Z,K]),ne=(0,m.useMemo)(()=>new Set(se.map(be=>be.id)),[se]);(0,m.useEffect)(()=>{const be=Date.now();for(const Ie of $)c.current.set(Ie,be);for(const Ie of c.current.keys())ne.has(Ie)||c.current.delete(Ie)},[$,ne]);const fe=(0,m.useMemo)(()=>{const be=Date.now(),Ie=c.current;return se.filter(Ue=>{if((z.get(Ue.id)??0)>0)return!0;const at=Ie.get(Ue.id);return at!==void 0&&be-at<=Ese})},[z,o,se]),X=fe.length>0,re=e?X?fe:se.slice(0,Clt):se,oe=e&&se.length>0,G=N.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Y=G?.[1]??null,Q=G?.[2]??null;(0,m.useEffect)(()=>{if(!O){H("top");return}H(mk(O))},[O]),(0,m.useEffect)(()=>{if(!O)return;const be=r(Ue=>{Ue.key===O&&H(mk(O))},"onStorage"),Ie=r(Ue=>{const at=Ue.detail;!at||at.storageKey!==O||H(at.sortMode)},"onCustomEvent");return window.addEventListener("storage",be),window.addEventListener(b_,Ie),()=>{window.removeEventListener("storage",be),window.removeEventListener(b_,Ie)}},[O]),(0,m.useEffect)(()=>{if(!e)return;const be=Date.now();let Ie=null;for(const at of se){if((z.get(at.id)??0)>0)continue;const dt=c.current.get(at.id);if(dt===void 0)continue;const de=dt+Ese;de<be||(Ie=Ie===null?de:Math.min(Ie,de))}if(Ie===null)return;const Ue=window.setTimeout(()=>{l(at=>at+1)},Math.max(0,Ie-be+1));return()=>{window.clearTimeout(Ue)}},[e,se,z,o]);const te=(0,m.useCallback)(be=>{const Ie=be==="alphabetical"||be==="recent"?be:"top";H(Ie),O&&Sye(O,Ie)},[O]),ae=je({mutationFn:r(({agent:be,action:Ie})=>Ie==="pause"?$t.pause(be.id,u??void 0):$t.resume(be.id,u??void 0),"mutationFn"),onMutate:r(({agent:be})=>{i(Ie=>{const Ue=new Set(Ie);return Ue.add(be.id),Ue})},"onMutate"),onSuccess:r(async(be,{agent:Ie,action:Ue})=>{u&&await Promise.all([d.invalidateQueries({queryKey:P.agents.list(u)}),d.invalidateQueries({queryKey:P.liveRuns(u)}),d.invalidateQueries({queryKey:P.dashboard(u)})]),await Promise.all([d.invalidateQueries({queryKey:P.agents.detail(Ie.id)}),d.invalidateQueries({queryKey:P.agents.detail(Xl(Ie))})]),j({title:Ue==="pause"?"Agent paused":"Agent resumed",body:Ie.name,tone:"success"})},"onSuccess"),onError:r((be,{agent:Ie,action:Ue})=>{j({title:Ue==="pause"?"Could not pause agent":"Could not resume agent",body:be instanceof Error?be.message:Ie.name,tone:"error"})},"onError"),onSettled:r((be,Ie,{agent:Ue})=>{i(at=>{const dt=new Set(at);return dt.delete(Ue.id),dt})},"onSettled")}),le=(0,m.useCallback)(be=>A.mutate({resourceType:"agent",resourceId:be.id,resourceName:be.name,state:"left"}),[A]),he=(0,m.useCallback)(be=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===be.id,[A.isPending,A.variables]),ce=(0,m.useCallback)((be,Ie)=>A.mutate({resourceType:"agent",resourceId:be.id,resourceName:be.name,starred:Ie}),[A]),ge=(0,m.useCallback)(be=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===be.id&&A.variables.starred!==void 0,[A.isPending,A.variables]),me=(0,m.useMemo)(()=>new Set(LM(T.data,"agent")),[T.data]),ie=(0,m.useMemo)(()=>Pse(q.filter(be=>me.has(be.id)),"alphabetical"),[q,me]),ue=(0,m.useMemo)(()=>re.filter(be=>!me.has(be.id)),[re,me]),ke=r((be,Ie)=>(0,t.jsx)(Alt,{activeAgentId:Y,activeTab:Q,agent:be,disabled:a.has(be.id),isMobile:p,leaving:he(be),onLeaveAgent:le,onPauseResume:r((Ue,at)=>ae.mutate({agent:Ue,action:at}),"onPauseResume"),rail:v,runCount:z.get(be.id)??0,setSidebarOpen:f,builtInStatus:I.get(be.id),starred:Ie||gb(T.data,"agent",be.id),onToggleStar:ce,starPending:ge(be)},be.id),"renderAgentRow");return(0,t.jsxs)(tg,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:yn,onClick:h},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Ho,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:_lt,radioValue:K,onRadioValueChange:te},children:[ie.map(be=>ke(be,!0)),ue.map(be=>ke(be,!1)),oe&&(()=>{const be=(0,t.jsxs)(Ke,{to:"/agents/all",state:Qf,"aria-label":v?"See all agents":void 0,onClick:r(()=>{p&&f(!1)},"onClick"),className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Ho,{className:"shrink-0 h-4 w-4"}),(0,t.jsx)("span",{className:v?"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none":void 0,children:"See all agents"})]});return v?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:be}),(0,t.jsx)(Un,{side:"right",children:"See all agents"})]}):be})()]})}r(Tlt,"SidebarAgents");var Rlt="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function Elt(){const{selectedCompanyId:e}=ps(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=qa(),o=a&&!i,l=na(),{data:c}=ee({queryKey:P.projects.list(e),queryFn:r(()=>pa.list(e),"queryFn"),enabled:!!e}),d=Yf(e),u=Rg(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(LM(d.data,"project"));if(v.size===0)return[];const j=new Map((c??[]).map(N=>[N.id,N]));return Array.from(v).map(N=>j.get(N)).filter(N=>!!N).sort((N,w)=>N.name.localeCompare(w.name,void 0,{sensitivity:"base"}))},[d.data,d.isSuccess,c]),f=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,starred:!1}),[u]),x=(0,m.useCallback)(v=>u.mutate({resourceType:"project",resourceId:v.id,resourceName:v.name,state:"left"}),[u]),b=(0,m.useCallback)(v=>u.isPending&&u.variables?.resourceType==="project"&&u.variables.resourceId===v.id,[u.isPending,u.variables]);return!d.isSuccess||p.length===0?null:(0,t.jsx)("div",{className:"flex flex-col gap-0.5","aria-label":"Starred projects",children:p.map(v=>{const j=cg(v),N=h===j||h===v.id,w=b(v),k=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=gb(d.data,"project",v.id),I=(0,t.jsxs)(hb,{to:`/projects/${j}/issues`,state:Qf,onClick:r(()=>{s&&n(!1)},"onClick"),className:W("flex min-w-0 flex-1 items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 pr-8 text-(length:--text-compact) font-medium transition-colors",!o&&"pl-6",N?"bg-accent text-foreground":"text-foreground/80 hover:bg-accent/50 hover:text-foreground"),children:[(0,t.jsx)(Em,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?By:"flex-1 truncate",children:v.name}),!o&&v.pauseReason==="budget"?(0,t.jsx)(XI,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:I})}),(0,t.jsx)(Un,{side:"right",children:v.name})]}):I,!o&&!s?(0,t.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:(0,t.jsx)(bb,{size:"row",quiet:!0,starred:C,pending:k,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:Rlt})}):null,!o&&s?(0,t.jsxs)(Zr,{children:[(0,t.jsx)(Xr,{asChild:!0,children:(0,t.jsx)(L,{variant:"ghost",size:"icon-xs",className:"absolute right-3 top-1/2 h-6 w-6 -translate-y-1/2 opacity-100","aria-label":`Open actions for ${v.name}`,children:(0,t.jsx)(Ri,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(ea,{align:"end",className:"w-48",children:[(0,t.jsxs)(ls,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[k?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(yp,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(ni,{}),(0,t.jsxs)(ls,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(rt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:"Leave project"})]})]})]}):null]},v.id)})})}r(Elt,"SidebarStarredProjects");var Plt="size-5 shrink-0 rounded-md text-(length:--text-micro)",Mlt="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",Dlt="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",rO="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 YCe({company:e,inPopover:s=!1}){return(0,t.jsx)(tS,{companyName:e.name,logoUrl:e.logoUrl,className:s?Mlt:Plt})}r(YCe,"WorkspaceIcon");function Llt({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=UN({id:e.id,disabled:!s});return(0,t.jsxs)(ls,{ref:c,style:{transform:LN.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(Dlt,s&&"cursor-grab",h&&"opacity-80"),children:[(0,t.jsx)(YCe,{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)(IM,{className:"size-4","aria-hidden":"true"})}):(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:n?(0,t.jsx)(gs,{className:"size-4 text-foreground"}):null})]})}r(Llt,"SortableCompanyItem");function $lt(e={}){return(0,t.jsx)(yje,{...e,children:(0,t.jsx)(Olt,{...e})})}r($lt,"SidebarCompanyMenu");function Olt({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}=Yo(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=qa(),j=b&&!v,N=na(),w=Mn(),k=e??n,S=s??a,C=BN(Mf(m7,{activationConstraint:{distance:8}}),Mf(Wfe,{activationConstraint:{delay:180,tolerance:6}})),I=(0,m.useMemo)(()=>l.filter(ne=>ne.status!=="archived"),[l]),{data:R}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),T=R?.user?.id??R?.session?.userId??null,{orderedCompanies:A,persistOrder:D}=vje({companies:I,userId:T}),{hidden:M,loaded:B}=cu(),E=B&&!dg(M,"company.members")&&!dg(M,"company.invites"),z="company",$=c?.name??null,q=!!$c(),U=eS({onSignedOut:K});function O(ne){ne||o(!1),S(ne)}r(O,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function H(ne){const fe=N.pathname.split("/")[1]?.toUpperCase(),X=I.some(oe=>oe.issuePrefix.toUpperCase()===fe),re=ne.id!==c?.id&&(N.pathname.startsWith("/instance/")||X);d(ne.id),S(!1),f&&x(!1),re&&w(`/${ne.issuePrefix}/dashboard`)}r(H,"selectCompany");function Z(){q||(S(!1),f&&x(!1),p({initialStep:1}))}r(Z,"addCompany");const se=(0,m.useCallback)(ne=>{const{active:fe,over:X}=ne;if(!X||fe.id===X.id)return;const re=A.map(Y=>Y.id),oe=re.indexOf(fe.id),G=re.indexOf(X.id);oe===-1||G===-1||D(gM(re,oe,G))},[A,D]);return(0,t.jsxs)(Zr,{open:k,onOpenChange:O,children:[(0,t.jsx)(Xr,{asChild:!0,children:(0,t.jsxs)(L,{variant:"ghost",className:"h-9 min-w-0 flex-1 justify-start gap-2 px-4 text-left hover:bg-accent/50 hover:text-foreground has-[>svg]:px-4 dark:hover:bg-accent/50","aria-label":$?`Open ${$} ${z} switcher`:`Open ${z} switcher`,children:[(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c?(0,t.jsx)(YCe,{company:c}):null,(0,t.jsx)("span",{className:W("min-w-0 truncate text-sm font-bold text-foreground",j&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),title:$??void 0,children:$??`Select ${z}`})]}),!j&&(0,t.jsx)(jM,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(ea,{align:"start",sideOffset:8,className:"ml-2 w-(--organization-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"flex h-(--organization-popover-header-height) items-center justify-between gap-2 px-3.5",children:[(0,t.jsx)(pb,{className:"p-0 text-(length:--text-compact) font-semibold text-foreground",children:"Organizations"}),(0,t.jsx)("button",{type:"button",onClick:r(ne=>{ne.preventDefault(),ne.stopPropagation(),o(fe=>!fe)},"onClick"),className:"rounded px-1.5 py-0.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:i?"Done":"Edit"})]}),(0,t.jsxs)("div",{className:"flex max-h-96 flex-col gap-0.5 overflow-y-auto px-2.5 pb-2 pt-1",children:[(0,t.jsx)(FN,{sensors:C,collisionDetection:MI,onDragEnd:se,children:(0,t.jsx)(zN,{items:A.map(ne=>ne.id),strategy:$I,children:A.map(ne=>(0,t.jsx)(Llt,{company:ne,isEditing:i,isSelected:ne.id===c?.id,onSelect:H},ne.id))})}),A.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ls,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(ls,{onSelect:r(ne=>{ne.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(_i,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(ls,{disabled:!0,children:"No companies"}):null]}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5 border-t border-border px-2.5 pb-2.5 pt-2",children:[!q&&(0,t.jsxs)(ls,{onClick:Z,className:rO,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(yn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),E?(0,t.jsx)(ls,{asChild:!0,disabled:i,className:rO,children:(0,t.jsxs)(Ke,{to:"/company/settings/invites",onClick:r(ne=>{if(i){ne.preventDefault();return}K()},"onClick"),children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Gf,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:$?`Invite people to ${$}`:"Invite people"})]})}):null,R?.session?(0,t.jsxs)(ls,{className:rO,onClick:r(()=>U.mutate(),"onClick"),disabled:i||U.isPending,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(Tp,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:U.isPending?"Signing out...":"Sign out"})]}):null]})]})]})}r(Olt,"BuiltinCompanyMenu");function Mse(){const{openNewIssue:e}=Yo(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=ps(),{collapsed:c,peeking:d}=qa(),u=c&&!d,h=BM(o),{data:p,isFetched:f}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}),x=P.liveRuns(o),b=No({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:j}=ee({queryKey:x,queryFn:r(()=>Jr.liveRunsForCompany(o),"queryFn"),enabled:b.enabled,refetchInterval:b.refetchInterval});So(b,v,j);const N=v?.length??0,w=p?.enableIsolatedWorkspaces===!0,k=p?.enableApps===!0,S=p?.enablePipelines===!0,C=p?.enableStatusCards===!0,I=!f,R=p?.enableGoalsSidebarLink===!0,T=p?.enableDecisions===!0,{data:A}=ee({queryKey:P.attention(o),queryFn:r(()=>JN.list(o),"queryFn"),enabled:!!o&&T,refetchInterval:6e4}),D=Qye(A),M=p?.enableCases===!0,B=!0,E=p?.enableConferenceRoomChat===!0,z={companyId:o,companyPrefix:l?.issuePrefix??null};return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex items-center gap-1 px-3 h-12 shrink-0",children:(0,t.jsx)($lt,{})}),(0,t.jsxs)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 pointer-coarse:gap-3 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(()=>{const $=(0,t.jsxs)("button",{onClick:r(()=>e(),"onClick"),"data-slot":"icon-button","aria-label":u?"New Task":void 0,className:"flex items-center gap-2.5 mx-2 rounded-lg px-2 py-1.5 pointer-coarse:py-1 text-(length:--text-compact) font-medium text-foreground/80 hover:bg-accent/50 hover:text-foreground transition-colors",children:[(0,t.jsx)(f_,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?By:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:$}),(0,t.jsx)(Un,{side:"right",children:"New Task"})]}):$})(),(0,t.jsx)(si,{to:"/search",label:"Search",icon:oa}),(0,t.jsx)(si,{to:"/dashboard",label:"Dashboard",icon:eg,liveCount:N}),(0,t.jsx)(si,{to:"/inbox",label:"Inbox",icon:hd,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),T?(0,t.jsx)(si,{to:"/decisions",label:"Decisions",icon:Hy,badge:D,badgeLabel:"decisions"}):null,C?(0,t.jsx)(si,{to:"/status",label:"Status",icon:QN,textBadge:"beta"}):null,E?(0,t.jsx)(si,{to:"/board-chat",label:"Conference Room",icon:pbe}):null]}),(0,t.jsxs)(tg,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(si,{to:"/issues",label:"Tasks",icon:Mu}),M?(0,t.jsx)(si,{to:"/cases",label:"Cases",icon:zl,textBadge:"beta"}):null,(0,t.jsx)(si,{to:"/routines",label:"Routines",icon:Ou}),S?(0,t.jsx)(si,{to:"/pipelines",label:"Pipelines",icon:io}):null,R?(0,t.jsx)(si,{to:"/goals",label:"Goals",icon:vp}):I?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(si,{to:"/artifacts",label:"Artifacts",icon:Th}),(0,t.jsx)(si,{to:"/skills",label:"Skills",icon:xc}),w?(0,t.jsx)(si,{to:"/workspaces",label:"Workspaces",icon:io}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(si,{to:"/projects",label:"Projects",icon:Go}),(0,t.jsx)(Elt,{})]}),(0,t.jsx)(Sp,{slotTypes:["sidebar"],context:z,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(ZN,{placementZones:["sidebar"],context:z,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(Tlt,{streamlined:B}),(0,t.jsxs)(tg,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(si,{to:"/org",label:"Org",icon:hy}),k?(0,t.jsx)(si,{to:"/apps",label:"Connectors",icon:H3}):null,(0,t.jsx)(si,{to:"/timeline",label:"Timeline",icon:b0}),(0,t.jsx)(si,{to:"/costs",label:"Costs",icon:mp}),(0,t.jsx)(si,{to:"/activity",label:"Activity",icon:Zl}),(0,t.jsx)(si,{to:"/company/settings",label:"Settings",icon:iu})]}),(0,t.jsx)(Sp,{slotTypes:["sidebarPanel"],context:z,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(Mse,"Sidebar");function Flt(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Flt,"isSandboxProviderOnly");function Blt(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),{hidden:i}=cu(),o=r(f=>!i.has(f),"showPage"),l=o("instance.plugins"),c=!!$c(),{slots:d}=gd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:u}=ee({queryKey:s?P.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await p9.get(s)}catch(f){if(f instanceof dn&&(f.status===401||f.status===403))return null;throw f}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:h}=ee({queryKey:P.plugins.all,queryFn:r(()=>Al.list(),"queryFn"),enabled:l}),p=(h??[]).filter(f=>!Flt(f));return(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsx)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:(0,t.jsxs)(Ke,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Uu,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:e?.name??"Company"})]})}),(0,t.jsx)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2",children:(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(si,{to:"/company/settings",label:"General",icon:Ku,end:!0}),o("instance.profile")&&(0,t.jsx)(si,{to:"/company/settings/instance/profile",label:"Profile",icon:EM,end:!0}),o("company.members")&&(0,t.jsx)(si,{to:"/company/settings/members",label:"Members",icon:Ho,badge:u?.joinRequests??0,end:!0}),d.filter(f=>f.routePath).map(f=>(0,t.jsx)(si,{to:`/company/settings/${f.routePath}`,label:f.displayName,icon:Zx,end:!0},`${f.pluginKey}:${f.id}`)),o("company.invites")&&(0,t.jsx)(si,{to:"/company/settings/invites",label:"Invites",icon:Nqe,end:!0}),o("company.secrets")&&(0,t.jsx)(si,{to:"/company/settings/secrets",label:"Secrets",icon:Si,end:!0}),o("instance.environments")&&(0,t.jsx)(si,{to:"/company/settings/instance/environments",label:"Environments",icon:vbe,end:!0}),o("instance.access")&&(0,t.jsx)(si,{to:"/company/settings/instance/access",label:"Access",icon:EI,end:!0}),o("instance.heartbeats")&&(0,t.jsx)(si,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:au,end:!0}),o("company.export")&&(0,t.jsx)(si,{to:"/company/export",label:"Export",icon:po}),!c&&o("company.import")&&(0,t.jsx)(si,{to:"/company/import",label:"Import",icon:py,end:!0}),o("instance.experimental")&&(0,t.jsx)(si,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Dm}),l&&(0,t.jsx)(si,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Zx}),l&&p.length>0?(0,t.jsx)("div",{className:"ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3",children:p.map(f=>(0,t.jsx)(hb,{to:`${ep}/plugins/${f.id}`,state:Qf,className:r(({isActive:x})=>["rounded-md px-2 py-1.5 text-xs transition-colors",x?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50 hover:text-foreground"].join(" "),"className"),children:f.manifestJson.displayName??f.packageName},f.id))}):null,o("instance.adapters")&&(0,t.jsx)(si,{to:"/company/settings/instance/adapters",label:"Adapters",icon:ym})]})})]})}r(Blt,"CompanySettingsSidebar");function zlt(){const{pathname:e}=na(),{selectedCompany:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=Aje(),{enabled:o}=zM(),l=v9.filter(d=>!Ije(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(J7,{});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|reviews|conversations|activity|approvals|audit))?\/?$/);return c?(0,t.jsx)(_je,{endpointId:c[1],NavItem:si}):(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:[(0,t.jsxs)(Ke,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Uu,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:s?.name??"Company"})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 px-2 py-1",children:[(0,t.jsx)(uX,{className:"h-4 w-4 text-muted-foreground shrink-0"}),(0,t.jsx)("span",{className:"flex-1 truncate text-sm font-bold text-foreground",children:"Connectors"})]})]}),(0,t.jsxs)("nav",{className:"flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2",children:[(0,t.jsx)("div",{className:"px-3 pb-1 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:"Connectors"}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(si,{to:"/apps",label:"Browse",icon:x_,end:!0}),(0,t.jsx)(si,{to:"/apps/review",label:"Review",icon:YN,badge:i>0?i:void 0,badgeTone:"warning",badgeLabel:"waiting for your OK"})]}),(0,t.jsx)("div",{className:"px-3 pb-1 pt-4 text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground",children:"Developer"}),(0,t.jsx)("p",{className:"px-3 pb-1.5 text-(length:--text-micro) leading-snug text-muted-foreground/70",children:"Advanced setup for developers. Most teams never open this."}),(0,t.jsxs)("div",{className:"flex flex-col gap-0.5",children:[(0,t.jsx)(si,{to:"/apps/connections",label:"Connections",icon:uX,end:!0}),l.map(d=>(0,t.jsx)(si,{to:F0(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(zlt,"AppsSidebar");function Dse(e){const{selectedCompanyId:s}=ps(),{isMobile:n,setSidebarOpen:a}=qa(),i=ee({queryKey:P.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>Zt.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=ee({queryKey:P.tools.applications(s??"__none__"),queryFn:r(()=>Zt.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=ee({queryKey:P.tools.connections(s??"__none__"),queryFn:r(()=>Zt.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=ee({queryKey:P.apps.gallery(s??"__none__"),queryFn:r(()=>Zt.listGallery(s),"queryFn"),enabled:!!s}),d=ee({queryKey:P.apps.attention(s??"__none__"),queryFn:r(()=>Zt.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(N=>N.id===e.applicationId):null,p=Klt(e.kind==="application"?(l.data?.connections??[]).filter(N=>N.applicationId===e.applicationId):[]),f=u?$f(u):h?.name??"App",x=Ult(c.data?.apps??[],u,h??void 0),b=u?.id??p?.id??null,v=b?d.data?.apps.find(N=>N.connection.id===b):null,j=(v?.pendingActionRequestCount??0)+((v?.quarantinedCatalogEntryCount??0)>0?1:0);return(0,t.jsxs)("aside",{className:"flex h-full min-h-0 w-full flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 px-3 py-3",children:[(0,t.jsxs)(Ke,{to:"/apps/connections",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Uu,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{className:"truncate",children:"All apps"})]}),(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2 px-2 py-1",children:[(0,t.jsx)(al,{name:f,logoUrl:sA(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:qM.map(N=>(0,t.jsx)(si,{to:qlt(e,N.key),label:N.label,icon:N.icon,end:!0,badge:N.key==="review"&&j>0?j:void 0,badgeTone:"danger",badgeLabel:"needing review"},N.key))})})]})}r(Dse,"AppDetailSidebar");function qlt(e,s){return e.kind==="connection"?vm(e.connectionId,s):C1(e.applicationId,s)}r(qlt,"tabHref");function Ult(e,s,n){if(n?.applicationKey){const i=e.find(o=>mc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>sg(i).toLowerCase()===a)??e.find(i=>mc(i)===a)??null:null}r(Ult,"galleryEntryFor$1");function Klt(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(Klt,"latestArchivedConnection$1");function aO({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(aO,"CrumbIdentifier");function Wlt({context:e}){const{slots:s}=gd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=x9({placementZones:["globalToolbarButton"],companyId:e.companyId,enabled:!!e.companyId});return(0,t.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-1 pl-2 empty:hidden",children:[s.length>0?(0,t.jsx)(Sp,{slotTypes:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null,n.length>0?(0,t.jsx)(ZN,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(Wlt,"GlobalToolbar");function Vlt(){const{breadcrumbs:e,mobileToolbar:s}=Bn(),{toggleSidebar:n,isMobile:a}=qa(),{selectedCompanyId:i,selectedCompany:o}=ps(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(Wlt,{context:l});if(a&&s)return(0,t.jsx)("div",{className:"border-b border-border px-2 h-12 shrink-0 flex items-center",children:s});if(e.length===0)return(0,t.jsx)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:c});const d=a&&(0,t.jsx)(L,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(abe,{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)(aO,{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)(y9,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(j9,{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)(r5,{}),(0,t.jsx)(_1,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(k_,{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)(aO,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(k_,{className:"truncate",children:u.label}):(0,t.jsx)(n5,{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)(aO,{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(Vlt,"BreadcrumbBar");var eT=240,k6=208,N6=420,Lse=16;function U5(e){return Math.min(N6,Math.max(k6,e))}r(U5,"clampSidebarWidth");function $se(e){if(typeof window>"u")return eT;try{const s=window.localStorage.getItem(e);if(!s)return eT;const n=Number.parseInt(s,10);return Number.isFinite(n)?U5(n):eT}catch{return eT}}r($se,"readStoredSidebarWidth");function Ose(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(U5(s)))}catch{}}r(Ose,"writeStoredSidebarWidth");function Hlt({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)(()=>$se(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=$se(o);v.current=E,f(E)},[o]);const N=s?p:0,w=s?n?64:N:0,k=s?n&&!a?64:N:0,S=k>w,C=i&&s&&!n,I=(0,m.useMemo)(()=>({width:`${w}px`}),[w]),R=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),T=(0,m.useCallback)(E=>{const z=U5(E);v.current=z,f(z),Ose(o,z)},[o]),A=(0,m.useCallback)(E=>{C&&(E.preventDefault(),E.currentTarget.setPointerCapture(E.pointerId),j.current={startX:E.clientX,startWidth:v.current},b(!0))},[C]),D=(0,m.useCallback)(E=>{if(!j.current)return;const z=U5(j.current.startWidth+E.clientX-j.current.startX);v.current=z,f(z)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),Ose(o,v.current))},[o]),B=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),T(p-Lse)):E.key==="ArrowRight"?(E.preventDefault(),T(p+Lse)):E.key==="Home"?(E.preventDefault(),T(k6)):E.key==="End"&&(E.preventDefault(),T(N6)))},[C,T,p]);return(0,t.jsx)("div",{className:W("relative h-full shrink-0",l),style:I,children:(0,t.jsxs)("div",{className:W("absolute inset-y-0 left-0 flex flex-col overflow-hidden",S?"z-30 border-r border-border bg-background shadow-lg":"z-0"),style:R,"data-sidebar-overlay":S?"":void 0,onMouseEnter:c,onMouseLeave:d,onFocusCapture:u,onBlurCapture:h,children:[e,C?(0,t.jsx)("div",{role:"separator","aria-label":"Resize sidebar","aria-orientation":"vertical","aria-valuemin":k6,"aria-valuemax":N6,"aria-valuenow":p,tabIndex:0,className:W("absolute inset-y-0 right-0 z-20 w-3 cursor-col-resize touch-none outline-none","before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-transparent before:transition-colors","hover:before:bg-border focus-visible:before:bg-ring",x&&"before:bg-ring"),onPointerDown:A,onPointerMove:D,onPointerUp:M,onPointerCancel:M,onLostPointerCapture:M,onKeyDown:B}):null]})})}r(Hlt,"SidebarShell");function Glt({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)(Nlt,{children:e})})}r(Glt,"SecondarySidebar");var Qlt="/company/settings/members?tab=invites",Ylt="https://docs.paperclip.ing/",Jlt="https://paperclip.ing/feedback";function Xlt(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(Xlt,"deriveInitials$1");function Fse({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(Fse,"MenuAction");function Bse({deploymentMode:e,open:s,onOpenChange:n}){const i=!!$c(),{hidden:o,loaded:l}=cu(),c=RCe(),d=ECe(!i),u=i?c:d?Qlt:null,h=l&&u!==null&&!dg(o,"company.members")&&!dg(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:b,collapsed:v,peeking:j}=qa(),N=v&&!j,w=s??p,k=PCe(w),S=n??f,{data:C}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),I=eS({onSignedOut:M}),R=C?.user.name?.trim()||"Board",T=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),A=Xlt(R),D=MCe(C?.user);function M(){S(!1),x&&b(!1)}r(M,"closeNavigationChrome");function B(){I.mutate()}return r(B,"handleSignOut"),(0,t.jsx)("div",{className:"border-t border-r border-border bg-background px-3 py-2",children:(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",!N&&"px-2"),children:[(0,t.jsxs)(br,{open:w,onOpenChange:S,children:[(0,t.jsx)(Sr,{asChild:!0,children:(0,t.jsxs)("button",{type:"button",className:W("flex min-w-0 items-center gap-2.5 rounded-lg text-left text-(length:--text-compact) font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground",N?"w-full px-3 py-2":"flex-1 px-2 py-1.5"),"aria-label":"Open account menu",children:[(0,t.jsxs)(Mo,{size:"sm",children:[C?.user.image?(0,t.jsx)(xd,{src:C.user.image,alt:R}):null,(0,t.jsx)(Do,{children:A})]}),(0,t.jsx)("span",{className:W("min-w-0 flex-1 truncate",N&&"block w-0 min-w-0 overflow-hidden whitespace-nowrap text-transparent select-none"),children:R})]})}),(0,t.jsxs)(dr,{side:"top",align:"start",sideOffset:10,className:"w-(--sz-277px) max-w-(--sz-calc-24) overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl",children:[(0,t.jsx)("div",{className:"h-24 bg-(image:--gradient-extract-25)"}),(0,t.jsxs)("div",{className:"-mt-8 px-4 pb-4",children:[(0,t.jsxs)("div",{className:"relative flex items-start gap-3",children:[(0,t.jsx)(Ke,{to:D,"aria-label":"View profile",onClick:M,className:"absolute inset-0 rounded-xl transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),(0,t.jsx)("div",{className:"pointer-events-none relative rounded-2xl border-4 border-popover bg-popover p-0.5 shadow-sm",children:(0,t.jsxs)(Mo,{size:"lg",children:[C?.user.image?(0,t.jsx)(xd,{src:C.user.image,alt:R}):null,(0,t.jsx)(Do,{children:A})]})}),(0,t.jsxs)("div",{className:"pointer-events-none relative min-w-0 flex-1 pt-1",children:[(0,t.jsx)("h2",{className:"truncate text-base font-semibold text-foreground",children:R}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:T}),k?(0,t.jsxs)("a",{className:"pointer-events-auto block truncate font-mono text-(length:--text-micro) leading-(--profile-popover-meta-line-height) text-muted-foreground hover:underline focus-visible:underline",href:`https://github.com/paperclipai/paperclip/commit/${k}`,target:"_blank",rel:"noreferrer","aria-label":`View commit ${k} on GitHub`,title:k,children:["SHA ",k.slice(0,7)]}):null]})]}),(0,t.jsxs)("div",{className:"mt-4 space-y-1",children:[h&&u?(0,t.jsx)(Fse,{label:"Invite",description:"Invite people to your organization.",icon:Gf,href:u,topLevel:i,onClick:M}):null,(0,t.jsx)(Fse,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:GN,href:Ylt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(yk,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)($Ce,{variant:"menu-action",onAfterAction:r(()=>S(!1),"onAfterAction")}),e==="authenticated"?(0,t.jsxs)("button",{type:"button",className:W("flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-destructive/10",I.isPending&&"cursor-not-allowed opacity-60"),onClick:B,disabled:I.isPending,children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(Tp,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:I.isPending?"Signing out...":"Sign out"}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:"End this browser session."})]})]}):null,(0,t.jsx)(OCe,{})]})]})]})]}),!N&&!i?(0,t.jsxs)(zn,{children:[(0,t.jsx)(qn,{asChild:!0,children:(0,t.jsx)("a",{href:Jlt,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)(_g,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Un,{side:"top",children:"Share feedback"})]}):null]})})}r(Bse,"SidebarAccountMenu");function Zlt(e,s){return JCe(e,s)[0]?.toLowerCase()??null}r(Zlt,"getCompanyRouteSegment");function JCe(e,s){if(!s)return[];const n=e.split("/").filter(Boolean);return n.length<2?[]:n[0]?.toUpperCase()!==s.toUpperCase()?[]:n.slice(1)}r(JCe,"getCompanyPathSegments");var ect=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function tct(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(tct,"isSkillsStoreRoute");function sct(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=qa(),{openNewIssue:d,openOnboarding:u}=Yo(),{togglePanelVisible:h}=Jf(),p=Xc()?.pushToast??null,{companies:f,loading:x,selectedCompany:b,selectedCompanyId:v,selectionSource:j,setSelectedCompanyId:N}=ps(),{companyPrefix:w,pluginRoutePath:k}=va(),S=Mn(),C=na(),I=hM(),R=kje(C.pathname,w).isTaskDetail,T=["/company/settings","/company/export","/company/import"].some(vt=>C.pathname.includes(vt)),A=JCe(C.pathname,w),D=A[0]?.toLowerCase()==="tools",M=A[0]?.toLowerCase()==="apps",B=M&&A[1]&&!ect.has(A[1].toLowerCase())?A[1]:null,E=M&&A[1]?.toLowerCase()==="app"&&A[2]?A[2]:null,z=tct(C.pathname,w),$=(0,m.useRef)(!1),q=(0,m.useRef)(null),U=(0,m.useRef)(null),O=(0,m.useRef)(new hye),K=(0,m.useRef)(C.key),H=KCe(l&&!R,C.pathname),[Z,se]=(0,m.useState)(!1),ne=(0,m.useMemo)(()=>{if(!w)return null;const vt=w.toUpperCase();return f.find(Le=>Le.issuePrefix.toUpperCase()===vt)??null},[f,w]),fe=!!w&&!x&&f.length>0&&!ne,X=(0,m.useMemo)(()=>k?.toLowerCase()??Zlt(C.pathname,w),[w,C.pathname,k]),re=ne?.id??null,oe=ne?.issuePrefix??null,{slots:G}=gd({slotTypes:["page","routeSidebar"],companyId:re,enabled:!!(re&&X)}),Y=(0,m.useMemo)(()=>l9(G,X),[X,G]),Q=(0,m.useMemo)(()=>({companyId:re,companyPrefix:oe}),[re,oe]),te=T?(0,t.jsx)(Blt,{}):B?(0,t.jsx)(Dse,{kind:"connection",connectionId:B}):E?(0,t.jsx)(Dse,{kind:"application",applicationId:E}):M||D?(0,t.jsx)(zlt,{}):Y?(0,t.jsx)(Wu,{slot:Y,context:Q,className:"h-full w-full",missingBehavior:"placeholder"}):null,ae=te!=null,{data:le}=ee({queryKey:P.health,queryFn:r(()=>du.get(),"queryFn"),retry:!1,refetchInterval:r(vt=>vt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),he=ae||z;(0,m.useLayoutEffect)(()=>(c(he),()=>c(!1)),[he,c]),(0,m.useEffect)(()=>{x||$.current||le?.deploymentMode!=="authenticated"&&(le?.cloud||f.length===0&&($.current=!0,u()))},[f,x,u,le?.cloud,le?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!ne){const Le=(v?f.find(Qe=>Qe.id===v):null)??f[0]??null;Le&&v!==Le.id&&N(Le.id,{source:"route_sync"});return}if(w!==ne.issuePrefix){const Le=C.pathname.replace(/^\/[^/]+/,"");S(`/${ne.issuePrefix}${Le}${C.search}`,{replace:!0});return}const vt=WCe({matchedCompany:ne,selectedCompanyId:v,companies:f});if(vt){p?.({title:`${ne.name} is archived`,body:`Switched to ${vt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${ne.id}`}),N(vt.id,{source:"route_sync"}),S(`/${vt.issuePrefix}/dashboard`,{replace:!0});return}VCe({selectionSource:j,selectedCompanyId:v,routeCompanyId:ne.id})&&N(ne.id,{source:"route_sync"})},[w,f,x,ne,C.pathname,C.search,S,p,j,v,N]);const ce=h,ge=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),me=(0,m.useRef)(null),ie=(0,m.useRef)(!1),ue=(0,m.useRef)(!1),ke=(0,m.useCallback)(()=>{me.current!==null&&(window.clearTimeout(me.current),me.current=null)},[]),be=(0,m.useCallback)(()=>{ke(),me.current=window.setTimeout(()=>o(!0),50)},[ke,o]),Ie=(0,m.useCallback)(()=>{ke(),o(!0)},[ke,o]),Ue=(0,m.useCallback)(()=>{ke(),me.current=window.setTimeout(()=>o(!1),120)},[ke,o]),at=(0,m.useCallback)(()=>{ie.current=!0,a&&!ue.current&&be()},[a,be]),dt=(0,m.useCallback)(()=>{ie.current=!1,ue.current=!1,Ue()},[Ue]),de=(0,m.useCallback)(()=>{ue.current||Ie()},[Ie]),Be=(0,m.useCallback)(()=>{ie.current||Ue()},[Ue]);(0,m.useEffect)(()=>ke,[ke]);const pt=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==pt.current&&(a?(ke(),o(!1),ue.current=ie.current):ue.current=!1,pt.current=a)},[a,ke,o]),(0,m.useEffect)(()=>{if(!i)return;const vt=r(Le=>{Le.key==="Escape"&&(ke(),o(!1))},"onKeyDown");return window.addEventListener("keydown",vt),()=>window.removeEventListener("keydown",vt)},[i,ke,o]),UCe(),FCe({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ge,onToggleSidebar:n,onTogglePanel:ce,onShowShortcuts:r(()=>se(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const vt=30,Le=50,Qe=75;let ut=0,Ye=0;const it=r(tt=>{const Pe=tt.touches[0];ut=Pe.clientX,Ye=Pe.clientY},"onTouchStart"),kt=r(tt=>{const Pe=tt.changedTouches[0],Ce=Pe.clientX-ut;if(!(Math.abs(Pe.clientY-Ye)>Qe)){if(!e&&ut<vt&&Ce>Le){s(!0);return}e&&Ce<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",it,{passive:!0}),document.addEventListener("touchend",kt,{passive:!0}),()=>{document.removeEventListener("touchstart",it),document.removeEventListener("touchend",kt)}},[l,e,s]),(0,m.useEffect)(()=>{const vt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=vt}},[l]),(0,m.useEffect)(()=>{if(!l)return GCe()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const vt=U.current;return HCe(vt)},[C.pathname]),(0,m.useEffect)(()=>{const vt=U.current;if(!vt)return;const Le=r(()=>{O.current.remember(K.current,vt.scrollTop)},"recordScroll");return vt.addEventListener("scroll",Le,{passive:!0}),()=>vt.removeEventListener("scroll",Le)},[]),(0,m.useLayoutEffect)(()=>{const vt=U.current,Le=mye({previousPathname:q.current,pathname:C.pathname,navigationType:I,state:C.state});q.current=C.pathname;const Qe=I==="POP",ut=Qe?O.current.recall(C.key):0;if(K.current=C.key,Qe){Q3(vt,ut);const Ye=requestAnimationFrame(()=>Q3(vt,ut));return()=>cancelAnimationFrame(Ye)}Le&&pye(vt)},[C.key,C.pathname,C.state,I]),(0,t.jsx)(uye,{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)(bCe,{}),(0,t.jsx)(vCe,{devServer:le?.devServer}),(0,t.jsxs)("div",{className:W("min-h-0 flex-1",l?"w-full":"flex overflow-clip"),children:[l&&e&&(0,t.jsx)("button",{type:"button",className:"fixed inset-0 z-40 bg-black/50",onClick:r(()=>s(!1),"onClick"),"aria-label":"Close sidebar"}),l?(0,t.jsxs)("div",{className:W("fixed inset-y-0 left-0 z-50 flex flex-col overflow-hidden pt-(--sz-safe-top) transition-transform duration-100 ease-out",e?"translate-x-0":"-translate-x-full"),children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:(0,t.jsx)("div",{className:"w-60 shrink-0 overflow-hidden",children:ae?te:(0,t.jsx)(Mse,{})})}),(0,t.jsx)(Bse,{deploymentMode:le?.deploymentMode})]}):(0,t.jsxs)(Hlt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:at,onPanelMouseLeave:dt,onPanelFocusCapture:a?de:void 0,onPanelBlurCapture:a?Be:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(Mse,{})}),(0,t.jsx)(Bse,{deploymentMode:le?.deploymentMode})]}),!l&&ae?(0,t.jsx)(Glt,{children:te}):null,(0,t.jsxs)("div",{className:W("flex min-w-0 flex-col",l?"w-full":"h-full flex-1"),children:[(0,t.jsxs)("div",{className:W(l&&"sticky top-0 z-20 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/85"),children:[(0,t.jsx)(g6,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(Vlt,{}),l&&T?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(Cje,{})}):null]}),(0,t.jsxs)("div",{className:W(l?"block":"flex flex-1 min-h-0"),children:[(0,t.jsx)("main",{id:"main-content",ref:U,tabIndex:-1,style:l?{"--tc-composer-bottom":"var(--sz-calc-14)"}:void 0,className:W("flex-1 p-4 outline-none md:p-6",l?"overflow-visible pb-(--sz-calc-14)":"overflow-auto [scrollbar-gutter:stable]"),children:fe?(0,t.jsx)(zu,{scope:"invalid_company_prefix",requestedPrefix:w??b?.issuePrefix}):(0,t.jsx)(kCe,{children:(0,t.jsx)(mb,{})})}),(0,t.jsx)(Oje,{})]})]})]}),l&&(0,t.jsx)(gCe,{visible:H}),(0,t.jsx)(Fje,{}),(0,t.jsx)(vwe,{}),(0,t.jsx)(cCe,{}),(0,t.jsx)(mCe,{}),(0,t.jsx)(hCe,{}),(0,t.jsx)(pCe,{open:Z,onOpenChange:se}),(0,t.jsx)(fCe,{}),(0,t.jsx)(xCe,{localTrusted:le?.deploymentMode==="local_trusted"})]})})}r(sct,"Layout");var zse=null;function nct(){return zse??=new qN,zse}r(nct,"getDetachedClient");function rct(){const e=(0,m.useContext)(CI),{data:s,isFetched:n}=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn"),enabled:e!=null},e??nct());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(rct,"useConferenceRoomChatEnabled");function act(){const{enabled:e,loaded:s}=rct();return s?e?(0,t.jsx)(mb,{}):(0,t.jsx)(kn,{to:"/dashboard",replace:!0}):null}r(act,"ConferenceRoomChatGate");var ict=["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"],oct={"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 }"}},rcs=ict.map(e=>oct[e]);function XCe({browser:e,label:s="Browser",onOpen:n}){const a=e.status==="closed"||e.status==="failed";return(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2 py-1 text-sm","aria-label":`${s} session`,children:[(0,t.jsx)(Ap,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{children:s}),(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.status]}),n&&(0,t.jsx)(L,{variant:"ghost",size:"sm",onClick:r(()=>n(e.id),"onClick"),children:a?"View session":"Open browser"})]})}r(XCe,"TaskBrowserActivity");function ZCe({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)(gqe,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Project created"}),(0,t.jsx)(Ke,{to:`/projects/${e.projectId}`,className:"break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description&&(0,t.jsx)("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:e.description}),e.repositories.length>0&&(0,t.jsx)("ul",{className:"space-y-1 pt-1",children:e.repositories.map(s=>(0,t.jsxs)("li",{className:"flex min-w-0 items-center gap-2 text-xs text-muted-foreground",children:[(0,t.jsx)(io,{className:"size-3 shrink-0","aria-hidden":!0}),(0,t.jsx)("a",{className:"truncate hover:underline focus-visible:underline",href:s.url,target:"_blank",rel:"noreferrer",children:s.name})]},s.id))})]})]})})}r(ZCe,"TaskChatProjectCreatedCard");function lct({item:e,onOpen:s}){return(0,t.jsx)("article",{className:"rounded-lg border border-border bg-card p-3","aria-label":`Skill created: ${e.name}`,children:(0,t.jsxs)("button",{type:"button",className:"flex w-full items-start gap-3 text-left",onClick:r(()=>s?.(e.skillId,e.name),"onClick"),children:[(0,t.jsx)(Pf,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("span",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:"Skill created"}),(0,t.jsx)("span",{className:"block break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description?(0,t.jsx)("span",{className:"block line-clamp-3 text-sm text-muted-foreground",children:e.description}):null]})]})})}r(lct,"TaskChatSkillCreatedCard");function cct(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(cct,"McpIcon");var dct=new Set(["tool","tool call","tool_call","acp_tool"]);function Gd(e){const s=(e??"").trim().toLowerCase().replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/,"");return!s||dct.has(s)}r(Gd,"isGenericToolName");function JW(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(JW,"mcpToolIdentity");function XW(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(XW,"identifierWords");function e1e(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(e1e,"sentenceCase");function jk(e){const s=(e??"").trim();return Gd(s)?"Unnamed tool":e1e(XW(JW(s)?.name??s))}r(jk,"humanizeToolName");var Nd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),uct={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:Nd("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:Nd("task_operation","task operation","task operations")},task_create:{action:"create",running:"Creating a task",completed:"Created a task",family:"plan",group:Nd("task_operation","task operation","task operations")},task_update:{action:"update",running:"Updating a task",completed:"Updated a task",family:"plan",group:Nd("task_operation","task operation","task operations")},task_list:{action:"list",running:"Listing tasks",completed:"Listed tasks",family:"plan",group:Nd("task_operation","task operation","task operations")},task_get:{action:"read",running:"Reading a task",completed:"Read a task",family:"plan",group:Nd("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:Nd("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"}},mct={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:[]},hct={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function pct(e){return XW(e).join("_")}r(pct,"normalizedKey");function fct(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(mct))if(a.includes(s))return n;return null}r(fct,"inferredAction");function xct(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(xct,"actionFamily");var gct={terminal:hg,grep:Lqe,search:oa,read:GN,edit:CM,web:aqe,plan:Hy,question:Pc,agent:hy,safety:Di,image:QI,wait:au,mcp:cct,other:Pf};function bct(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(bct,"actionCopy");function vct(e){switch(e){case"run":return Nd("command","command","commands");case"read":case"list":return Nd("read","read","reads");case"search":return Nd("search","search","searches");case"update":case"create":case"delete":case"move":return Nd("file_change","file change","file changes");case"start":case"stop":return Nd("delegation","delegation","delegations");case"wait":return Nd("wait","wait","waits");default:return Nd("tool_action","tool action","tool actions")}}r(vct,"defaultSummaryGroup");function yct(e){return e==="read"||e==="list"?Nd("paperclip_read","Paperclip read","Paperclip reads"):Nd("task_operation","task operation","task operations")}r(yct,"paperclipSummaryGroup");function wy(e){const s=(e.name??"").trim(),n=JW(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=XW(o),c=pct(o),d=uct[c],u=hct[(e.operation??"").trim().toLowerCase()],h=fct(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":Gd(o)?"unnamed":"fallback",x=Gd(o)?"Unnamed tool":jk(o),b=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&b&&l.length>1?l.slice(1):[],j=v.length?e1e(v).replace(/^./,I=>I.toLowerCase()):void 0,N=d?.running&&d.completed?{running:d.running,completed:d.completed}:p==="other"?Gd(o)?{running:"Running an unnamed tool",completed:"Ran an unnamed tool"}:{running:`Running ${x}`,completed:`Ran ${x}`}:bct(p,d?void 0:j),w=d?.family??xct(p),k=i==="mcp"?"mcp":w,S=a?jk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?yct(p):d?.group??vct(p);return{icon:gct[k],family:k,runningLabel:N.running,completedLabel:N.completed,failedLabel:`${N.completed} · failed`,interruptedLabel:`${N.running} · stopped`,displayName:x,sourceLabel:S,technicalName:s||void 0,confidence:f,summaryGroup:C}}r(wy,"toolActivityPresentation");function hN(e){const s=wy({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(hN,"toolTaxonomy");function t1e(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?Xx:s==="responding"||s.startsWith("responding (")?Sqe:null}r(t1e,"statusLabelIcon");var iO=["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"],oO=["Brewing","Tinkering","Distilling","Deliberating"],qse=(()=>{const e=[],s=Math.max(iO.length,oO.length);for(let n=0;n<s;n++)n<iO.length&&e.push(iO[n]),n<oO.length&&e.push(oO[n]);return e})(),jct=1e4;function wct(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(wct,"isGenericStatusLabel");function kct(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(kct,"fnv1a");function Nct(e,s=0){const n=Math.floor(Math.max(0,s)/jct);return qse[(kct(e)+n)%qse.length]}r(Nct,"whimsyWord");var Sct=[{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}],acs=Array.from(new Set(Sct.map(e=>e.group)));function s1e(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(s1e,"parseCssTimeMs");function Cct(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(Cct,"elapsedLabel");function _ct(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(_ct,"liveElapsedLabel");function Ict(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(Ict,"useLiveElapsedMs");function Act(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(Act,"lineScrollOffset");function NE(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=s1e(s);return Number.isFinite(n)?n:0}r(NE,"motionTokenMs");function Tct({text:e,streaming:s,leaving:n}){const a=(0,m.useRef)(null),[i,o]=(0,m.useState)(0),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1);(0,m.useLayoutEffect)(()=>{const p=a.current;if(!p)return;const f=r(()=>{const b=parseFloat(window.getComputedStyle(p).lineHeight);o(Act(p.scrollHeight,b))},"measure");if(f(),typeof ResizeObserver>"u")return;const x=new ResizeObserver(f);return x.observe(p),()=>x.disconnect()},[e,s]),(0,m.useEffect)(()=>{const p=requestAnimationFrame(()=>c(!0)),f=window.setTimeout(()=>u(!0),NE("--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(Tct,"LiveSelfTalkLine");function Rct(e,s){const[n,a]=(0,m.useState)(null),i=(0,m.useRef)(n),o=(0,m.useRef)(null),l=(0,m.useRef)(e),c=(0,m.useRef)(0),d=(0,m.useRef)(null),u=(0,m.useRef)(null),h=(0,m.useRef)(null);return l.current=e,(0,m.useEffect)(()=>{const p=r(j=>{j.current!=null&&(window.clearTimeout(j.current),j.current=null)},"clear"),f=r(j=>{i.current=j,a(j)},"show"),x=r(()=>{p(u),p(h),u.current=window.setTimeout(()=>{if(u.current=null,o.current!=null)return;const j=i.current;j==null||j.streaming||(f({...j,leaving:!0}),h.current=window.setTimeout(()=>{h.current=null,i.current?.leaving&&f(null)},NE("--motion-line-scroll")))},NE("--motion-interstitial-dwell"))},"scheduleLeave"),b=r((j,N)=>{p(u),p(h),c.current=Date.now(),f({text:j,streaming:N,swapKey:(i.current?.swapKey??0)+1}),N||x()},"swapIn");if(!s){p(d),p(u),p(h),o.current=null,i.current&&f(null);return}const v=i.current;if(e==null){v?.streaming&&(f({...v,streaming:!1}),x());return}if(v==null){b(e,!0);return}if(v.streaming){v.text!==e&&f({...v,text:e});return}if(o.current=e,d.current==null){const j=NE("--motion-interstitial-dwell"),N=Math.max(0,c.current+j-Date.now());d.current=window.setTimeout(()=>{d.current=null;const w=o.current;o.current=null,w!=null&&b(w,l.current!=null)},N)}},[e,s]),(0,m.useEffect)(()=>()=>{d.current!=null&&window.clearTimeout(d.current),u.current!=null&&window.clearTimeout(u.current),h.current!=null&&window.clearTimeout(h.current)},[]),n}r(Rct,"useHeldSelfTalk");var Ect={running:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:YN,spin:!1,tone:"text-primary"},interrupted:{Icon:F7,spin:!1,tone:"text-destructive"},refused:{Icon:jm,spin:!1,tone:"text-destructive"},truncated:{Icon:Dqe,spin:!1,tone:"text-(--status-agent-paused)"}};function n1e({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=Ect[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=Ict(e.startedAtMs,d),h=Rct(d?e.selfTalk:void 0,d),p=Cct(e.elapsedMs);if(d){const f=_ct(u??e.elapsedMs),x=e.selfTalk!=null,b=e.toolName?hN(e.toolName).icon:x?null:t1e(e.label),v=x||wct(e.label)?Nct(e.id,u??e.elapsedMs??0):e.label,j=(0,t.jsxs)("div",{className:"tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground",children:[n!==void 0?(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-caret-slot",children:(0,t.jsx)(En,{className:W("h-3 w-3 transition-transform",n?"rotate-90":null),"aria-hidden":!0})}):null,(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-dot-slot",children:(0,t.jsx)("span",{"aria-hidden":!0,className:"h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"})}),b?(0,t.jsx)(b,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}):null,(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[(0,t.jsxs)("span",{className:"shimmer-text shimmer-text-muted shrink-0 font-medium",children:[v,"…"]}),f?(0,t.jsx)("span",{className:"shrink-0 font-mono tabular-nums text-(length:--text-micro)",children:f}):null,e.detail?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro)",children:e.detail}):null,e.tokens?(0,t.jsxs)("span",{className:"ml-auto shrink-0 font-mono text-(length:--text-micro)",children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]});return(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 py-0.5 text-xs text-muted-foreground","data-testid":"task-chat-interstitial-row",children:[(0,t.jsx)("span",{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0"}),h?(0,t.jsx)(Tct,{text:h.text,streaming:h.streaming,leaving:h.leaving},h.swapKey):(0,t.jsx)("span",{"aria-hidden":!0,className:"tc-line-scroll min-w-0 flex-1"})]}),a?(0,t.jsx)("button",{type:"button",onClick:a,"aria-expanded":n,className:"-mx-1.5 block w-full rounded-sm px-1.5 text-left transition-colors hover:bg-muted/60","data-testid":"task-chat-live-turn",children:j}):j]})}return(0,t.jsxs)("div",{className:W("tc-enter-status flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm",c?"tc-approval border-primary/40 bg-primary/5":"border-border bg-muted/40"),children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(i,{className:W("h-4 w-4 shrink-0",l,o&&"animate-spin")}),(0,t.jsx)("span",{className:"min-w-0 truncate font-medium",children:e.label}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[p?(0,t.jsx)("span",{children:p}):null,e.tokens?(0,t.jsxs)("span",{children:[e.tokens.used.toLocaleString(),"/",e.tokens.size.toLocaleString()," ctx"]}):null]})]}),e.detail?(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:e.detail}):null,c&&e.approval?(0,t.jsx)("div",{className:"flex flex-wrap justify-end gap-2 pt-1",children:e.approval.options.map(f=>{const x=f.kind.startsWith("reject");return(0,t.jsx)("button",{type:"button",onClick:r(()=>s?.(f.id),"onClick"),className:W("rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",x?"border-border text-muted-foreground hover:bg-accent/50 hover:text-foreground":"border-primary bg-primary text-primary-foreground hover:bg-primary/90"),children:f.label},f.id)})}):null]})}r(n1e,"TaskChatStatusPill");var Eg=(0,m.createContext)(null);function tj(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${Math.round(e)} B`;const s=["KB","MB","GB","TB"];let n=e/1024,a=0;for(;n>=1024&&a<s.length-1;)n/=1024,a+=1;const i=n.toFixed(1);return`${i.endsWith(".0")?i.slice(0,-2):i} ${s[a]}`}r(tj,"formatBytes$4");var K5=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),Pct=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],Mct=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],Dct=new Set(["application/wasm"]),Lct=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),r1e=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),$ct=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"]),Oct=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function fA(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(fA,"normalizeOutputContentType");function Fct(e){const s=(e??"").trim().toLowerCase();return s?Oct.some(n=>s.endsWith(n)):!1}r(Fct,"hasDocumentLikeFilename");function a1e(e){return Lct.has(e)||e.endsWith("+zip")}r(a1e,"isZipContentType");function Bct(e){return e?!!(e.startsWith("text/")||r1e.has(e)||$ct.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Bct,"isDocumentLikeOutputContentType");function zct(e,s){const n=fA(e);return!n||Bct(n)||K5.has(n)&&Fct(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||Dct.has(n)||a1e(n)||K5.has(n)}r(zct,"isOutputEligibleContentType");function qct(e){const s=fA(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"}:a1e(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:r1e.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(qct,"getOutputFileGlyph");function Vu(e,s){const n=fA(e);if(n.startsWith("video/"))return!0;if(!K5.has(n))return!1;const a=(s??"").trim().toLowerCase();return Pct.some(i=>a.endsWith(i))}r(Vu,"isVideoLikeOutput");function ky(e){const s=fA(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(ky,"isImageContentType");function f4(e,s){const n=fA(e);if(ky(n))return!0;if(n&&!K5.has(n))return!1;const a=(s??"").trim().toLowerCase();return Mct.some(i=>a.endsWith(i))}r(f4,"isImageLikeOutput");function Use(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(Use,"toTime");function x4(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=y$e.safeParse(n.metadata);return a.success&&!zct(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:Use(a.createdAt)-Use(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(x4,"getIssueOutputs");function ZW(e){return e.metadata?.originalFilename||e.title||"output"}r(ZW,"outputFilename");function i1e(e){return new Set(x4(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(i1e,"getPromotedOutputAttachmentIds");function Uct(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(Uct,"normalizedContentType");function vg(e){return e.originalFilename??e.id}r(vg,"attachmentFilename");function g4(e){return e.openPath??e.contentPath}r(g4,"attachmentOpenPath");function lS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(lS,"attachmentDownloadPath");function o1e(e){const s=Uct(e);return f4(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(o1e,"isImageAttachment$1");function l1e(e){return Vu(e.contentType,e.originalFilename)}r(l1e,"isVideoAttachment");function c1e(e){return nfe(e)}r(c1e,"isMarkdownAttachment");function sj(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return nfe(e)||s.startsWith("text/")||/^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(s)||["","application/octet-stream"].includes(s)&&/\.(txt|log|csv|json|yaml|yml|toml|ini|sh|ts|tsx|js|jsx|py|css|html)$/i.test(e.originalFilename??"")}r(sj,"isTextAttachment");function d1e(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(d1e,"downloadBlob$1");function Kct(e,s,n){d1e(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(Kct,"downloadTextFile");var lO="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 u1e({issueId:e,documentKey:s,title:n,format:a,body:i,className:o}){const[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(null),{copy:f,copied:x,failed:b}=Cp(),v=(0,m.useRef)(void 0);(0,m.useEffect)(()=>()=>clearTimeout(v.current),[]);const j=(0,m.useCallback)(async(I,R)=>{c(I),p(null);try{await R(),u(I)}catch(T){u(null),p(T instanceof Error?T.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),N=(0,m.useCallback)(async()=>i??(await St.getDocument(e,s)).body,[i,s,e]),w=(0,m.useCallback)(()=>{c("copy"),p(null),(async()=>{try{await f(await N())==="failed"&&p("Copy failed")}catch(I){p(I instanceof Error?I.message:"Copy failed")}finally{c(null)}})()},[f,N]),k=b||h==="Copy failed"?"Copy failed":x?"Copied!":"Copy full content",S=d==="download"?"Downloaded!":"Download source",C=d==="pdf"?"Downloaded!":"Export to PDF";return(0,t.jsxs)("div",{className:W("flex items-center gap-0.5",o),"data-testid":"document-export-actions",children:[(0,t.jsx)("button",{type:"button",className:lO,disabled:l!==null,"aria-label":"Copy full content",title:k,"data-testid":"document-export-copy",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),w()},"onClick"),children:x?(0,t.jsx)(gs,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(Ir,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:lO,disabled:l!==null,"aria-label":"Download source",title:S,"data-testid":"document-export-download",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),j("download",async()=>{const R=OBe(a);Kct(iX(n,R),await N(),R==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(po,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:lO,disabled:l!==null,"aria-label":"Export to PDF",title:C,"data-testid":"document-export-pdf",onClick:r(I=>{I.preventDefault(),I.stopPropagation(),j("pdf",async()=>{d1e(iX(n,"pdf"),await St.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(fqe,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("span",{className:"sr-only",role:"status","aria-live":"polite",children:h??(x?"Copied!":b?"Copy failed":d?"Downloaded!":"")})]})}r(u1e,"DocumentExportActions");function K_({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(K_,"PreviewFrame");function W5({label:e}){return(0,t.jsx)(K_,{className:"flex items-center justify-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-1.5 text-muted-foreground/50",children:[(0,t.jsx)(Dc,{className:"h-7 w-7","aria-hidden":"true"}),e?(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide",children:e}):null]})})}r(W5,"PlaceholderPreview");function Wct({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(W5,{label:"Image"}):(0,t.jsx)(K_,{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(Wct,"ImagePreview");function Vct({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)(K_,{className:"flex items-center justify-center bg-black/80",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-white/15",children:(0,t.jsx)(oo,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})});const c=r(()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null),i(!0)},"markFrameReady"),d=r(()=>{l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(c,3e3)},"scheduleFrameReadyFallback"),u=r(p=>{if(o.current)return;o.current=!0;const f=p.currentTarget,x=Number.isFinite(f.duration)&&f.duration>0?f.duration:0,b=x>0?Math.min(1,x/4):.05;try{Math.abs(f.currentTime-b)>.001?(f.currentTime=b,d()):c()}catch{c()}},"loadThumbnailFrame"),h=r(p=>{(o.current||p.currentTarget.currentTime>0)&&c()},"handleLoadedData");return(0,t.jsxs)(K_,{className:"bg-black",children:[(0,t.jsx)("video",{src:e.contentPath,preload:"metadata",muted:!0,playsInline:!0,"data-frame-ready":a?"true":"false",className:W("h-full w-full object-contain transition-opacity",a?"opacity-100":"opacity-0"),onLoadedMetadata:u,onLoadedData:h,onSeeked:c,onError:r(()=>n(!0),"onError")}),(0,t.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,t.jsx)("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-black/55",children:(0,t.jsx)(oo,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(Vct,"VideoPreview");function Hct({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(K_,{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)(W5,{label:e.source==="document"?"Document":"Text"})}r(Hct,"TextPreview");function xA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(Wct,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(Vct,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(Hct,{artifact:e});case"file":return(0,t.jsx)(W5,{label:"File"});default:return(0,t.jsx)(W5,{})}}r(xA,"ArtifactPreview");function Kse({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(Kse,"SecondaryAction");function Gct({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)(xA,{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)(u1e,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Kse,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)(Vn,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Kse,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(po,{className:"h-3.5 w-3.5"})}):null]})]}),(0,t.jsxs)("div",{className:"mt-0.5 flex items-center gap-1.5 text-(length:--text-micro) text-muted-foreground/65",children:[(0,t.jsxs)("span",{children:["Last edited ",Id(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(Gct,"ArtifactCard");var Ql={credentials:r(e=>Te.get(`/companies/${e}/email/connections`),"credentials"),checkAddress:r((e,s,n,a)=>Te.post(`/companies/${e}/email/connections/${s}/check-address`,n,{signal:a}),"checkAddress"),connect:r((e,s)=>Te.post(`/companies/${e}/email/connections`,s),"connect"),inspectSaved:r((e,s)=>Te.post(`/companies/${e}/email/connections/${s}/inspect`,{}),"inspectSaved"),list:r(e=>Te.get(`/companies/${e}/email/inboxes`),"list"),setup:r((e,s)=>Te.post(`/companies/${e}/email/inboxes`,s),"setup"),inspect:r((e,s)=>Te.post(`/companies/${e}/email/inspect`,{apiKey:s}),"inspect"),control:r((e,s)=>Te.post(`/email/inboxes/${e}/control`,{action:s}),"control"),reconnect:r((e,s,n)=>Te.post(`/email/inboxes/${e}/reconnect`,{apiKey:s,receiveMode:n}),"reconnect"),resolve:r((e,s,n,a)=>Te.post(`/companies/${e}/email/deliveries/${s}/resolve`,{outcome:n,providerMessageId:a}),"resolve"),thread:r((e,s)=>Te.get(`/companies/${e}/email/tasks/${s}`),"thread"),send:r((e,s)=>Te.post(`/companies/${e}/email/send`,s),"send")};function m1e(e,s){return ee({queryKey:["email-thread",e,s],queryFn:r(()=>Ql.thread(e,s),"queryFn"),enabled:!!(e&&s)&&!s.startsWith("chat:"),refetchInterval:r(n=>n.state.data===null?!1:3e3,"refetchInterval")})}r(m1e,"useEmailThread");var h1e=(0,m.createContext)(null);function Qct({companyId:e,issueId:s,children:n}){const a=m1e(e,s);return(0,t.jsx)(h1e.Provider,{value:a.data??null,children:n})}r(Qct,"EmailThreadProvider");function p1e(e){const s=(0,m.useContext)(h1e),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(f1e,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r(p1e,"useEmailComment");function f1e({message:e,publication:s,issueId:n}){const a=ee({queryKey:["email-attachments",n],queryFn:r(()=>St.listAttachments(n),"queryFn"),enabled:e.attachmentIds.length>0});return(0,t.jsxs)("article",{"aria-label":e.direction==="inbound"?"Email received":"Email sent",className:"space-y-4 rounded-xl border border-border bg-card p-5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,t.jsxs)("span",{className:"flex items-center gap-2 text-sm font-semibold",children:[(0,t.jsx)(c7,{className:"size-4"}),e.direction==="inbound"?"Email received":"Email sent"]}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:new Date(e.timestamp).toLocaleString()})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("p",{className:"text-sm font-medium",children:[e.from,e.direction==="inbound"&&(0,t.jsx)("span",{className:"ml-2 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground",children:"External"})]}),(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["To: ",e.to.join(", ")]}),!!e.cc?.length&&(0,t.jsxs)("p",{className:"break-words text-xs text-muted-foreground",children:["Cc: ",e.cc.join(", ")]}),(0,t.jsx)("p",{className:"text-sm font-semibold",children:e.subject})]}),(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words text-sm",children:e.text||"(No text body)"}),!!e.attachmentIds.length&&(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:e.attachmentIds.map(i=>{const o=a.data?.find(l=>l.id===i);return(0,t.jsxs)("a",{href:`/api/attachments/${i}/content`,target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[(0,t.jsx)(Dc,{className:"size-3.5"}),o?.originalFilename??"Open attachment"]},i)})}),(0,t.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,t.jsx)("summary",{className:"cursor-pointer",children:"Email details"}),(0,t.jsxs)("div",{className:"space-y-2 pt-3",children:[!!e.bcc?.length&&(0,t.jsxs)("p",{children:["Bcc: ",e.bcc.join(", ")]}),(0,t.jsxs)("p",{className:"break-all",children:["Message ID: ",e.providerMessageId]}),e.fullText!==e.text&&(0,t.jsx)("div",{className:"whitespace-pre-wrap break-words",children:e.fullText})]})]}),s&&(0,t.jsxs)("p",{className:"border-t border-border pt-3 text-xs text-muted-foreground",children:[s.outcome==="delivered"?"Delivered":s.outcome==="failed"?"Delivery failed":s.outcome==="uncertain"?"Delivery uncertain":s.outcome==="queued"?"Queued":"Sent",s.error?` · ${s.error}`:""]}),a.error&&(0,t.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:"Attachments could not be loaded."})]})}r(f1e,"EmailMessageCard");var Xv=(0,m.createContext)(null);function nj({items:e,initialIndex:s,open:n,onOpenChange:a}){const[i,o]=(0,m.useState)(s),l=(0,m.useRef)(null),c=(0,m.useCallback)(b=>{l.current=b},[]);(0,m.useEffect)(()=>{n&&o(s)},[n,s]);const d=(0,m.useCallback)(()=>{o(b=>(b+1)%e.length)},[e.length]),u=(0,m.useCallback)(()=>{o(b=>(b-1+e.length)%e.length)},[e.length]);(0,m.useEffect)(()=>{i<e.length||o(0)},[i,e.length]),(0,m.useEffect)(()=>{if(!n)return;const b=r(v=>{v.key==="ArrowRight"?d():v.key==="ArrowLeft"?u():v.key==="Escape"&&a(!1)},"handler");return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[n,d,u,a]);const h=(0,m.useCallback)(b=>{const v=b.target;v.closest("button")||v.closest("a")||v===l.current||a(!1)},[a]);if(e.length===0)return null;const p=e[i];if(!p)return null;const f=vg(p),x=Vu(p.contentType,p.originalFilename);return(0,t.jsx)(LFe,{open:n,onOpenChange:a,children:(0,t.jsxs)(MFe,{children:[(0,t.jsx)(DFe,{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)(BFe,{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(b=>b.stopPropagation(),"onClick"),children:(0,t.jsx)(po,{className:"h-4.5 w-4.5"})}),(0,t.jsx)("button",{type:"button",onClick:r(()=>a(!1),"onClick"),className:"text-white/50 hover:text-white transition-colors",title:"Close",children:(0,t.jsx)(Fn,{className:"h-5 w-5"})})]})]}),(0,t.jsxs)("div",{className:"flex-1 flex items-center min-h-0",children:[(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:u,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Previous",children:(0,t.jsx)(Uu,{className:"h-7 w-7"})})}),(0,t.jsx)("div",{className:"flex-1 flex items-center justify-center min-w-0 min-h-0 h-full px-2",children:x?(0,t.jsx)("video",{ref:c,src:p.contentPath,className:"max-w-full max-h-full rounded-lg",controls:!0,playsInline:!0}):(0,t.jsx)("img",{ref:c,src:p.contentPath,alt:f,className:"max-w-full max-h-full object-contain select-none rounded-lg",draggable:!1})}),(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:d,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Next",children:(0,t.jsx)(En,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(nj,"ImageGalleryModal");var eV=(0,m.createContext)(null);function Yct({value:e,children:s}){return(0,t.jsx)(eV.Provider,{value:e,children:s})}r(Yct,"DispositionRecoveryProvider");function Jct(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(Jct,"readDispositionRecoverySnapshot");function x1e(e){return Jct(e,(0,m.useContext)(eV)?.issue.activeRecoveryAction)}r(x1e,"useDispositionRecoverySnapshot");function Xct(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(Xct,"dispositionRetryUnavailableReason");function Zct(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(Zct,"descriptionFor");function tV({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(eV),[i,o]=(0,m.useState)(n),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(null),f=(0,m.useRef)(!1),x=(0,m.useId)(),b=(0,m.useId)(),v=(0,m.useId)(),j=Xct(e,a),N=!!(a&&a.issue.activeRecoveryAction?.id!==e.actionId),w=e.assigneeAgentId&&a?.agentMap?.get(e.assigneeAgentId)?.name||"the assigned agent",k=d||N?gs:Es;async function S(){if(!(!a||j||f.current)){f.current=!0,c(!0),p(null);try{await a.onRetry(e.actionId),u(!0)}catch(C){p(C instanceof Error?C.message:"Refresh the task to check its current state, then try again.")}finally{f.current=!1,c(!1)}}}return r(S,"retry"),(0,t.jsxs)("section",{"aria-labelledby":b,className:"flex min-w-0 gap-2.5 py-3","data-testid":"disposition-recovery-notice",children:[(0,t.jsx)(k,{"aria-hidden":"true",className:W("mt-0.5 size-4 shrink-0",d||N?"text-muted-foreground":"text-(--status-task-icon-todo)")}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",role:"status","aria-live":"polite",children:[(0,t.jsx)("h2",{id:b,className:"break-words text-sm font-medium text-foreground",children:d?"Retry requested":N?"Agent needed attention":"Agent needs attention"}),(0,t.jsx)("p",{className:"text-sm leading-relaxed text-muted-foreground",children:d?`The task was returned to To do for ${w}.`:Zct(e)})]}),j&&!d?(0,t.jsxs)("p",{id:v,className:"text-xs leading-relaxed text-muted-foreground",children:[!N&&(0,t.jsx)("span",{className:"font-medium text-foreground",children:"Retry unavailable. "}),j]}):null,h?(0,t.jsxs)("p",{role:"alert",className:"text-sm text-destructive",children:["Couldn’t confirm the retry. ",h]}):null,(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[!d&&!N?(0,t.jsxs)(L,{size:"xs",variant:"outline",disabled:l||!!j,"aria-describedby":j?v:void 0,onClick:r(()=>{S()},"onClick"),children:[l?(0,t.jsx)(rt,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ci,{"aria-hidden":"true",className:"size-3"}),l?"Requesting retry…":"Retry agent"]}):null,(0,t.jsxs)(L,{size:"xs",variant:"ghost",className:"text-muted-foreground","aria-expanded":i,"aria-controls":x,onClick:r(()=>o(C=>!C),"onClick"),children:[i?"Hide details":"View details",(0,t.jsx)(nn,{"aria-hidden":"true",className:W("size-3",i&&"rotate-180")})]}),s?(0,t.jsx)("time",{dateTime:s,className:"font-mono text-xs text-muted-foreground sm:ml-auto",children:ao(s)}):null]}),i?(0,t.jsxs)("div",{id:x,className:"flex flex-col gap-3 rounded-lg border border-border bg-muted/20 p-3",children:[(0,t.jsxs)("dl",{className:"flex flex-col gap-2 text-xs",children:[(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Assigned when recovery stopped"}),(0,t.jsx)("dd",{children:w})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Automatic attempts"}),(0,t.jsxs)("dd",{className:"font-mono",children:[e.attemptCount," of ",e.maxAttempts]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-1",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Automatic retries for this recovery"}),(0,t.jsx)("dd",{children:"Stopped"})]})]}),(0,t.jsx)("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"Recovery asked the assigned agent to record an outcome or a next step. Retrying keeps the same task and agent, and checks the task’s current controls before continuing."}),(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Technical reason"}),(0,t.jsx)("code",{className:"break-all font-mono text-xs",children:e.reason})]})]}):null]})]})}r(tV,"DispositionRecoveryNotice");var g1e={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:Df,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:Df,iconClass:"text-sky-700 dark:text-sky-300",label:"text-sky-800 dark:text-sky-200",divider:"border-sky-300/50 dark:border-sky-500/30"},success:{container:"border-emerald-300/70 bg-emerald-50/70 dark:border-emerald-500/30 dark:bg-emerald-500/10",iconWrap:"bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-200",icon:ca,iconClass:"text-emerald-700 dark:text-emerald-300",label:"text-emerald-800 dark:text-emerald-200",divider:"border-emerald-300/50 dark:border-emerald-500/30"},warning:{container:"border-amber-300/70 bg-amber-50/80 dark:border-amber-500/30 dark:bg-amber-500/10",iconWrap:"bg-amber-100 text-amber-800 dark:bg-amber-500/20 dark:text-amber-200",icon:Es,iconClass:"text-amber-700 dark:text-amber-300",label:"text-amber-900 dark:text-amber-200",divider:"border-amber-300/60 dark:border-amber-500/30"},danger:{container:"border-red-400/60 bg-red-50/80 dark:border-red-500/35 dark:bg-red-500/10",iconWrap:"bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-200",icon:Hk,iconClass:"text-red-700 dark:text-red-300",label:"text-red-900 dark:text-red-200",divider:"border-red-400/50 dark:border-red-500/30"}};function edt(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(edt,"formatTimestamp$1");function tdt({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(tdt,"MetadataRow$1");function b1e({sections:e,tone:s="neutral"}){const n=g1e[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)(tdt,{row:o,tone:n},l))})]},i))})}r(b1e,"SystemNoticeMetadataSections");function sV({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=g1e[e],u=d.icon,[h,p]=(0,m.useState)(o),f=(0,m.useId)(),x=!!(i&&i.length>0),b=s??{neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"}[e];return(0,t.jsxs)("section",{role:"status","aria-label":b,className:W("relative w-full overflow-hidden rounded-lg border text-sm shadow-(--shadow-extract-8)",d.container,c),children:[(0,t.jsxs)("header",{className:"flex items-start gap-3 px-3 py-2.5 sm:px-4",children:[(0,t.jsx)("span",{className:W("mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md",d.iconWrap),"aria-hidden":!0,children:(0,t.jsx)(u,{className:W("h-4 w-4",d.iconClass)})}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-eyebrow)",children:[(0,t.jsx)("span",{className:d.label,children:b}),a?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),a.href?(0,t.jsx)("a",{href:a.href,className:"rounded-sm font-medium normal-case tracking-normal text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",children:a.label}):(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:a.label})]}):null,l?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-muted-foreground/60","aria-hidden":!0,children:"·"}),(0,t.jsx)("span",{className:"font-medium normal-case tracking-normal text-muted-foreground",children:edt(l)})]}):null]}),(0,t.jsx)("div",{className:"mt-1 break-words text-sm leading-6 text-foreground",children:n})]}),x?(0,t.jsxs)("button",{type:"button",onClick:r(()=>p(v=>!v),"onClick"),"aria-expanded":h,"aria-controls":f,className:W("ml-1 inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-transparent px-2 text-(length:--text-micro) font-medium uppercase tracking-(--tracking-eyebrow) text-muted-foreground transition-(--tp-background-color-border-color-color)","hover:border-border/70 hover:bg-background/70 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)("span",{children:h?"Hide details":"Details"}),(0,t.jsx)(nn,{className:W("h-3.5 w-3.5 transition-transform duration-150",h&&"rotate-180")})]}):null]}),x&&h?(0,t.jsx)("div",{id:f,className:W("border-t bg-background/50 dark:bg-background/30",d.divider),children:(0,t.jsx)(b1e,{sections:i,tone:e})}):null]})}r(sV,"SystemNotice");var sdt="System update",ndt=80;function rdt(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(rdt,"retryFailureCode");function adt(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(adt,"recoveryOwnerName");function idt(e){const s=e.split(`
|
|
356
356
|
`).map(i=>i.trim()).find(i=>i.length>0);if(!s)return;const n=s.search(/[.!?](\s|$)/),a=n>=0?s.slice(0,n+1):s;return a.length<=ndt?a:`${a.slice(0,79).trimEnd()}…`}r(idt,"firstSentence");function odt(e){const s=e.presentation?.title?.trim(),n=e.presentation?.tone;if(s)return{title:s,tone:n??"neutral"};const a=e.body??"",i=rdt(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=adt(a);return{title:o?`Task paused — waiting on ${o}`:"Task paused — waiting on a recovery owner",tone:n??"warning"}}return{title:sdt,tone:n??"neutral",detail:idt(a)}}r(odt,"humanizeSystemNotice");var ldt={neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"};function Jj(e,s){const n=e.label?.trim();return n&&n.length>0?n:s}r(Jj,"metadataRowText");function cdt(e,s){switch(e.type){case"text":return{kind:"text",label:Jj(e,"Detail"),value:e.text};case"code":return{kind:"code",label:Jj(e,"Code"),value:e.code};case"key_value":return{kind:"text",label:e.label,value:e.value};case"issue_link":{const n=e.identifier??null;return n?{kind:"issue",label:Jj(e,"Task"),identifier:n,href:`/issues/${n}`,title:e.title??void 0}:{kind:"text",label:Jj(e,"Task"),value:e.title??"unknown"}}case"agent_link":{const n=e.name?.trim()||e.agentId.slice(0,8);return{kind:"agent",label:Jj(e,"Agent"),name:n,href:`/agents/${e.agentId}`}}case"run_link":{const n=e.agentId??s.runAgentId??null,a=n?`/agents/${n}/runs/${e.runId}`:void 0;return{kind:"run",label:Jj(e,"Run"),runId:e.runId,href:a,status:e.title??void 0}}default:return null}}r(cdt,"mapMetadataRow");function nV(e,s={}){return!e||!Array.isArray(e.sections)?[]:e.sections.map(n=>{const a=n.rows.map(o=>cdt(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(nV,"mapCommentMetadataToSystemNoticeSections");function v1e(e,s){const n=s?.trim();return n&&n.length>0?n:ldt[e]}r(v1e,"systemNoticeLabelForTone");function ddt(e){const s=e.presentation?.tone??"neutral",n=v1e(s,e.presentation?.title),a=!!e.presentation?.detailsDefaultOpen,i=nV(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(ddt,"buildSystemNoticeProps");var udt={neutral:Df,info:Df,success:ca,warning:Es,danger:Hk},mdt={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 hdt({item:e,onTryAgainNoLiveExecutionPath:s,tryAgainNoLiveExecutionPathPending:n=!1}){const a=x1e(e.metadata),i=Rp(),[o,l]=(0,m.useState)(!!e.presentation?.detailsDefaultOpen),c=(0,m.useId)(),{title:d,tone:u,detail:h}=odt({body:e.text,presentation:e.presentation}),p=nV(e.metadata,{runAgentId:e.runAgentId}),f=!(e.presentation?.kind==="system_notice"&&e.presentation.title?.trim().toLowerCase().startsWith("workspace ready")===!0&&p.some(N=>N.title?.trim().toLowerCase()==="workspace")),x=udt[u],b=e.createdAtIso?ao(e.createdAtIso):void 0,v=!!s&&(e.presentation?.title?.trim()==="No live execution path"||e.text.toLowerCase().includes("no live execution path")),j=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");return e.author==="system"&&a?(0,t.jsx)(tV,{snapshot:a,createdAt:e.createdAtIso,defaultExpanded:e.presentation?.detailsDefaultOpen}):(0,t.jsxs)("div",{className:W("tc-enter-bubble flex flex-col items-start",i?"py-0.5":"py-1"),"data-testid":"task-chat-system-notice","data-tone":i?u:void 0,role:i?"group":void 0,"aria-label":i?`System update: ${d}`:void 0,children:[(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) items-center gap-1.5",children:[(0,t.jsxs)("button",{type:"button",onClick:r(()=>l(N=>!N),"onClick"),"aria-expanded":o,"aria-controls":c,className:W("flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5 text-xs text-muted-foreground","hover:bg-muted/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)(x,{className:W("h-3.5 w-3.5 shrink-0",mdt[u]),"aria-hidden":!0}),(0,t.jsx)("span",{className:"truncate font-medium",children:d}),h?(0,t.jsxs)("span",{className:"hidden truncate sm:inline",children:["· ",h]}):null,b?(0,t.jsxs)("span",{className:"shrink-0 text-muted-foreground/70",children:["· ",b]}):null,(0,t.jsx)(nn,{className:W("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",o&&"rotate-180"),"aria-hidden":!0})]}),v&&!o?(0,t.jsx)(L,{type:"button",variant:"outline",size:"xs",onClick:j,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"}):null]}),o?(0,t.jsxs)("div",{id:c,"data-testid":"task-chat-system-notice-details",className:"mt-1 w-full max-w-(--pct-85) overflow-hidden rounded-lg border border-border bg-muted/25 text-left text-sm dark:bg-muted/15",children:[f?(0,t.jsx)("div",{className:"px-3 py-2.5 text-foreground/90",children:(0,t.jsx)(Sn,{softBreaks:!0,linkIssueReferences:!0,children:e.text})}):null,p.length>0?(0,t.jsx)("div",{className:W("bg-background/50 dark:bg-background/30",f&&"border-t border-border/70"),children:(0,t.jsx)(b1e,{sections:p,tone:u})}):null,v?(0,t.jsx)("div",{className:"flex justify-end border-t border-border/70 bg-background/50 px-3 py-2 dark:bg-background/30",children:(0,t.jsx)(L,{type:"button",size:"xs",onClick:j,disabled:n,"data-testid":"task-chat-no-live-path-try-again",children:n?"Trying again...":"Try again"})}):null]}):null]})}r(hdt,"TaskChatSystemNotice");function rV({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)(gr,{agent:n,name:e,size:24})}),(0,t.jsx)("span",{className:"text-sm font-semibold text-foreground",children:e})]})}r(rV,"TaskChatAgentIdentity");function Wse(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(Wse,"galleryItemForMedia");function Vse(e){return e.filter((s,n)=>e.findIndex(a=>s.id&&a.id===s.id||a.url===s.url)===n)}r(Vse,"uniqueAttachmentRefs");function y1e(e){return p1e(e.item.id)??(0,t.jsx)(pdt,{...e})}r(y1e,"TaskChatBubble");function pdt({item:e,animateEntry:s=!0,queuedAction:n,attachedTurn:a,beforeTurn:i,hideAgentIdentity:o=!1,actions:l,attachments:c=[],onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u}){const h=Rp(),p=(0,m.useContext)(Eg),f=(0,m.useContext)(Xv),[x,b]=(0,m.useState)(null),v=(0,m.useCallback)(z=>{f?.(z)||b(z)},[f]);if(e.interstitial)return null;if(e.author==="system")return(0,t.jsx)(hdt,{item:e,onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u});const j=e.author==="human",N=j&&e.sourceChannel==="imessage-photon",{refs:w,text:k}=QVe(e.text),S=HVe(k),C=GVe(k),I=RZ(w,c),R=RZ(S,c),T=c.filter(z=>z.issueCommentId===e.id).map(z=>({id:z.id,name:z.originalFilename?.trim()||"attachment",url:z.contentPath,contentType:z.contentType,byteSize:z.byteSize,openPath:z.openPath,downloadPath:z.downloadPath})),A=Vse([...R,...I.filter(D2),...T.filter(D2)]),D=Vse([...I.filter(z=>!D2(z)),...T.filter(z=>!D2(z))]),M=[...A,...D.filter(z=>Vu(z.contentType,z.name))],B=x!==null&&!M.some(z=>z.url===x)?[Wse(x)]:M.map(z=>Wse(z.url,z.name,z)),E=x===null?-1:Math.max(0,M.findIndex(z=>z.url===x));return(0,t.jsxs)("div",{className:W("flex w-full flex-col gap-1",s&&"tc-enter-bubble",j?"items-end":"items-start"),children:[i?(0,t.jsx)("div",{className:"w-full pb-1",children:i}):null,!j&&e.authorName&&!o?(0,t.jsx)(rV,{agentName:e.authorName,agentIcon:e.agentIcon,agent:e.agent}):null,C.length>0?(0,t.jsx)("div",{"data-testid":j?"task-chat-human-bubble":"task-chat-agent-bubble",className:W("break-words py-2 text-sm",j?"max-w-(--pct-85) rounded-2xl rounded-br-sm bg-(--liveness-blue) px-3.5 text-white":"w-full bg-transparent px-1 text-foreground"),children:(0,t.jsx)(Sn,{className:j?"paperclip-markdown-on-accent":void 0,softBreaks:!0,linkIssueReferences:!0,onImageClick:v,children:C})}):null,A.length>0?(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) flex-col gap-2","data-testid":"task-chat-bubble-media",children:[(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["Images · ",A.length]}),(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-2",children:[A.slice(0,A.length>4?3:4).map((z,$)=>(0,t.jsx)("button",{type:"button",className:"group aspect-video min-w-0 overflow-hidden rounded-md bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open ${z.name||`image ${$+1}`}`,onClick:r(()=>v(z.url),"onClick"),children:(0,t.jsx)("img",{src:z.openPath??z.url,alt:z.name,loading:"lazy",className:"h-full w-full object-cover transition-transform group-hover:scale-(--s-1_02)"})},z.url)),A.length>4?(0,t.jsxs)("button",{type:"button",className:"aspect-video min-w-0 rounded-md bg-muted text-sm font-semibold text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open ${A.length-3} more screenshots`,onClick:r(()=>v(A[3].url),"onClick"),children:["+",A.length-3]}):null]}),(0,t.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:A.map(z=>z.name||"image").join(" · ")})]}):null,D.length>0?(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) flex-col gap-2",children:[(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:["Files · ",D.length]}),(0,t.jsx)(D9,{"data-testid":"task-chat-bubble-attachments",children:D.map(z=>{const $=owe(z),q=$.icon,U=L9(z.byteSize),O=Vu(z.contentType,z.name);return(0,t.jsxs)(T9,{size:"sm",children:[(0,t.jsx)(R9,{className:O?"aspect-video group-data-[size=sm]/attachment:w-20":void 0,children:O?(0,t.jsx)(xA,{artifact:{title:z.name,contentPath:z.openPath??z.url,mediaKind:"video"}}):(0,t.jsx)(q,{"aria-hidden":!0})}),(0,t.jsxs)(E9,{children:[(0,t.jsx)(P9,{className:"max-w-48",children:z.name}),(0,t.jsx)(M9,{className:"max-w-48",children:U?`${$.label} · ${U}`:$.label})]}),(0,t.jsx)(nwe,{"aria-label":`Open ${z.name}`,onClick:O?()=>v(z.url):void 0,render:O?(0,t.jsx)("button",{type:"button"}):(0,t.jsx)("a",{href:z.openPath??z.url,onClick:r(K=>{p&&z.id&&sj({contentType:z.contentType??"",originalFilename:z.name})&&!K.metaKey&&!K.ctrlKey&&!K.shiftKey&&!K.altKey&&(K.preventDefault(),p(z.id,z.name))},"onClick"),target:"_blank",rel:"noreferrer"})})]},z.url)})})]}):null,!j&&e.verificationCaveats?.length?(0,t.jsxs)("div",{className:"mx-1 w-(--sz-calc-7) rounded-md border border-amber-500/25 bg-amber-500/5 px-3 py-2 text-xs","data-testid":"task-chat-verification-caveats",children:[(0,t.jsx)("p",{className:"font-medium text-amber-800 dark:text-amber-200",children:"Verification caveat"}),(0,t.jsx)("ul",{className:"mt-1 space-y-1 text-muted-foreground",children:e.verificationCaveats.map((z,$)=>(0,t.jsxs)("li",{children:[(0,t.jsx)("span",{className:"font-mono text-foreground",children:z.commandOrCheck}),z.reasonCode?` · ${z.reasonCode.replaceAll("_"," ")}`:"",z.detail?(0,t.jsx)("span",{className:"block",children:z.detail}):null]},`${z.commandOrCheck}:${$}`))})]}):null,e.optimistic?(0,t.jsxs)("span",{className:"flex items-center gap-1 px-1 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)("span",{children:e.optimistic==="queued"?"Queued":"Sending…"}),e.optimistic==="queued"?n:null]}):a?(0,t.jsx)("div",{className:"self-stretch","data-testid":"task-chat-bubble-attached-turn",children:a}):l?h?(0,t.jsxs)("div",{className:"flex w-full items-center justify-between gap-2 px-1",children:[e.timestamp||N?(0,t.jsxs)("span",{className:"text-(length:--text-micro) text-muted-foreground",children:[N?"Sent from iMessage":null,N&&e.timestamp?" · ":null,e.timestamp]}):null,l]}):(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[l,e.timestamp||N?(0,t.jsxs)("span",{className:"px-1 text-(length:--text-micro) text-muted-foreground",children:[N?"Sent from iMessage":null,N&&e.timestamp?" · ":null,e.timestamp]}):null]}):e.timestamp||N?(0,t.jsxs)("span",{className:"px-1 text-(length:--text-micro) text-muted-foreground",children:[N?"Sent from iMessage":null,N&&e.timestamp?" · ":null,e.timestamp]}):null,x!==null&&E>=0?(0,t.jsx)(nj,{items:B,initialIndex:E,open:!0,onOpenChange:r(z=>{z||b(null)},"onOpenChange")}):null]})}r(pdt,"TaskChatBubbleContent");function Hse(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(Hse,"turnSummaryMetrics");function Gse({item:e,renderChild:s,timestampPrefix:n,leading:a}){const i=Rp(),o=!e.settled&&e.liveStatus!=null;if(e.standaloneHeader)return(0,t.jsxs)("div",{"data-testid":"task-chat-turn","data-settled":e.settled?"true":"false",children:[e.agentName||!e.historical?(0,t.jsxs)("div",{className:"flex min-h-8 w-full min-w-0 items-center gap-2 pb-1 pt-1.5 text-sm text-muted-foreground","data-testid":"task-chat-turn-summary","data-turn-position":"identity",children:[e.agentName?(0,t.jsx)(rV,{agentName:e.agentName,agentIcon:e.agentIcon,agent:e.agent}):null,e.historical?null:(0,t.jsxs)("span",{className:"min-w-0 truncate",children:[e.continuedAfterSteering?"Continued after steering · ":"",e.summary.durationLabel?`${e.summary.failed?"Stopped":"Worked"} for ${e.summary.durationLabel}`:e.summary.failed?"Stopped":"Worked"]})]}):null,e.items.length>0?(0,t.jsx)("div",{className:"flex min-w-0 flex-col gap-2 py-1","data-testid":"task-chat-turn-timeline",children:e.items.map(C=>(0,t.jsx)("div",{className:"min-w-0","data-testid":"task-chat-turn-timeline-row","data-timeline-row-id":C.id,"data-thread-anchor":C.id,children:s(C)},C.id))}):null,e.finalResponse?(0,t.jsx)("div",{className:"w-full","data-testid":"task-chat-final-response",children:(0,t.jsx)("div",{className:"break-words px-1 py-2 text-sm text-foreground","data-testid":"task-chat-agent-bubble",children:(0,t.jsx)(Sn,{softBreaks:!0,linkIssueReferences:!0,children:e.finalResponse.text})})}):null]});const l=e.settled?e.items.filter(C=>C.kind==="protocol"&&C.surface==="runtime_request"):[],c=new Set(l.map(C=>C.id)),d=l.length>0?e.items.filter(C=>!c.has(C.id)):e.items,[u,h]=(0,m.useState)(()=>!e.settled&&e.liveStatus==null),[p,f]=(0,m.useState)(u);u&&!p&&f(!0);const[x,b]=(0,m.useState)(e.settled),[v,j]=(0,m.useState)(o);o&&!v&&j(!0),e.settled!==x&&(b(e.settled),e.settled&&!v&&h(!1));const N=d.length>0,w=(e.settled||o)&&!u,k=e.summary.failed?Fn:gs,S=e.settled&&(!e.historical||N)?(0,t.jsxs)("button",{type:"button",onClick:r(()=>h(C=>!C),"onClick"),"aria-expanded":u,className:W("group flex w-full items-center gap-2 px-1 text-muted-foreground transition-colors hover:text-foreground",e.standaloneHeader?"border-b border-border/70 py-2 text-sm":"py-0.5 text-xs",i&&"min-w-0"),"data-testid":"task-chat-turn-summary",children:[n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-(length:--text-micro)",children:n}),(0,t.jsx)("span",{"aria-hidden":!0,className:"text-(length:--text-micro)",children:"·"})]}):null,!e.standaloneHeader&&!e.historical?(0,t.jsx)(k,{className:"h-3.5 w-3.5 shrink-0"}):null,(0,t.jsx)("span",{children:e.historical?"Activity":e.standaloneHeader&&e.summary.durationLabel?`${e.summary.failed?"Stopped":"Worked"} for ${e.summary.durationLabel}`:e.summary.failed?"Stopped":"Worked"}),!e.standaloneHeader&&Hse(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:Hse(e.summary)})}):null,(0,t.jsx)(En,{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)(n1e,{item:e.liveStatus,chevronOpen:N?u:void 0,onToggle:N?()=>h(C=>!C):void 0}):null;return(0,t.jsxs)("div",{"data-testid":"task-chat-turn","data-settled":e.settled?"true":"false",children:[a?i?(0,t.jsxs)("div",{className:"flex w-full items-center justify-between gap-2",children:[(0,t.jsx)("div",{className:"min-w-0",children:S}),(0,t.jsx)("div",{className:"shrink-0",children:a})]}):(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[a,S]}):S,(0,t.jsx)("div",{className:"tc-turn-fold","data-folded":w?"true":"false","aria-hidden":w,children:(0,t.jsx)("div",{children:(0,t.jsx)("div",{className:"flex flex-col gap-2 pt-1",children:p&&d.map(C=>(0,t.jsx)("div",{children:s(C)},C.id))})})}),l.length>0?(0,t.jsx)("div",{className:"flex flex-col gap-2 pt-2","data-testid":"task-chat-turn-persistent-history",children:l.map(C=>(0,t.jsx)("div",{children:s(C)},C.id))}):null]})}r(Gse,"TaskChatTurn");var fdt={session_start:Mu,interrupted:F7,turn_boundary:_g};function j1e({item:e,onTryAgain:s,tryAgainPending:n=!1}){const[a,i]=(0,m.useState)(!1),o=(0,m.useId)(),l=Rp(),c=e.tone==="neutral"?Tg:fdt[e.variant],d=e.variant==="interrupted"&&e.tone!=="neutral",u=e.createdAtIso?ao(e.createdAtIso):void 0,h=r(()=>{Promise.resolve().then(()=>s?.()).catch(()=>{})},"handleTryAgain");return e.collapsible?(0,t.jsxs)("div",{className:"tc-enter-marker flex flex-col items-start py-1 text-xs text-muted-foreground","data-testid":"task-chat-collapsible-marker",children:[(0,t.jsxs)("div",{className:"flex max-w-(--pct-85) items-center gap-1.5",children:[(0,t.jsxs)("button",{type:"button",onClick:r(()=>i(p=>!p),"onClick"),"aria-expanded":a,"aria-controls":o,className:W("flex min-w-0 items-center gap-1.5 rounded-md px-2 py-0.5",d?"text-destructive":"text-muted-foreground","hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"),children:[(0,t.jsx)(c,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),(0,t.jsx)("span",{className:"truncate font-medium",children:e.label}),u?(0,t.jsxs)("span",{className:"shrink-0 text-muted-foreground/70",children:["· ",u]}):null,(0,t.jsx)(nn,{className:W("tc-notice-chevron h-3.5 w-3.5 shrink-0 transition-transform",a&&"rotate-180"),"aria-hidden":!0})]}),s&&!a?(0,t.jsx)(L,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}),a?(0,t.jsxs)("div",{id:o,"data-testid":"task-chat-collapsible-marker-details",className:"mt-1 w-full max-w-(--pct-85) overflow-hidden rounded-lg border border-border bg-muted/25 text-left text-sm dark:bg-muted/15",children:[e.detail?(0,t.jsx)("div",{className:"px-3 py-2.5 text-foreground/90",children:e.detail}):null,e.runHref||e.planHref||s?(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 border-t border-border/70 bg-background/50 px-3 py-2 dark:bg-background/30",children:[e.planHref?(0,t.jsx)(L,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(Ke,{to:e.planHref,children:"View saved plan"})}):null,e.runHref?(0,t.jsx)(L,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(Ke,{to:e.runHref,children:"View run"})}):null,s?(0,t.jsx)(L,{type:"button",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}):null]}):null]}):(0,t.jsxs)("div",{className:"tc-enter-marker flex items-center gap-2 py-1 text-xs text-muted-foreground",role:l?"separator":void 0,"aria-label":l?e.label:void 0,children:[(0,t.jsx)("span",{className:W("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")}),(0,t.jsxs)("span",{className:W("flex items-center gap-1.5",d&&"text-destructive"),children:[(0,t.jsx)(c,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{className:"font-medium",children:e.label}),e.detail?(0,t.jsxs)("span",{className:"text-muted-foreground",children:["· ",e.detail]}):null,s?(0,t.jsx)(L,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:n,"data-testid":"task-chat-run-failed-try-again",children:n?"Trying again...":"Try again"}):null]}),(0,t.jsx)("span",{className:W("h-px flex-1",d?"border-t border-dashed border-destructive/50":"bg-border")})]})}r(j1e,"TaskChatMarker");var w1e=(0,m.createContext)(null);function aV(e,s){const n=(0,m.useContext)(w1e),[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(aV,"useTaskChatExpansion");var xdt={pending:{Icon:rt,spin:!1,tone:"text-muted-foreground"},in_progress:{Icon:rt,spin:!0,tone:"text-(--status-agent-running)"},completed:{Icon:gs,spin:!1,tone:"text-muted-foreground"},failed:{Icon:Fn,spin:!1,tone:"text-destructive"},interrupted:{Icon:Fn,spin:!1,tone:"text-muted-foreground"}};function k1e({item:e}){const{Icon:s,spin:n,tone:a}=xdt[e.status],i=hN(e.rawName??e.name).icon,[o,l]=aV(e.id,!1),c=!!(e.target||e.detail||e.diff);return(0,t.jsxs)("div",{"data-testid":"task-chat-tool-card",className:"flex min-w-0 max-w-full flex-col text-xs",children:[(0,t.jsxs)("button",{type:"button",onClick:c?()=>l(d=>!d):void 0,"aria-expanded":c?o:void 0,className:W("group/tool -mx-1.5 flex min-h-6 w-full min-w-0 max-w-full items-center gap-2 overflow-hidden rounded-sm px-1.5 py-1 text-left leading-none text-muted-foreground",c?"cursor-pointer transition-colors hover:bg-muted/60 hover:text-foreground":"cursor-default"),children:[(0,t.jsx)("span",{className:"flex w-5 shrink-0 items-center justify-center",children:(0,t.jsx)(i,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0,"data-testid":"task-chat-tool-icon"})}),(0,t.jsxs)("span",{className:"flex min-w-0 flex-1 items-baseline gap-2 overflow-hidden",children:[(0,t.jsx)("span",{className:"shrink-0 font-medium leading-4",children:e.name}),e.target?(0,t.jsx)("span",{className:"task-chat-collapsed-line-fade min-w-0 flex-1 font-mono text-(length:--text-micro) leading-4",children:e.target}):null]}),(0,t.jsxs)("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[e.decision?(0,t.jsxs)("span",{className:W("flex items-center gap-1 text-(length:--text-micro)",e.decision==="allowed"?"text-(--status-task-icon-done)":"text-destructive"),children:[e.decision==="allowed"?(0,t.jsx)(Di,{className:"h-3 w-3"}):(0,t.jsx)(W7,{className:"h-3 w-3"}),e.decision]}):null,c?(0,t.jsx)(En,{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(k1e,"TaskChatToolCard");function iV({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)(M7,{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(iV,"TaskChatUsageReadout");function Up(e,...s){return e.details.find(n=>s.includes(n.label))?.value}r(Up,"providerDetail");function cO(e){if(!(!e||Gd(e)||/^tool(?:\s+|_)call\b/i.test(e)))return e}r(cO,"meaningfulToolDetail");function gdt(e){const s=e.summary??Up(e,"Query","URL","Target","Name","Reference","Reason","Summary");switch(e.family){case"research":{const n=Up(e,"Action")?.toLowerCase();return n==="open_page"?{icon:oa,runningLabel:"Opening a web page",completedLabel:"Opened a web page",failedLabel:"Couldn’t open the web page",interruptedLabel:"Stopped opening the web page",detail:s}:n==="find_in_page"?{icon:oa,runningLabel:"Searching the page",completedLabel:"Searched the page",failedLabel:"Page search failed",interruptedLabel:"Page search stopped",detail:s}:{icon:oa,runningLabel:"Searching the web",completedLabel:"Searched the web",failedLabel:"Web search failed",interruptedLabel:"Web search stopped",detail:s}}case"tool_execution":{const n=Up(e,"Name"),a=Up(e,"Target"),i=Up(e,"Progress"),o=wy({name:n,transport:Up(e,"Transport"),namespace:Up(e,"Namespace"),operation:Up(e,"Operation"),target:a,progress:i}),l=cO(e.summary)??cO(i)??cO(a),c=!!(l&&n&&jk(l)===jk(n)),d=n?JW(n)?.name??n:o.displayName,u=o.sourceLabel?`${o.sourceLabel} · ${d}`:n&&!Gd(n)&&jk(n)!==o.runningLabel.replace(/^Running /,"")?n:void 0;return{icon:o.icon,runningLabel:o.runningLabel,completedLabel:o.completedLabel,failedLabel:o.failedLabel,interruptedLabel:o.interruptedLabel,detail:[c?void 0:l,u].filter(Boolean).join(" · ")||void 0}}case"plan":return{icon:Hy,runningLabel:"Updating the plan",completedLabel:"Updated the plan",failedLabel:"Plan update failed",interruptedLabel:"Plan update stopped",detail:s};case"delegation":{const n=Up(e,"Action")?.toLowerCase();return n==="message"?{icon: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:no,runningLabel:"Switching models",completedLabel:"Switched models",failedLabel:"Model switch failed",interruptedLabel:"Model switch stopped",detail:s}:{icon:no,runningLabel:"Verifying the model",completedLabel:"Verified the model",failedLabel:"Model verification failed",interruptedLabel:"Model verification stopped",detail:s};case"context":return{icon:PI,runningLabel:"Compacting context",completedLabel:"Compacted context",failedLabel:"Context compaction failed",interruptedLabel:"Context compaction stopped",detail:s};case"artifact":return e.eventType==="artifact.viewed"?{icon:a_,runningLabel:"Viewing an artifact",completedLabel:"Viewed an artifact",failedLabel:"Couldn’t view the artifact",interruptedLabel:"Artifact view stopped",detail:s}:{icon:a_,runningLabel:"Generating an artifact",completedLabel:"Generated an artifact",failedLabel:"Artifact generation failed",interruptedLabel:"Artifact generation stopped",detail:s};case"review":return Up(e,"State")?.toLowerCase()==="exited"?{icon:hX,runningLabel:"Leaving review mode",completedLabel:"Left review mode",failedLabel:"Couldn’t leave review mode",interruptedLabel:"Review-mode change stopped",detail:s}:{icon:hX,runningLabel:"Entering review mode",completedLabel:"Entered review mode",failedLabel:"Couldn’t enter review mode",interruptedLabel:"Review-mode change stopped",detail:s};case"hook":return{icon:io,runningLabel:"Running a hook",completedLabel:"Ran a hook",failedLabel:"Hook failed",interruptedLabel:"Hook stopped",detail:s};case"memory":return{icon:GN,runningLabel:"Checking memory",completedLabel:"Referenced memory",failedLabel:"Memory lookup failed",interruptedLabel:"Memory lookup stopped",detail:s};case"safety":return{icon:Di,runningLabel:"Reviewing safety",completedLabel:"Reviewed safety",failedLabel:"Safety review failed",interruptedLabel:"Safety review stopped",detail:s};case"terminal":return{icon:fg,runningLabel:"Sending terminal input",completedLabel:"Sent terminal input",failedLabel:"Terminal input failed",interruptedLabel:"Terminal input stopped",detail:s};case"wait":return{icon:au,runningLabel:"Waiting",completedLabel:"Finished waiting",failedLabel:"Wait failed",interruptedLabel:"Wait stopped",detail:s};case"provider_notice":return{icon:Es,runningLabel:"Provider notice",completedLabel:"Provider notice",failedLabel:"Provider error",interruptedLabel:"Provider notice",detail:s}}}r(gdt,"providerActivityPresentation$1");function bdt(e){const s=e.totals.files||e.files.length,n=s>0?`${s} ${s===1?"file":"files"}`:void 0;return{icon:CM,runningLabel:"Editing files",completedLabel:"Edited files",detail:n}}r(bdt,"workspaceChangePresentation");function vdt(e){return{icon:Ha,runningLabel:"Referencing a file",completedLabel:"Referenced a file",detail:e.line==null?e.path:`${e.path}:${e.line}`}}r(vdt,"workspaceFilePresentation");function ydt(e){return{icon:e.resourceKind==="document"?Ha:Gk,runningLabel:"Saving a resource",completedLabel:e.resourceKind==="document"?"Added a document":"Added a deliverable",detail:e.title}}r(ydt,"resourcePresentation");function N1e(e){switch(e.surface){case"provider_activity":return gdt(e);case"workspace_change":return bdt(e);case"workspace_file":return vdt(e);case"resource":return ydt(e);case"runtime_request":case"run_result":case"run_terminal":return null}}r(N1e,"protocolActivityPresentation");function S1e(e){return e.surface==="provider_activity"?e.status==="running":e.surface==="workspace_change"?!e.complete:!1}r(S1e,"protocolActivityIsRunning");function jdt(e,s){return e.surface!=="provider_activity"?S1e(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(jdt,"protocolActivityLabel");var wdt={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 kdt(e){const s=new Map,n=r((d,u,h=0)=>{const p=s.get(d);(!p||h<p.order)&&s.set(d,{label:d,icon:u,order:h})},"add"),a=[];for(const[d,u]of e.entries())if(u.kind==="tool"){const h=wy({name:u.rawName??u.name,target:u.target});a.push({...h,order:d,completed:u.status==="completed"})}else if(u.kind==="protocol")if(u.surface==="provider_activity"&&u.family==="tool_execution"){const h=r(f=>u.details.find(x=>x.label===f)?.value,"value"),p=wy({name:h("Name"),operation:h("Operation"),transport:h("Transport"),namespace:h("Namespace"),target:h("Target")});a.push({...p,order:d,completed:u.status==="completed"})}else{const h=N1e(u);if(!h)continue;n({research:"Searched the web",plan:"Worked on a plan",delegation:"Worked with agents",artifact:"Worked with artifacts",context:"Managed context",memory:"Checked memory",model_identity:"Checked model settings",review:"Worked in review mode",hook:"Ran hooks",safety:"Reviewed safety",terminal:"Ran commands",wait:"Waited",provider_notice:"Received a provider update",workspace_change:"Worked on files",workspace_file:"Referenced files",resource:"Added resources"}[u.surface==="provider_activity"?u.family:u.surface]??"Used tools",h.icon,d)}const i=new Set(a.filter(d=>d.completed).map(d=>d.family));for(const d of a){const u=i.has(d.family);n(d.family==="read"&&!u?"Checked files":d.family==="edit"&&!u?"Worked on files":wdt[d.family],d.icon,d.order)}s.size||(e.some(d=>d.kind==="thinking")?n("Thought through the task",Xx):e.some(d=>d.kind==="marker")?n("Activity stopped",Td):n("Recorded usage",M7));const o=[...s.values()].sort((d,u)=>d.order-u.order),l=r(d=>d.map((u,h)=>h?u.charAt(0).toLowerCase()+u.slice(1):u).join(", "),"join"),c=l(o.map(d=>d.label));return{label:o.length>3?`${l(o.slice(0,2).map(d=>d.label))}, and more`:c,fullLabel:c,icon:o.length===1?o[0].icon:zl}}r(kdt,"completedActivitySummary");var Qse=5,Ndt=8;function Sdt(e,s=!1){return s&&(e==="blocked"||e==="failed")?(0,t.jsx)(pg,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0}):e==="in_progress"?(0,t.jsx)(rt,{className:"h-3 w-3 animate-spin text-(--status-agent-running)","aria-hidden":!0}):e==="completed"?(0,t.jsx)(gs,{className:"h-3 w-3 text-(--status-task-icon-done)","aria-hidden":!0}):e==="blocked"||e==="failed"?(0,t.jsx)(Fn,{className:"h-3 w-3 text-destructive","aria-hidden":!0}):(0,t.jsx)(pg,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0})}r(Sdt,"stepStatusIcon");function C1e({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(C1e,"DetailList");function Cdt(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}r(Cdt,"sourceHostname");function _dt({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,Qse),l=e.links.length-o.length;return(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-2.5",children:[a?(0,t.jsxs)("div",{className:"min-w-0 rounded-sm bg-muted/40 px-2.5 py-2","data-testid":"task-chat-research-query",children:[(0,t.jsx)("p",{className:"text-(length:--text-nano) font-medium uppercase tracking-wide text-muted-foreground",children:"Query"}),(0,t.jsx)("p",{className:"mt-0.5 min-w-0 break-words font-mono text-(length:--text-micro) text-foreground",children:a.value})]}):null,e.links.length>0?(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("p",{className:"mb-1 text-(length:--text-nano) font-medium uppercase tracking-wide text-muted-foreground",children:[e.links.length," ",e.links.length===1?"result":"results"]}),(0,t.jsx)("ol",{className:"divide-y divide-border/60","aria-label":"Research sources",children:o.map((c,d)=>(0,t.jsxs)("li",{className:"min-w-0 py-1.5 first:pt-0 last:pb-0",children:[(0,t.jsxs)("a",{className:"flex min-w-0 items-center gap-1 font-medium text-foreground hover:underline",href:c.href,target:"_blank",rel:"noreferrer",children:[(0,t.jsx)("span",{className:"truncate",children:c.label}),(0,t.jsx)(Vn,{className:"h-3 w-3 shrink-0","aria-hidden":!0})]}),(0,t.jsxs)("p",{className:"mt-0.5 flex min-w-0 gap-2 text-muted-foreground",children:[(0,t.jsx)("span",{className:"shrink-0",children:Cdt(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>Qse?(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)(C1e,{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(_dt,"ResearchDetails");function Idt({item:e,neutral:s=!1}){return e.family==="research"?(0,t.jsx)(_dt,{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:Sdt(n.status,s)}),(0,t.jsx)("span",{className:W("min-w-0",n.status==="completed"&&"text-muted-foreground line-through"),children:n.label})]},n.id))}):null,e.links.length>0?(0,t.jsx)("ul",{className:"flex flex-col gap-1.5","aria-label":"Research sources",children:e.links.map(n=>(0,t.jsxs)("li",{children:[(0,t.jsxs)("a",{className:"inline-flex min-w-0 items-center gap-1 font-medium text-primary hover:underline",href:n.href,target:"_blank",rel:"noreferrer",children:[(0,t.jsx)("span",{className:"truncate",children:n.label}),(0,t.jsx)(Vn,{className:"h-3 w-3 shrink-0","aria-hidden":!0})]}),n.description?(0,t.jsx)("p",{className:"mt-0.5 text-muted-foreground",children:n.description}):null]},n.href))}):null,e.children.length>0?(0,t.jsx)("ul",{className:"flex flex-col gap-1.5","aria-label":"Delegated agents",children:e.children.map(n=>(0,t.jsxs)("li",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,t.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium text-foreground",children:n.title}),(0,t.jsx)("span",{className:"capitalize text-muted-foreground",children:n.status}),n.metadata?(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro)",children:n.metadata}):null]}),n.summary?(0,t.jsx)("span",{className:"text-muted-foreground",children:n.summary}):null]},n.id))}):null,e.details.length>0?(0,t.jsx)(C1e,{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(Idt,"ProviderDetails");function Adt({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,Ndt),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(Adt,"WorkspaceChangeDetails");function Tdt({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)(Fxe,{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(Tdt,"WorkspaceFileDetails");function _1e(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)(Idt,{item:e,neutral:s}):null;case"workspace_change":return(0,t.jsx)(Adt,{item:e});case"workspace_file":return(0,t.jsx)(Tdt,{item:e});case"resource":case"runtime_request":case"run_result":case"run_terminal":return null}}r(_1e,"detailContent");function I1e(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(I1e,"safeActivityHref");function Rdt(e){return e.surface==="resource"?!!I1e(e.href):_1e(e)!==null||e.surface==="provider_activity"&&!!e.summary?.trim()}r(Rdt,"hasTaskChatProtocolActivityDetails");function Edt({item:e,neutral:s=!1}){const n=_1e(e,s);if(e.surface==="resource"){const a=I1e(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(Edt,"TaskChatProtocolActivityDetails");function A1e(e,s){if(e.kind==="tool"){const d=wy({name:e.rawName??e.name,target:e.target}),u=s&&(e.status==="pending"||e.status==="in_progress");return{icon:d.icon,label:e.status==="failed"?d.failedLabel:e.status==="interrupted"?d.interruptedLabel:u?d.runningLabel:d.completedLabel,target:e.target,mono:!0,running:u}}if(e.kind==="thinking"){const d=s&&!!e.streaming;return{icon:Xx,label:d?"Thinking":"Thought",target:e.lines.filter(u=>u.trim()).at(-1)?.trim(),mono:!1,running:d}}if(e.kind==="protocol"){const d=N1e(e);return d?{icon:d.icon,label:jdt(e,d),target:d.detail,mono:!0,running:s&&S1e(e)}:null}if(e.kind==="marker")return{icon:Td,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:M7,label:e.label??"Token usage",target:c||e.detail,mono:!1,running:!1}}r(A1e,"presentation");function S6({item:e,active:s}){const n=A1e(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(S6,"ActivityContent");function Pdt({item:e,active:s}){const n=SNe(),[a,i]=(0,m.useState)({current:e,previous:null});return a.current.id!==e.id?i({current:e,previous:n?null:a.current}):a.current!==e&&i({...a,current:e}),(0,t.jsxs)("span",{className:"relative flex h-8 min-w-0 flex-1 items-center overflow-hidden","aria-live":"polite","aria-atomic":"true","data-testid":"task-chat-activity-viewport",children:[a.previous&&!n?(0,t.jsx)("span",{className:"runner-activity-roll-out absolute inset-0 flex items-center","aria-hidden":"true",onAnimationEnd:r(()=>i(o=>o.current.id===e.id?{...o,previous:null}:o),"onAnimationEnd"),children:(0,t.jsx)(S6,{item:a.previous,active:!1})},`exit-${e.id}`):null,(0,t.jsx)("span",{className:W("relative flex w-full min-w-0 items-center",a.previous&&!n&&"runner-activity-roll-in"),children:(0,t.jsx)(S6,{item:e,active:s})},e.id)]})}r(Pdt,"RollingActivity");function Mdt({item:e}){return e.kind==="thinking"?(0,t.jsx)(Sn,{softBreaks:!0,children:e.lines.join(`
|
|
357
357
|
`)}):e.kind==="usage"?(0,t.jsx)(iV,{item:e}):e.kind==="protocol"?(0,t.jsx)(Edt,{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(Mdt,"ActivityDetails");function Ddt(e){return e.kind==="protocol"?Rdt(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(Ddt,"hasActivityDetails");function Ldt({item:e,active:s}){const[n,a]=aV(`runner-detail:${e.id}`,!1),i=(0,m.useId)(),o=Ddt(e),l=(0,t.jsx)(S6,{item:e,active:s});return(0,t.jsxs)("li",{className:"min-w-0","data-activity-item-id":e.id,children:[o?(0,t.jsxs)("button",{type:"button",className:"flex h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:r(()=>a(!n),"onClick"),"aria-expanded":n,"aria-controls":n?i:void 0,children:[l,(0,t.jsx)(En,{className:W("size-3.5 shrink-0",n&&"rotate-90"),"aria-hidden":"true"})]}):(0,t.jsx)("div",{className:"flex h-8 w-full min-w-0 items-center gap-2 text-muted-foreground",children:l}),o&&n?(0,t.jsx)("div",{id:i,className:"flex min-w-0 flex-col gap-2 overflow-hidden rounded-md bg-muted/40 p-3 text-xs leading-relaxed text-muted-foreground","data-testid":"task-chat-runner-activity-detail",children:(0,t.jsx)(Mdt,{item:e})}):null]})}r(Ldt,"ExpandedActivity");function W_({item:e,defaultExpanded:s=!1}){const[n,a]=aV(e.id,s),i=(0,m.useId)(),o=e.items.filter(h=>A1e(h,!1)!==null),l=o.at(-1),c=kdt(o),d=c.icon,u=`${o.length} ${o.length===1?"activity":"activities"}`;return(0,t.jsxs)("section",{className:"flex min-w-0 flex-col gap-2","data-testid":"task-chat-activity-phase","data-activity-group":e.id,"data-expanded":n,children:[e.interstitial?(0,t.jsx)("div",{className:"min-w-0 px-1 text-sm text-foreground/90","data-testid":"task-chat-phase-interstitial",children:(0,t.jsx)(Sn,{softBreaks:!0,linkIssueReferences:!0,children:e.interstitial.text})}):null,l?(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsxs)("button",{type:"button",className:"flex min-h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":"task-chat-activity-phase-toggle",onClick:r(()=>a(!n),"onClick"),"aria-expanded":n,"aria-controls":n?i:void 0,"aria-label":`${n?"Collapse":"Expand"} ${e.active?u:`${c.fullLabel.toLowerCase()} (${u})`}`,children:[e.active?n?(0,t.jsxs)("span",{className:"flex min-h-8 flex-1 items-center gap-2 text-xs",children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:(0,t.jsx)(nn,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsx)("span",{children:u})]}):(0,t.jsx)(Pdt,{item:l,active:e.active}):(0,t.jsxs)("span",{className:"flex h-8 min-w-0 flex-1 items-center gap-2 text-xs","data-completed-summary":!0,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:(0,t.jsx)(d,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsx)("span",{className:"truncate",title:c.fullLabel,children:c.label})]}),(0,t.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs",children:[n?u:e.active?o.length:null,(0,t.jsx)(En,{className:W("size-3.5",n&&"rotate-90"),"aria-hidden":"true"})]})]}),n?(0,t.jsx)("ol",{id:i,className:"flex min-w-0 flex-col gap-1","aria-label":"Activity history","data-testid":"task-chat-runner-activity-list",children:o.map((h,p)=>(0,t.jsx)(Ldt,{item:h,active:e.active&&p===o.length-1},h.id))}):null]}):null]})}r(W_,"TaskChatRunnerActivityGroup");var $dt=new Set(["failed","timed_out","cancelled","interrupted","succeeded"]);function Zv(e){return e!=null&&$dt.has(e)}r(Zv,"isTerminalRunStatus$1");function Yse(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(Yse,"splitTranscriptAtAnchors");function Odt(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(Odt,"flattenSelfTalk");function Fdt(e){return e==="add"?"add":e==="remove"?"remove":"context"}r(Fdt,"diffKind");var Bdt=["file_path","path","notebook_path","command","pattern","query","url","prompt","description","skill","subject"],YC=96;function N0(e,s){const n=e.replace(/\s+/g," ").trim();return n.length>s?`${n.slice(0,s-1)}…`:n}r(N0,"clip");function zdt(e){if(e==null)return;if(typeof e=="string")return e.trim()?N0(e,YC):void 0;if(typeof e!="object")return N0(String(e),YC);const s=e;for(const a of Bdt){const i=s[a];if(typeof i=="string"&&i.trim())return N0(i,YC)}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 N0(n.map(([a,i])=>`${a}: ${String(i)}`).join(", "),YC)}r(zdt,"summarizeToolInput$2");function dO(e){const s=(e??"").trim();return Gd(s)?"Unnamed tool":jk(s)}r(dO,"toolDisplayName");function qdt(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(qdt,"thoughtDurationLabel");function Udt(e,s,n){const a=s.split(`
|
|
358
358
|
`);if(!n||e.length===0){e.push(...a);return}e[e.length-1]=`${e[e.length-1]??""}${a[0]??""}`,e.push(...a.slice(1))}r(Udt,"appendThinkingText");var Jse=600,L1=8192;function tT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}r(tT,"objectRecord");function zc(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}r(zc,"stringValue");function Kdt(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(Kdt,"scalarValue");function Wdt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("_"," ").replace(/\b\w/g,s=>s.toUpperCase())}r(Wdt,"titleCaseKey$1");function Vdt(e){const s=zc(e);if(!s)return null;try{const n=new URL(s);return n.protocol==="http:"||n.protocol==="https:"?s:null}catch{return null}}r(Vdt,"safeHttpHref");var Hdt={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 T1e(e){for(const s of["planId","executionId","researchId","delegationId","routeId","verificationId","compactionId","artifactId","reviewId","hookId","citationId","waitId","noticeId"]){const n=zc(e.payload[s]);if(n)return`${e.family}:${n}`}return`${e.family}:${e.eventType}:${e.ts}`}r(T1e,"providerActivityKey");function Gdt(e,s,n){const a=[];for(const h of Hdt[e.family]){const p=Kdt(e.payload[h]);p&&(e.family==="tool_execution"&&h==="name"&&Gd(p)||e.family==="tool_execution"&&h==="progress"&&!C6(p)||a.push({label:Wdt(h),value:N0(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=tT(h);typeof p.name=="string"&&typeof p.value=="string"&&a.push({label:N0(p.name,160),value:N0(p.value,4e3),mono:!1})}const i=e.family==="plan"&&Array.isArray(e.payload.steps)?e.payload.steps.map(tT).slice(0,256).map((h,p)=>{const f=zc(h.status),x=f==="in_progress"||f==="completed"||f==="blocked"?f:"pending";return{id:zc(h.stepId)??`${s}:plan-step:${p}`,label:zc(h.body)??"Plan step",status:x}}):[],o=e.family==="research"&&Array.isArray(e.payload.sources)?e.payload.sources.map(tT).slice(0,64).flatMap(h=>{const p=Vdt(h.url);return p?[{label:zc(h.title)??p,href:p,description:zc(h.snippet)}]:[]}):[],l=e.family==="delegation"&&Array.isArray(e.payload.children)?e.payload.children.map(tT).slice(0,64).map((h,p)=>({id:zc(h.childId)??`${s}:delegation:${p}`,title:zc(h.role)??"Subagent",status:zc(h.status)??"unknown",metadata:[zc(h.model),zc(h.activitySummary)].filter(Boolean).join(" · ")||void 0,summary:zc(h.summary)})):[],c=e.family==="tool_execution"?zc(e.payload.output):void 0,d=e.payload.outputTruncated===!0||!!(c&&c.length>L1),u=e.summary&&e.summary!==e.eventType?e.summary:zc(e.payload.explanation)??zc(e.payload.progress)??zc(e.payload.message)??zc(e.payload.summary);return{id:`${s}:provider:${T1e(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,L1):void 0,outputTruncated:d,transcriptIndex:n}}r(Gdt,"providerActivityItem");function Kd(e,s){return e.details.find(n=>n.label===s)?.value}r(Kd,"providerItemDetail");function C6(e){return!!(e&&!Gd(e)&&!/^tool(?:\s+|_)call\b/i.test(e))}r(C6,"meaningfulProviderToolSummary");function Qdt(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=Kd(s,"Name"),i=Gd(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"&&!C6(l.value)&&n.has("Progress")||n.set(l.label,l);return{...s,id:e.id,summary:C6(s.summary)?s.summary:e.summary,details:[...n.values()]}}r(Qdt,"mergeProviderActivityItem");function Ydt(e){if(e==null)return;const s=(typeof e=="string"?e:String(e)).trim();if(s)return s.length>Jse?`${s.slice(0,Jse)}
|
|
@@ -772,7 +772,7 @@ Last resolved: user values resolve per member`;return(0,t.jsxs)("div",{role:"row
|
|
|
772
772
|
|
|
773
773
|
Review the **original** file.`,markdown:!0,downloadUrl:"data:text/markdown,%23%20Project%20notes"}),(0,t.jsx)(GU,{title:"notes.txt",text:"Plain text stays literal: <example>",markdown:!1,downloadUrl:"data:text/plain,Plain%20text"})]})]}),(0,t.jsxs)(xr,{title:"Connection recovery",children:[(0,t.jsx)(Yn,{title:"Waiting for server",children:(0,t.jsx)(AE,{temporary:!0,retrying:!1,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(Yn,{title:"Checking connection",children:(0,t.jsx)(AE,{temporary:!0,retrying:!0,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(Yn,{title:"Access check failed",children:(0,t.jsx)(AE,{temporary:!1,retrying:!1,onRetry:r(()=>{},"onRetry")})})]}),(0,t.jsxs)(xr,{title:"Browser session footer",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Fit to pane follows the visible panel. Fixed viewport presets and session actions live in the footer menu. Costs stay in task reporting. The idle countdown appears only in the final five minutes. Full panel, activity, and settings states are in Storybook under Browser Use."}),["running","idle","closing-soon","closed"].map(B=>(0,t.jsx)(Yn,{title:B==="closing-soon"?"Closing soon":B,children:(0,t.jsx)(vEe,{browser:{id:"design-browser",sessionId:"design-session",issueId:"design-task",status:B==="closing-soon"?"idle":B,runStatus:"completed",progress:null,error:null,costCents:15,idleDeadline:new Date(B==="closing-soon"?282e3:6e5).toISOString(),expiresAt:null,createdAt:new Date(0).toISOString()},now:0,onControl:r(()=>{},"onControl"),onReconnect:r(()=>{},"onReconnect"),onResize:r(()=>{},"onResize")})},B))]}),(0,t.jsxs)(xr,{title:"Browser activity in the task feed",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Each browser appears once at its opening time among the task messages. Its status updates in place; the action opens its side-panel tab."}),["starting","running","idle","closed","failed"].map(B=>(0,t.jsx)(Yn,{title:B,children:(0,t.jsx)(XCe,{browser:{id:`design-${B}`,sessionId:`design-${B}`,issueId:"design-task",status:B,runStatus:"completed",progress:null,error:null,costCents:0,idleDeadline:null,expiresAt:null,createdAt:new Date(0).toISOString()},onOpen:r(()=>{},"onOpen")})},B))]}),(0,t.jsxs)(xr,{title:"Media artifacts",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Images and videos use gallery tiles. The whole tile opens the task gallery; files and links keep compact, fully clickable rows. Task/Artifact Gallery in Storybook covers playable videos, mixed files, narrow panels, and unavailable previews."}),(0,t.jsxs)("div",{className:"grid max-w-2xl grid-cols-1 gap-3 sm:grid-cols-2",children:[(0,t.jsx)(R6,{id:"design-image",title:"Launch artwork",contentPath:"/announcement-preview.svg",contentType:"image/svg+xml",originalFilename:"launch.svg",detail:"Image"}),(0,t.jsx)(R6,{id:"design-video",title:"Video preview unavailable",contentPath:"",contentType:"video/mp4",originalFilename:"preview.mp4",detail:"Video"})]})]}),(0,t.jsx)(xr,{title:"AI Connections",children:(0,t.jsx)(zrs,{})}),(0,t.jsxs)(xr,{title:"Built-in Agent Lifecycle Chips",children:[(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:["A derived lifecycle chip (amber) for attention states. The lifecycle chip is separate from the agent status vocabulary and only shows for"," ",(0,t.jsx)("span",{className:"font-mono",children:"needs_setup"})," / ",(0,t.jsx)("span",{className:"font-mono",children:"pending_approval"}),"."]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,t.jsx)(uk,{status:"needs_setup"}),(0,t.jsx)(uk,{status:"pending_approval"}),(0,t.jsx)(uk,{status:"needs_setup",compact:!0})]}),(0,t.jsxs)("p",{className:"mt-3 text-sm text-muted-foreground",children:[(0,t.jsx)("span",{className:"font-mono",children:"<BuiltInAgentGate agentKey>"})," composes"," ",(0,t.jsx)("span",{className:"font-mono",children:"PageSkeleton"})," + ",(0,t.jsx)("span",{className:"font-mono",children:"EmptyState"})," ","+ ",(0,t.jsx)("span",{className:"font-mono",children:"InlineBanner"})," to render the loading / setup / pending-approval / paused / ready states of a feature that depends on a built-in agent."]})]})]})}r(_as,"DesignGuide");function Ias(){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)(OMe,{candidates:e,selected:s,excludedFolders:a,onChange:r((o,l)=>{n(o),i(l)},"onChange")})}r(Ias,"SkillSourceTreeShowcase");function Aas(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(Aas,"resolveWorktreeRunExecutionDisplayState");function Tas(e){const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}r(Tas,"formatActivationTimestamp");function R4e(){return(0,t.jsxs)(ct,{variant:"outline",className:"text-muted-foreground",children:[(0,t.jsx)(pd,{"aria-hidden":"true"}),"Managed by Paperclip Cloud"]})}r(R4e,"ManagedByCloudBadge");function vo({title:e,description:s,footnote:n,checked:a,onCheckedChange:i,disabled:o,settingKey:l,managed:c,ariaLabel:d}){const{hidden:u}=cu(),h=c?.managed===!0;return u.has(afe(l))?null:(0,t.jsx)(rn,{className:"block bg-transparent p-5",children:(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:e}),h?(0,t.jsx)(R4e,{}):null]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:s}),n?(0,t.jsx)("p",{className:"max-w-2xl text-xs text-muted-foreground",children:n}):null]}),(0,t.jsx)(ci,{checked:a,onCheckedChange:r(p=>{h||i(p)},"onCheckedChange"),disabled:o||h,"aria-label":d})]})})}r(vo,"ExperimentalToggleCard");function Ras(){const{setBreadcrumbs:e}=Bn(),s=Pt(),{hidden:n}=cu(),[a,i]=(0,m.useState)(null);(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Experimental"}])},[e]);const o=ee({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Nr.getExperimental(),"queryFn")}),l=je({mutationFn:r(async G=>Nr.updateExperimental(G),"mutationFn"),onMutate:r(async G=>{await s.cancelQueries({queryKey:P.instance.experimentalSettings});const Y=s.getQueryData(P.instance.experimentalSettings);return Y&&s.setQueryData(P.instance.experimentalSettings,{...Y,...G}),{previousSettings:Y}},"onMutate"),onSuccess:r(async G=>{i(null),s.setQueryData(P.instance.experimentalSettings,G),await Promise.all([s.invalidateQueries({queryKey:P.instance.experimentalSettings}),s.invalidateQueries({queryKey:P.adapters.all}),s.invalidateQueries({queryKey:["built-in-agents"]}),s.invalidateQueries({queryKey:P.health}),s.invalidateQueries({queryKey:["apps"]})])},"onSuccess"),onError:r((G,Y,Q)=>{Q?.previousSettings&&s.setQueryData(P.instance.experimentalSettings,Q.previousSettings),i(G instanceof Error?G.message:"Failed to update experimental settings.")},"onError")});if(o.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading experimental settings..."});if(o.error)return(0,t.jsx)("div",{className:"text-sm text-destructive",children:o.error instanceof Error?o.error.message:"Failed to load experimental settings."});const c=jot(),d=o.data?.managedKeys??{},u=o.data?.enableWorktreeRunExecution===!0,h=d.enableWorktreeRunExecution?.managed===!0,p=Aas(o.data,wot()),f=o.data?.enableEnvironments===!0,x=o.data?.enableNativeRunner===!0,b=o.data?.enableChatConnectors===!0,v=o.data?.enableManagedSandboxOnly===!0,j=o.data?.enableIsolatedWorkspaces===!0,N=o.data?.enableIsolatedWorkspacesByDefault===!0,w=o.data?.enableStreamlinedUi!==!1;o.data?.enableConferenceRoomChat;const k=o.data?.enableClassicTaskInterface===!0,S=o.data?.enableIssuePlanDecompositions===!0,C=o.data?.enableExperimentalFileViewer===!0,I=o.data?.enableExternalObjects===!0,R=o.data?.enableBuiltInAgents===!0,T=o.data?.enableBetaSkills===!0,A=o.data?.enableSummaries===!0,D=o.data?.enableStatusCards===!0,M=d.enableSummaries?.managed===!0,B=d.enableStatusCards?.managed===!0,E=M&&!A,z=B&&D,$=o.data?.enableDecisions===!0,q=o.data?.enableGoalsSidebarLink===!0,U=o.data?.enableCases===!0,O=o.data?.enableServerInfoDebugView===!0,K=o.data?.enablePaperclipDeveloperMode===!0,H=o.data?.enableSimplifiedEnglishInteractions===!0,Z=o.data?.enableFirstTaskPlanProposal===!0,se=o.data?.enableSmokeLab===!0,ne=o.data?.autoRestartDevServerWhenIdle===!0,fe=r(G=>!n.has(afe(G)),"isVisible"),X=c&&fe("enableWorktreeRunExecution"),re=X||["autoRestartDevServerWhenIdle","enableManagedSandboxOnly","enablePaperclipDeveloperMode","enableServerInfoDebugView","enableSmokeLab","enableIssuePlanDecompositions"].some(fe),oe=fe("enableClassicTaskInterface")||fe("enableGoalsSidebarLink");return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Dm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Experimental"})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Opt into features that are still being evaluated before they become default behavior."})]}),(0,t.jsx)("div",{role:"alert",className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Experimental features may break at any time."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"These features are opt-in and come with no compatibility guarantees. They may change, break, or be removed without notice. Avoid relying on them for critical or production workflows."})]})]})}),a&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:a}),(0,t.jsxs)("section",{className:"space-y-3","aria-labelledby":"experimental-features-heading",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("h2",{id:"experimental-features-heading",className:"text-sm font-semibold",children:"Experimental features"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Optional product features that are still being evaluated."})]}),(0,t.jsx)(vo,{title:"Agent Chat",description:"Talk to each agent in one ongoing conversation. Clarify goals and create tasks for execution. Chat leads the Work group and opens an agent rail beside the nav, and each chat's side panel shows the agent's tasks and artifacts as cards.",footnote:"Turning this off preserves conversations and lets active runs finish, but prevents new messages.",checked:o.data?.enableAgentChat??!1,onCheckedChange:r(G=>l.mutate({enableAgentChat:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableAgentChat",managed:d.enableAgentChat,ariaLabel:"Toggle agent chat experimental setting"}),(0,t.jsx)(vo,{title:"Beta skills",description:"Allow agents to pin beta releases of the Paperclip core skill. Disabling this returns every agent to the default live skill without removing saved pins.",checked:T,onCheckedChange:r(G=>l.mutate({enableBetaSkills:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableBetaSkills",managed:d.enableBetaSkills,ariaLabel:"Toggle beta skills experimental setting"}),(0,t.jsx)(vo,{title:"Built-in Agents",description:"Show Paperclip-managed built-in agent surfaces, including built-in roster badges, the Built-in agents tab, and built-in agent setup controls.",checked:R,onCheckedChange:r(G=>l.mutate({enableBuiltInAgents:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableBuiltInAgents",managed:d.enableBuiltInAgents,ariaLabel:"Toggle built-in agents experimental setting"}),(0,t.jsx)(vo,{title:"Cases",description:"Durable work products (blog posts, tweet storms…) that tasks create and iterate on. Adds the Cases tab and the agent case API.",footnote:"Turning Cases off hides the tab and blocks the case API; existing case data is kept.",checked:U,onCheckedChange:r(G=>l.mutate({enableCases:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCases",managed:d.enableCases,ariaLabel:"Toggle cases experimental setting"}),(0,t.jsx)(vo,{title:"Chat connectors",description:"Connect agents to Slack, GitHub, Discord, Microsoft Teams, and Telegram conversations.",footnote:"Turning this off hides experimental chat setup and connected-task controls. Existing chat connections keep running. AgentMail, GitHub tools, and other tool connectors stay available.",checked:b,onCheckedChange:r(G=>l.mutate({enableChatConnectors:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableChatConnectors",managed:d.enableChatConnectors,ariaLabel:"Toggle chat connectors experimental setting"}),(0,t.jsx)(vo,{title:"Combined Inbox + Task List",description:"Fold Inbox into Tasks. One Tasks row carries the unread badge, and a Views menu reaches every inbox view (Mine, Unread, Blocked, Recent, Everything) and every task view.",footnote:"Old Inbox links redirect to the matching view. Turning this off restores the separate Inbox; no data changes.",checked:o.data?.enableCombinedInboxTasks??!1,onCheckedChange:r(G=>l.mutate({enableCombinedInboxTasks:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCombinedInboxTasks",managed:d.enableCombinedInboxTasks,ariaLabel:"Toggle combined inbox and task list experimental setting"}),null,(0,t.jsx)(vo,{title:"Decisions",description:"Show the Decisions item in the main sidebar — the attention home that surfaces the tasks awaiting your input — while the surface is still being evaluated.",checked:$,onCheckedChange:r(G=>l.mutate({enableDecisions:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableDecisions",managed:d.enableDecisions,ariaLabel:"Toggle decisions experimental setting"}),(0,t.jsx)(vo,{title:"Enable Environments",description:"Show environment management in company settings and allow project and agent environment assignment controls.",checked:f,onCheckedChange:r(G=>l.mutate({enableEnvironments:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableEnvironments",managed:d.enableEnvironments,ariaLabel:"Toggle environments experimental setting"}),(0,t.jsx)(vo,{title:"Enable External Objects",description:"Detect external URLs in issues and show resolved status for pull requests, tickets, and other referenced work objects.",checked:I,onCheckedChange:r(G=>l.mutate({enableExternalObjects:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableExternalObjects",managed:d.enableExternalObjects,ariaLabel:"Toggle external objects experimental setting"}),(0,t.jsx)(vo,{title:"Enable Isolated Workspaces",description:"Show execution workspace controls in project configuration and allow isolated workspace behavior for new and existing task runs.",checked:j,onCheckedChange:r(G=>l.mutate({enableIsolatedWorkspaces:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIsolatedWorkspaces",managed:d.enableIsolatedWorkspaces,ariaLabel:"Toggle isolated workspaces experimental setting"}),(0,t.jsx)(vo,{title:"Experimental File Viewer",description:"Show task detail controls for browsing and previewing workspace files relative to a task.",checked:C,onCheckedChange:r(G=>l.mutate({enableExperimentalFileViewer:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableExperimentalFileViewer",managed:d.enableExperimentalFileViewer,ariaLabel:"Toggle experimental file viewer setting"}),(0,t.jsx)(vo,{title:"First task: propose with a plan document",description:"When the user's first request is a single task, the chief of staff writes a short plan document and a checkbox card instead of a one-card confirmation. Applies to organizations created after the toggle is flipped.",checked:Z,onCheckedChange:r(G=>l.mutate({enableFirstTaskPlanProposal:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableFirstTaskPlanProposal",managed:d.enableFirstTaskPlanProposal,ariaLabel:"Toggle first task plan proposal experimental setting"}),(0,t.jsx)(vo,{title:"Memory connectors",description:"Connect Mem0, Zep, Supermemory, Cognee, and Honcho for long-term memory and context.",footnote:"Turning this off hides setup for these connectors. Existing connections keep running.",checked:o.data?.enableMemoryConnectors===!0,onCheckedChange:r(G=>l.mutate({enableMemoryConnectors:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableMemoryConnectors",managed:d.enableMemoryConnectors,ariaLabel:"Toggle memory connectors experimental setting"}),(0,t.jsx)(vo,{title:"Paperclip Runner",description:"Allow new Codex agents to select the experimental Rust Paperclip Runner, including authenticated runner ingress when a sandbox requires it. Onboarding continues to use legacy adapters. Turning this off hides the choice without affecting existing native runs.",checked:x,onCheckedChange:r(G=>l.mutate({enableNativeRunner:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableNativeRunner",managed:d.enableNativeRunner,ariaLabel:"Toggle Paperclip Runner experimental setting"}),(0,t.jsx)(vo,{title:"Pixels Office",description:"Show a live pixel-art office floor plan where each agent is a character and each character shows how many tasks that agent is holding.",checked:o.data?.enablePixelsOffice===!0,onCheckedChange:r(G=>l.mutate({enablePixelsOffice:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePixelsOffice",managed:d.enablePixelsOffice,ariaLabel:"Toggle Pixels Office experimental setting"}),(0,t.jsx)(vo,{title:"Simplified English Interactions",description:"Instruct agents to write user interactions (plan confirmations, questions, suggested tasks, checkbox prompts) in ASD-STE100 Simplified Technical English, with brief context on what information the decision needs and what happens for each choice.",checked:H,onCheckedChange:r(G=>l.mutate({enableSimplifiedEnglishInteractions:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableSimplifiedEnglishInteractions",managed:d.enableSimplifiedEnglishInteractions,ariaLabel:"Toggle simplified english interactions experimental setting"}),(0,t.jsx)(vo,{title:"Status Cards",description:"Enable the experimental shared status-card board and its gated API. Existing card data is kept when this is disabled.",footnote:"Enabling Status Cards also enables Summaries.",checked:D,onCheckedChange:r(G=>l.mutate(G?{enableSummaries:!0,enableStatusCards:!0}:{enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||E,settingKey:"enableStatusCards",managed:d.enableStatusCards,ariaLabel:"Toggle status cards experimental setting"}),(0,t.jsx)(vo,{title:"Streamlined UI",description:"Use the simplified main sidebar, shared Tasks and Inbox presentation, focused task detail layout, and contextual navigation across Agents, Routines, Skills, and Settings.",footnote:"Turning this off restores the legacy shell and navigation. Task and page data are unchanged.",checked:w,onCheckedChange:r(G=>l.mutate({enableStreamlinedUi:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableStreamlinedUi",managed:d.enableStreamlinedUi,ariaLabel:"Toggle Streamlined UI experimental setting"}),(0,t.jsx)(vo,{title:"Summaries",description:"Show Summarizer-generated status slots on project and workspace pages, with on-demand refresh and revision history. Existing summary data is kept when this is disabled.",footnote:"Status Cards requires Summaries. Disabling Summaries also disables Status Cards.",checked:A,onCheckedChange:r(G=>l.mutate(G||!D?{enableSummaries:G}:{enableSummaries:!1,enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||z,settingKey:"enableSummaries",managed:d.enableSummaries,ariaLabel:"Toggle summaries experimental setting"}),j&&(0,t.jsx)(vo,{title:"Use Isolated Workspaces By Default",description:"Treat a project that has no execution workspace policy of its own as if it selected isolated workspaces, so its tasks get a per-task worktree instead of sharing the project checkout. A project that carries its own policy keeps it.",checked:N,onCheckedChange:r(G=>l.mutate({enableIsolatedWorkspacesByDefault:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIsolatedWorkspacesByDefault",managed:d.enableIsolatedWorkspacesByDefault,ariaLabel:"Toggle isolated workspaces by default experimental setting"})]}),re?(0,t.jsxs)("section",{className:"space-y-3","aria-labelledby":"developer-mode-heading",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("h2",{id:"developer-mode-heading",className:"text-sm font-semibold",children:"Paperclip Developer Mode"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Internal tools for developing, testing, and debugging Paperclip."})]}),(0,t.jsx)(vo,{title:"Auto-Restart Dev Server When Idle",description:"In `pnpm dev:once`, wait for all queued and running local agent runs to finish, then restart the server automatically when backend changes or migrations make the current boot stale.",checked:ne,onCheckedChange:r(G=>l.mutate({autoRestartDevServerWhenIdle:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"autoRestartDevServerWhenIdle",managed:d.autoRestartDevServerWhenIdle,ariaLabel:"Toggle guarded dev-server auto-restart"}),(0,t.jsx)(vo,{title:"Managed Environment Only",description:"Hide the local environment and run all agents in the platform-managed environment.",checked:v,onCheckedChange:r(G=>l.mutate({enableManagedSandboxOnly:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableManagedSandboxOnly",managed:d.enableManagedSandboxOnly,ariaLabel:"Toggle managed environment only experimental setting"}),(0,t.jsx)(vo,{title:"Paperclip Developer Mode",description:"Show internal Paperclip maintainer tools and observability links, including Honeycomb trace queries on run pages.",checked:K,onCheckedChange:r(G=>l.mutate({enablePaperclipDeveloperMode:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePaperclipDeveloperMode",managed:d.enablePaperclipDeveloperMode,ariaLabel:"Toggle Paperclip developer mode experimental setting"}),X?(0,t.jsx)(rn,{className:"block bg-transparent p-5",children:(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:"Run tasks in this worktree"}),h?(0,t.jsx)(R4e,{}):null]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"This is an isolated git-worktree preview instance. Turn this on to let the scheduler execute runs here. Only tasks created after enabling will run automatically — copied/pre-existing tasks stay parked. Toggling off and on resets the cutoff."})]}),(0,t.jsx)(ci,{checked:u,onCheckedChange:r(G=>{h||l.mutate({enableWorktreeRunExecution:G})},"onCheckedChange"),disabled:l.isPending||h,"aria-label":"Toggle worktree run execution setting"})]}),p.kind==="armed"?(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2 text-sm text-foreground",children:[(0,t.jsx)(oo,{className:"h-4 w-4 shrink-0 text-emerald-600"}),(0,t.jsxs)("span",{children:["Running tasks created after"," ",(0,t.jsx)("span",{className:"font-medium",children:Tas(p.activatedAt)}),"."]})]}):null,p.kind==="fail_closed"?(0,t.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-sm",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-0.5",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Execution is suppressed — effectively off."}),(0,t.jsxs)("p",{className:"text-muted-foreground",children:[p.reason==="instance_mismatch"?"This setting was armed in a different instance and copied here, so no tasks run automatically.":"This setting is missing its activation cutoff, so no tasks run automatically."," ","Toggle it off and back on to arm execution for tasks created here."]})]})]}):null]})}):null,(0,t.jsx)(vo,{title:"Server Info Debug View",description:'Show a "Server" section in the account drawer with the current server restart time and running commit.',checked:O,onCheckedChange:r(G=>l.mutate({enableServerInfoDebugView:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableServerInfoDebugView",managed:d.enableServerInfoDebugView,ariaLabel:"Toggle server info debug view experimental setting"}),(0,t.jsx)(vo,{title:"Smoke Lab",description:'Add a "Smoke Lab" tab under Apps → Developer and an "Integration smoke" card on the dashboard for exercising every integration path against deterministic local fixtures (fake OAuth provider + loopback MCP servers). Private (non-public) deployments only.',checked:se,onCheckedChange:r(G=>l.mutate({enableSmokeLab:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableSmokeLab",managed:d.enableSmokeLab,ariaLabel:"Toggle smoke lab experimental setting"}),(0,t.jsx)(vo,{title:"Task Plan Decomposition",description:"Show accepted-plan decomposition history on task detail pages. Intended for debugging and validating subtask creation behavior while the presentation is still being refined.",checked:S,onCheckedChange:r(G=>l.mutate({enableIssuePlanDecompositions:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIssuePlanDecompositions",managed:d.enableIssuePlanDecompositions,ariaLabel:"Toggle task plan decomposition panel experimental setting"})]}):null,oe?(0,t.jsxs)("section",{className:"space-y-3","aria-labelledby":"legacy-heading",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)("h2",{id:"legacy-heading",className:"text-sm font-semibold",children:"Legacy"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"These features are going to be removed."})]}),(0,t.jsx)(vo,{title:"Classic Task Interface",description:"Restores the previous task detail page: the page-level header with inline description editing, the plain comment thread, and the fixed Properties sidebar. Chat-only features — streaming activity folding, inline plan and question cards, the three-mode composer — are unavailable in the classic view.",footnote:"Switching takes effect immediately. No task data is affected.",checked:k,onCheckedChange:r(G=>l.mutate({enableClassicTaskInterface:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableClassicTaskInterface",managed:d.enableClassicTaskInterface,ariaLabel:"Toggle classic task interface experimental setting"}),(0,t.jsx)(vo,{title:"Goals Sidebar Link",description:"Restore the Goals item in the main sidebar while the goals surface is being evaluated.",checked:q,onCheckedChange:r(G=>l.mutate({enableGoalsSidebarLink:G}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableGoalsSidebarLink",managed:d.enableGoalsSidebarLink,ariaLabel:"Toggle goals sidebar link experimental setting"})]}):null]})}r(Ras,"InstanceExperimentalSettings");function Eas(){const{userId:e,settled:s}=Hf(),{setBreadcrumbs:n}=Bn(),{pushToast:a}=xi(),i=Pt(),[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=ee({queryKey:P.access.adminUsers(o),queryFn:r(()=>pr.searchAdminUsers(o),"queryFn")}),f=ee({...yLe(e),enabled:s&&p.isSuccess}),x=f.data??[],b=(0,m.useMemo)(()=>p.data?.find(w=>w.id===c)??null,[c,p.data]),v=ee({queryKey:P.access.userCompanyAccess(c??""),queryFn:r(()=>pr.getUserCompanyAccess(c),"queryFn"),enabled:!!c});(0,m.useEffect)(()=>{!c&&p.data?.[0]&&d(p.data[0].id)},[c,p.data]),(0,m.useEffect)(()=>{v.data&&h(new Set(v.data.companyAccess.filter(w=>w.status==="active").map(w=>w.companyId)))},[v.data]);const j=je({mutationFn:r(()=>pr.setUserCompanyAccess(c,[...u]),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.userCompanyAccess(c)}),await i.invalidateQueries({queryKey:P.access.adminUsers(o)}),await i.invalidateQueries({queryKey:P.companies.all}),a({title:"Organization access updated",tone:"success"})},"onSuccess")}),N=je({mutationFn:r(async w=>{if(!c)throw new Error("No user selected");return w?pr.promoteInstanceAdmin(c):pr.demoteInstanceAdmin(c)},"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.adminUsers(o)}),c&&await i.invalidateQueries({queryKey:P.access.userCompanyAccess(c)}),a({title:"Instance role updated",tone:"success"})},"onSuccess")});if(p.isLoading||!s||p.isSuccess&&f.isPending)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading instance access…"});if(p.error){const w=p.error instanceof dn&&p.error.status===403?"Instance admin access is required to manage users.":p.error instanceof Error?p.error.message:"Failed to load users.";return(0,t.jsx)("div",{className:"text-sm text-destructive",children:w})}return f.error?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsx)("p",{className:"text-sm text-destructive",children:"Failed to load organizations. Try again before changing access."}),(0,t.jsx)(L,{onClick:r(()=>{f.refetch()},"onClick"),children:"Try again"})]}):(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(EI,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Instance Access"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Search users, manage instance-admin status, and control which organizations they can access."})]}),(0,t.jsxs)("div",{className:"grid gap-6 lg:grid-cols-(--gtc-34)",children:[(0,t.jsxs)(rn,{className:"block space-y-4 p-4",children:[(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Search users"}),(0,t.jsx)("input",{className:"w-full rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(w=>l(w.target.value),"onChange"),placeholder:"Search by name or email"})]}),(0,t.jsx)("div",{className:"space-y-2",children:(p.data??[]).map(w=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>d(w.id),"onClick"),className:`w-full rounded-lg border px-3 py-3 text-left transition-colors ${w.id===c?"border-foreground bg-accent":"border-border hover:bg-accent/40"}`,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"truncate font-medium",children:w.name||w.email||w.id}),(0,t.jsx)("div",{className:"truncate text-sm text-muted-foreground",children:w.email||w.id})]}),w.isInstanceAdmin?(0,t.jsx)(Di,{className:"h-4 w-4 text-emerald-600"}):null]}),(0,t.jsxs)("div",{className:"mt-2 text-xs text-muted-foreground",children:[w.activeCompanyMembershipCount," active organization memberships"]})]},w.id))})]}),(0,t.jsx)(rn,{className:"block space-y-4 p-5",children:c?v.isLoading?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading user access…"}):v.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:v.error instanceof Error?v.error.message:"Failed to load user access."}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-lg font-semibold",children:b?.name||b?.email||c}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:b?.email||c})]}),(0,t.jsx)(L,{variant:b?.isInstanceAdmin?"outline":"default",onClick:r(()=>N.mutate(!(b?.isInstanceAdmin??!1)),"onClick"),disabled:N.isPending,children:b?.isInstanceAdmin?"Remove instance admin":"Promote to instance admin"})]}),(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-sm font-semibold",children:"Organization access"}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Toggle organization membership for this user. New access defaults to an active operator membership."})]}),(0,t.jsx)("div",{className:"grid gap-3 md:grid-cols-2",children:x.map(w=>(0,t.jsxs)("label",{className:"flex items-start gap-3 rounded-lg border border-border px-3 py-3",children:[(0,t.jsx)(pi,{checked:u.has(w.id),onCheckedChange:r(k=>{h(S=>{const C=new Set(S);return k?C.add(w.id):C.delete(w.id),C})},"onCheckedChange")}),(0,t.jsxs)("span",{className:"space-y-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium",children:w.name}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:w.issuePrefix})]})]},w.id))}),(0,t.jsx)("div",{className:"flex justify-end",children:(0,t.jsx)(L,{onClick:r(()=>j.mutate(),"onClick"),disabled:j.isPending,children:j.isPending?"Saving…":"Save organization access"})})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h2",{className:"text-sm font-semibold",children:"Current memberships"}),(0,t.jsx)("div",{className:"space-y-2",children:(v.data?.companyAccess??[]).map(w=>(0,t.jsxs)("div",{className:"flex items-center justify-between rounded-lg border border-border px-3 py-2 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"font-medium",children:w.companyName||w.companyId}),(0,t.jsxs)("div",{className:"text-muted-foreground",children:[w.membershipRole||"unset"," • ",w.status]})]}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:new Date(w.updatedAt).toLocaleDateString()})]},w.id))})]})]}):(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Select a user to inspect instance access."})})]})]})}r(Eas,"InstanceAccess");var dpe={getMine:r(e=>Te.get(`/companies/${e}/users/me/inbox-agent-policy`),"getMine"),updateMine:r((e,s)=>Te.put(`/companies/${e}/users/me/inbox-agent-policy`,s),"updateMine")},Pas=[{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 KR(e,s){return`${e}:${[...s].sort().join(",")}`}r(KR,"policyKey");function Mas({companyId:e}){const s=Pt(),[n,a]=(0,m.useState)(null),i=(0,m.useRef)(null),o=ee({queryKey:e?P.inboxAgentPolicy.mine(e):["inbox-agent-policy","none"],queryFn:r(()=>dpe.getMine(e),"queryFn"),enabled:!!e}),l=o.data,c=ee({queryKey:e?P.agents.list(e):["agents","none"],queryFn:r(()=>$t.list(e),"queryFn"),enabled:!!e}),d=(0,m.useMemo)(()=>(c.data??[]).filter(Lf),[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=KR(l.mode,l.allowedAgentIds);a(b=>b===null||KR(b.mode,b.allowedAgentIds)===i.current?{mode:l.mode,allowedAgentIds:l.allowedAgentIds}:b),i.current=x},[l]);const p=je({mutationFn:r(x=>dpe.updateMine(e,{mode:x.mode,allowedAgentIds:x.mode==="allowlist"?x.allowedAgentIds:[]}),"mutationFn"),onSuccess:r(x=>{s.setQueryData(P.inboxAgentPolicy.mine(e),x)},"onSuccess")}),f=!!(n&&l&&KR(n.mode,n.allowedAgentIds)!==KR(l.mode,l.allowedAgentIds));return o.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:o.error instanceof Error?o.error.message:"Failed to load inbox agent policy."}):o.isLoading||!n?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading inbox agent policy…"}):(0,t.jsxs)("section",{className:"space-y-4","aria-label":"Let agents tidy my inbox",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(hd,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Let agents tidy my inbox"})]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Choose whether the agents you manage may archive tasks out of your inbox on your behalf. You can undo any archive, and every agent archive is attributed in the task's properties."})]}),(0,t.jsx)(wm,{ariaLabel:"Inbox agent archiving policy",value:n.mode,onValueChange:r(x=>a(b=>b&&{...b,mode:x}),"onValueChange"),options:Pas,className:"max-w-2xl"}),n.mode==="allowlist"?(0,t.jsxs)("div",{className:"max-w-2xl space-y-2",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Agents allowed to tidy my inbox"}),(0,t.jsx)(Zy,{agents:u,selectedAgentIds:h,onChange:r(x=>a(b=>b&&{...b,allowedAgentIds:[...x]}),"onChange"),triggerLabel:h.size===0?"Select agents":`${h.size} ${h.size===1?"agent":"agents"} selected`,triggerFullWidth:!1,showSelectionPreview:!1,emptyMessage:"You don’t manage any agents yet."})]}):null,p.error?(0,t.jsx)("div",{className:"max-w-2xl rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:p.error instanceof Error?p.error.message:"Failed to save inbox agent policy."}):null,(0,t.jsxs)("div",{className:"flex max-w-2xl items-center justify-end gap-3",children:[p.isSuccess&&!f?(0,t.jsx)("span",{className:"text-xs text-muted-foreground",role:"status",children:"Saved"}):null,(0,t.jsxs)(L,{type:"button",disabled:!f||p.isPending,onClick:r(()=>n&&p.mutate(n),"onClick"),children:[p.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(Cf,{className:"size-4"}),p.isPending?"Saving…":"Save"]})]})]})}r(Mas,"InboxAgentPolicyControl");var Das={granted:"Allowed",denied:"Blocked in browser settings",default:"Not requested yet",unsupported:"Not supported in this browser"},upe={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 Las(){const[e,s]=(0,m.useState)({});return(0,m.useEffect)(()=>{let n=!1;const a=r(()=>{Promise.all(TI.map(async o=>[o,(await WTe(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=UTe(a);return()=>{n=!0,i()}},[]),e}r(Las,"useCustomSoundNames");function $as({kind:e,customName:s,disabled:n,onError:a}){const i=sRe(),o=i.kinds[e],l=(0,m.useId)(),[c,d]=(0,m.useState)(!1),u=XAt[e];async function h(x){const b=zTe(x);if(!b.ok){a(`${u}: ${b.error}`);return}d(!0);try{await QAt(e,x),BT(e,{soundId:vie}),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 YAt(e),wg().kinds[e].soundId==="custom"&&BT(e,{soundId:wP[e]})}finally{d(!1)}}r(p,"remove");const f=n||!o.enabled;return(0,t.jsxs)("div",{className:"flex flex-col gap-2 border-b border-border/70 py-3 last:border-b-0 sm:flex-row sm:items-center sm:gap-3",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-3 sm:w-48 sm:shrink-0",children:[(0,t.jsx)(ci,{checked:o.enabled,onCheckedChange:r(x=>BT(e,{enabled:x}),"onCheckedChange"),disabled:n,"aria-label":`${u} notifications`}),(0,t.jsx)("div",{className:"min-w-0 flex-1 truncate text-sm font-medium",title:u,children:u})]}),(0,t.jsxs)("div",{className:"flex min-w-0 flex-wrap items-center gap-2 sm:flex-1 sm:flex-nowrap",children:[(0,t.jsxs)($a,{value:o.soundId,onValueChange:r(x=>BT(e,{soundId:x}),"onValueChange"),disabled:f,children:[(0,t.jsx)(La,{className:"min-w-0 flex-1 sm:w-(--sz-170px) sm:flex-none","aria-label":`${u} sound`,children:(0,t.jsx)(Ma,{})}),(0,t.jsxs)(Da,{children:[VTe.map(x=>(0,t.jsx)(Nn,{value:x.id,children:x.label},x.id)),s?(0,t.jsxs)(Nn,{value:vie,children:["Custom: ",s]}):null,(0,t.jsx)(Nn,{value:JAt,children:"No sound"})]})]}),(0,t.jsx)(L,{type:"button",variant:"outline",size:"icon-sm","aria-label":`Preview ${u} sound`,disabled:f||o.soundId==="none",onClick:r(()=>{JTe(e,o.soundId,i.volume)},"onClick"),children:(0,t.jsx)(oo,{})}),(0,t.jsx)("input",{id:l,type:"file",accept:"audio/*",className:"sr-only",disabled:f||c,onChange:r(x=>{const b=x.target.files?.[0];x.target.value="",b&&h(b)},"onChange")}),(0,t.jsxs)(L,{type:"button",variant:"outline",size:"sm",disabled:f||c,onClick:r(()=>document.getElementById(l)?.click(),"onClick"),children:[c?(0,t.jsx)(rt,{className:"animate-spin"}):(0,t.jsx)(py,{}),s?"Replace":"Custom"]}),s?(0,t.jsx)(L,{type:"button",variant:"ghost",size:"icon-sm","aria-label":`Remove custom ${u} sound`,disabled:c,onClick:r(()=>{p()},"onClick"),children:(0,t.jsx)(la,{})}):null]})]})}r($as,"KindRow");function Oas({userId:e}){const s=sRe(),n=c2t(),a=Las(),[i,o]=(0,m.useState)(()=>V1()),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(!1),f=OTe(),x=n.status==="active",b=(0,m.useCallback)(()=>{e&&FU(wg(),e)},[e]);async function v(){const S=await $At();return o(S),S==="granted"&&b(),S}r(v,"askPermission");async function j(S){$E(C=>({...C,enabled:S})),S&&V1()==="default"&&await v()}r(j,"setEnabled");async function N(S){$E(C=>({...C,pushEnabled:S})),S&&V1()==="default"&&await v()}r(N,"setPushEnabled");async function w(){p(!0),c(null),u(null);try{const S=await NP.sendWebPushTest();c(S.sent>0?`Test sent to ${S.sent} device${S.sent===1?"":"s"}.`:"No device has push turned on for your account yet.")}catch(S){u(S instanceof Error?S.message:"Could not send the test notification.")}finally{p(!1)}}r(w,"sendTest");const k=!s.enabled;return(0,t.jsxs)("section",{className:"space-y-4","aria-label":"Notifications",children:[(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(eqe,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Notifications"})]}),(0,t.jsx)("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Sounds and alerts for approvals, agent questions, comments, assignments, reviews, failed runs and join requests. These settings apply to this browser only."})]}),(0,t.jsxs)("div",{className:"max-w-3xl space-y-4 rounded-md border border-border/70 p-4",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Notifications on this device"}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:"Play sounds and show alerts for new inbox items."})]}),(0,t.jsx)(ci,{checked:s.enabled,onCheckedChange:r(S=>{j(S)},"onCheckedChange"),"aria-label":"Notifications on this device"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Browser permission"}),(0,t.jsx)("div",{className:"text-xs text-muted-foreground",children:Das[i]})]}),i==="default"?(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",className:"shrink-0",onClick:r(()=>{v()},"onClick"),children:"Allow notifications"}):null]}),(0,t.jsxs)("div",{className:"flex items-center justify-between gap-4",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"text-sm font-medium",children:"Push when Paperclip is closed"}),(0,t.jsxs)("div",{className:"text-xs text-muted-foreground",children:[f?upe[n.status]:upe.unsupported,n.error?`: ${n.error}`:""]})]}),(0,t.jsx)(ci,{checked:s.pushEnabled,onCheckedChange:r(S=>{N(S)},"onCheckedChange"),disabled:k||!f,"aria-label":"Push when Paperclip is closed"})]}),s.enabled&&!x?(0,t.jsx)("p",{className:"rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground",children:"Push is off on this device, so background alerts only work while a Paperclip tab is visible."}):null,OAt()?(0,t.jsx)("p",{className:"rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground",children:"On iPhone and iPad, push notifications need Paperclip added to the Home Screen (Share, then Add to Home Screen) and opened from there."}):null,(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)("label",{htmlFor:"notification-volume",className:"text-sm font-medium",children:"Volume"}),(0,t.jsx)("input",{id:"notification-volume",type:"range",min:0,max:100,step:5,value:Math.round(s.volume*100),disabled:k,onChange:r(S=>$E(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:TI.map(S=>(0,t.jsx)($as,{kind:S,customName:a[S],disabled:k,onError:u},S))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Custom sounds must be audio files of 512 KB or less. They play only while Paperclip is open; push notifications use your system sound."}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsxs)(L,{type:"button",variant:"secondary",onClick:r(()=>{w()},"onClick"),disabled:h||k,children:[h?(0,t.jsx)(rt,{className:"animate-spin"}):(0,t.jsx)(YI,{}),"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(Oas,"NotificationSettingsSection");function Fas(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(Fas,"deriveInitials");function Bas(){const{setBreadcrumbs:e}=Bn(),{selectedCompanyId:s,selectedCompany:n}=ps(),a=Pt(),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=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Profile"}])},[e]),(0,m.useEffect)(()=>{const T=f.data;T&&(c(T.user.name??""),u(T.user.image??""))},[f.data]);function x(T){a.setQueryData(P.auth.session,A=>A&&{...A,user:{...A.user,...T}})}r(x,"syncSessionProfile");async function b(T){const A=await Oa.updateProfile(T);return x(A),A}r(b,"persistProfile");function v(){return l.trim()||f.data?.user.name||"Board"}r(v,"resolveProfileName");const j=je({mutationFn:r(T=>b(T),"mutationFn"),onSuccess:r(T=>{p(null),c(T.name??""),u(T.image??"")},"onSuccess"),onError:r(T=>{p(T instanceof Error?T.message:"Failed to update profile.")},"onError")}),N=je({mutationFn:r(async T=>{if(!s)throw new Error("Select an organization before uploading a profile avatar.");const A=await vb.uploadImage(s,T,`profiles/${f.data?.user.id??"board-user"}`);return b({name:v(),image:A.contentPath})},"mutationFn"),onSuccess:r(T=>{p(null),c(T.name??""),u(T.image??"")},"onSuccess"),onError:r(T=>{p(T instanceof Error?T.message:"Failed to upload avatar.")},"onError")}),w=je({mutationFn:r(()=>b({name:v(),image:null}),"mutationFn"),onSuccess:r(T=>{p(null),c(T.name??""),u(T.image??"")},"onSuccess"),onError:r(T=>{p(T instanceof Error?T.message:"Failed to remove avatar.")},"onError")});if(f.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading profile..."});if(f.error||!f.data)return(0,t.jsx)("div",{className:"text-sm text-destructive",children:f.error instanceof Error?f.error.message:"Failed to load profile."});const k=l.trim()||f.data.user.name||"Board",S=d.trim()||null,C=Fas(k),I=j.isPending||N.isPending||w.isPending,R=n?`Stored in Paperclip file storage for ${n.name}.`:"Select an organization to upload an avatar into Paperclip storage.";return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(EM,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Profile"})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Control how your account appears in the sidebar and other board surfaces."})]}),h?(0,t.jsx)("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:h}):null,(0,t.jsxs)("section",{className:"space-y-8",children:[(0,t.jsxs)(rn,{className:"block relative overflow-hidden rounded-(--rad-28) border-border/70",children:[(0,t.jsx)("div",{className:"absolute inset-x-0 top-0 h-32 bg-(image:--gradient-extract-26)"}),(0,t.jsx)("div",{className:"absolute inset-0 bg-(image:--gradient-extract-7)"}),(0,t.jsx)("div",{className:"relative p-6 pt-10",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-end gap-5 rounded-(--rad-24) border border-border/70 bg-background/92 p-5 shadow-(--shadow-extract-18) backdrop-blur-sm",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("label",{htmlFor:i,className:"group relative block cursor-pointer rounded-full focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background",children:[(0,t.jsx)("input",{ref:o,id:i,type:"file",accept:"image/*",className:"sr-only",disabled:!s||I,onChange:r(T=>{const A=T.target.files?.[0];A&&(N.mutate(A),T.target.value="")},"onChange")}),(0,t.jsx)("span",{className:"absolute inset-0 z-10 rounded-full bg-black/0 transition-colors group-hover:bg-black/14 group-focus-within:bg-black/14"}),(0,t.jsx)("span",{className:"absolute bottom-1 right-1 z-20 flex size-9 items-center justify-center rounded-full border border-background bg-primary text-primary-foreground shadow-sm",children:N.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(mX,{className:"size-4"})}),(0,t.jsxs)(Mo,{size:"lg",className:"data-[size=lg]:size-24 ring-4 ring-background shadow-xl",children:[S?(0,t.jsx)(xd,{src:S,alt:k}):null,(0,t.jsx)(Do,{children:C})]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsxs)(L,{type:"button",variant:"secondary",onClick:r(()=>o.current?.click(),"onClick"),disabled:!s||I,children:[N.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(mX,{className:"size-4"}),S?"Change photo":"Upload photo"]}),S?(0,t.jsxs)(L,{type:"button",variant:"outline",onClick:r(()=>w.mutate(),"onClick"),disabled:I,children:[w.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(la,{className:"size-4"}),"Remove"]}):null]})]}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-2 pb-1",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"truncate text-2xl font-semibold text-foreground",children:k}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:f.data.user.email??"No email"})]}),(0,t.jsxs)("p",{className:"max-w-2xl text-sm leading-6 text-muted-foreground",children:["Click the avatar to upload a new image. ",R]})]})]})})]}),(0,t.jsxs)("form",{className:"grid gap-6 md:grid-cols-2",onSubmit:r(T=>{T.preventDefault(),j.mutate({name:v(),image:d.trim()||null})},"onSubmit"),children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Qs,{htmlFor:"profile-name",children:"Display name"}),(0,t.jsx)(ht,{id:"profile-name",value:l,onChange:r(T=>c(T.target.value),"onChange"),maxLength:120,placeholder:"Board"}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Shown in the sidebar account footer and comment author surfaces."})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Qs,{htmlFor:"profile-email",children:"Email"}),(0,t.jsx)(ht,{id:"profile-email",value:f.data.user.email??"",readOnly:!0,disabled:!0}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Email is managed by your auth session and is read-only here."})]}),(0,t.jsx)("div",{className:"md:col-span-2 flex justify-end",children:(0,t.jsxs)(L,{type:"submit",disabled:I||!l.trim(),children:[j.isPending?(0,t.jsx)(rt,{className:"size-4 animate-spin"}):(0,t.jsx)(Cf,{className:"size-4"}),j.isPending?"Saving...":"Save profile"]})})]}),(0,t.jsx)(Mas,{companyId:s}),(0,t.jsx)(Oas,{userId:f.data.user.id??null})]})]})}r(Bas,"ProfileSettings");function zas(e){return e?e.split(/\r?\n/).map(s=>s.trim()).find(Boolean)??null:null}r(zas,"firstNonEmptyLine");function mpe(e){return zas(e.lastError)??"Plugin entered an error state without a stored error message."}r(mpe,"getPluginErrorSummary");function hpe(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(hpe,"isExperimentalPluginIdentity");function ppe(){return(0,t.jsx)(ct,{variant:"outline",className:"border-amber-500/30 bg-amber-500/10 text-amber-700 hover:bg-amber-500/10 dark:text-amber-200",children:"Experimental"})}r(ppe,"ExperimentalBadge");function qas(){const{selectedCompany:e}=ps(),{setBreadcrumbs:s}=Bn(),n=Pt(),{pushToast:a}=da(),[i,o]=(0,m.useState)(""),[l,c]=(0,m.useState)(!1),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null);(0,m.useEffect)(()=>{s([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Plugins"}])},[e?.name,s]);const{data:b,isLoading:v,error:j}=ee({queryKey:P.plugins.all,queryFn:r(()=>Al.list(),"queryFn")}),N=ee({queryKey:P.plugins.examples,queryFn:r(()=>Al.listBundled(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:P.plugins.all}),n.invalidateQueries({queryKey:P.plugins.examples}),n.invalidateQueries({queryKey:P.plugins.uiContributions})},"invalidatePluginQueries"),k=je({mutationFn:r(E=>Al.install(E),"mutationFn"),onSuccess:r(()=>{w(),c(!1),o(""),a({title:"Plugin installed successfully",tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Failed to install plugin",body:E.message,tone:"error"})},"onError")}),S=je({mutationFn:r(E=>Al.uninstall(E),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin uninstalled successfully",tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Failed to uninstall plugin",body:E.message,tone:"error"})},"onError")}),C=je({mutationFn:r(E=>Al.enable(E),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin enabled",tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Failed to enable plugin",body:E.message,tone:"error"})},"onError")}),I=je({mutationFn:r(E=>Al.disable(E),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Plugin disabled",tone:"info"})},"onSuccess"),onError:r(E=>{a({title:"Failed to disable plugin",body:E.message,tone:"error"})},"onError")}),R=b??[],T=N.data??[],A=new Map(R.map(E=>[E.packageName,E])),D=new Map(T.map(E=>[E.packageName,E])),M=k.variables?.isLocalPath?k.error?.message??null:null,B=(0,m.useMemo)(()=>new Map(R.map(E=>[E.id,mpe(E)])),[R]);return v?(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugins..."}):j?(0,t.jsx)("div",{className:"p-4 text-sm text-destructive",children:"Failed to load plugins."}):(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Zx,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Plugin Manager"})]}),(0,t.jsxs)(Ys,{open:l,onOpenChange:c,children:[(0,t.jsx)(Uy,{asChild:!0,children:(0,t.jsxs)(L,{size:"sm",className:"gap-2",children:[(0,t.jsx)(yn,{className:"h-4 w-4"}),"Install Plugin"]})}),(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Install Plugin"}),(0,t.jsx)(jn,{children:"Enter the npm package name of the plugin you wish to install."})]}),(0,t.jsx)("div",{className:"grid gap-4 py-4",children:(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Qs,{htmlFor:"packageName",children:"npm Package Name"}),(0,t.jsx)(ht,{id:"packageName",placeholder:"@tickernelz/paperclip-pro-plugin-example",value:i,onChange:r(E=>o(E.target.value),"onChange")})]})}),(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>c(!1),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{onClick:r(()=>k.mutate({packageName:i}),"onClick"),disabled:!i||k.isPending,children:k.isPending?"Installing...":"Install"})]})]})]})]}),(0,t.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Plugins are alpha."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"The plugin runtime and API surface are still changing. Expect breaking changes while this feature settles."})]})]})}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Dm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Available Plugins"}),(0,t.jsx)(ct,{variant:"outline",children:"Bundled"})]}),M&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/25 bg-destructive/[0.06] px-4 py-3 text-sm text-destructive whitespace-pre-wrap break-words",children:M}),N.isLoading?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading bundled plugins..."}):N.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:"Failed to load bundled plugins."}):T.length===0?(0,t.jsx)("div",{className:"rounded-md border border-dashed px-4 py-3 text-sm text-muted-foreground",children:"No bundled plugins were found in this checkout."}):(0,t.jsx)(rn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:T.map(E=>{const z=A.get(E.packageName),$=k.isPending&&k.variables?.isLocalPath&&k.variables.packageName===E.localPath;return(0,t.jsx)("li",{children:(0,t.jsxs)("div",{className:"flex items-center gap-4 px-4 py-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium",children:E.displayName}),(0,t.jsx)(ct,{variant:"outline",children:E.tag==="first-party"?"First-party":"Example"}),hpe({packageName:E.packageName,packagePath:E.localPath,bundledExperimental:E.experimental})&&(0,t.jsx)(ppe,{}),z?(0,t.jsx)(ct,{variant:z.status==="ready"?"default":"secondary",className:z.status==="ready"?"bg-green-600 hover:bg-green-700":"",children:z.status}):(0,t.jsx)(ct,{variant:"secondary",children:"Not installed"})]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:E.description}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:E.packageName}),$&&!E.hasBuiltEntrypoints&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Building plugin..."})]}),(0,t.jsx)("div",{className:"flex items-center gap-2 shrink-0",children:z?(0,t.jsxs)(t.Fragment,{children:[z.status!=="ready"&&(0,t.jsx)(L,{variant:"outline",size:"sm",disabled:C.isPending,onClick:r(()=>C.mutate(z.id),"onClick"),children:"Enable"}),(0,t.jsx)(L,{variant:"outline",size:"sm",asChild:!0,children:(0,t.jsx)(Ke,{to:`/company/settings/instance/plugins/${z.id}`,children:z.status==="ready"?"Open Settings":"Review"})})]}):(0,t.jsx)(L,{size:"sm",disabled:$||k.isPending,onClick:r(()=>k.mutate({packageName:E.localPath,isLocalPath:!0}),"onClick"),children:$?"Installing...":"Install"})})]})},E.packageName)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Zx,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Installed Plugins"})]}),R.length?(0,t.jsx)(rn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:R.map(E=>(0,t.jsx)("li",{children:(0,t.jsxs)("div",{className:"flex items-start gap-4 px-4 py-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(Ke,{to:`/company/settings/instance/plugins/${E.id}`,className:"font-medium hover:underline truncate block",title:E.manifestJson.displayName??E.packageName,children:E.manifestJson.displayName??E.packageName}),D.has(E.packageName)&&(0,t.jsx)(ct,{variant:"outline",children:D.get(E.packageName)?.tag==="first-party"?"First-party":"Example"}),hpe({packageName:E.packageName,packagePath:E.packagePath,manifestJson:E.manifestJson,bundledExperimental:D.get(E.packageName)?.experimental})&&(0,t.jsx)(ppe,{})]}),(0,t.jsx)("div",{children:(0,t.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",title:E.packageName,children:[E.packageName," · v",E.manifestJson.version??E.version]})}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground truncate mt-0.5",title:E.manifestJson.description,children:E.manifestJson.description||"No description provided."}),E.status==="error"&&(0,t.jsx)("div",{className:"mt-3 rounded-md border border-red-500/25 bg-red-500/[0.06] px-3 py-2",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-start gap-3",children:[(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium text-red-700 dark:text-red-300",children:[(0,t.jsx)(Es,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{children:"Plugin error"})]}),(0,t.jsx)("p",{className:"mt-1 text-sm text-red-700/90 dark:text-red-200/90 break-words",title:E.lastError??void 0,children:B.get(E.id)})]}),(0,t.jsx)(L,{variant:"outline",size:"sm",className:"border-red-500/30 bg-background/60 text-red-700 hover:bg-red-500/10 hover:text-red-800 dark:text-red-200 dark:hover:text-red-100",onClick:r(()=>x(E),"onClick"),children:"View full error"})]})})]}),(0,t.jsx)("div",{className:"flex shrink-0 self-center",children:(0,t.jsxs)("div",{className:"flex flex-col items-end gap-2",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(ct,{variant:E.status==="ready"?"default":E.status==="error"?"destructive":"secondary",className:W("shrink-0",E.status==="ready"?"bg-green-600 hover:bg-green-700":""),children:E.status}),(0,t.jsx)(L,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:E.status==="ready"?"Disable":"Enable",onClick:r(()=>{E.status==="ready"?I.mutate(E.id):C.mutate(E.id)},"onClick"),disabled:C.isPending||I.isPending,children:(0,t.jsx)(B7,{className:W("h-4 w-4",E.status==="ready"?"text-green-600":"")})}),(0,t.jsx)(L,{variant:"outline",size:"icon-sm",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Uninstall",onClick:r(()=>{u(E.id),p(E.manifestJson.displayName??E.packageName)},"onClick"),disabled:S.isPending,children:(0,t.jsx)(la,{className:"h-4 w-4"})})]}),(0,t.jsx)(L,{variant:"outline",size:"sm",className:"mt-2 h-8",asChild:!0,children:(0,t.jsxs)(Ke,{to:`/company/settings/instance/plugins/${E.id}`,children:[(0,t.jsx)(iu,{className:"h-4 w-4"}),"Configure"]})})]})})]})},E.id))})}):(0,t.jsx)(rn,{className:"bg-muted/30",children:(0,t.jsxs)(Xa,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(Zx,{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)(Ys,{open:d!==null,onOpenChange:r(E=>{E||u(null)},"onOpenChange"),children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Uninstall Plugin"}),(0,t.jsxs)(jn,{children:["Are you sure you want to uninstall ",(0,t.jsx)("strong",{children:h}),"? This action cannot be undone."]})]}),(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>u(null),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{variant:"destructive",disabled:S.isPending,onClick:r(()=>{d&&S.mutate(d,{onSettled:r(()=>u(null),"onSettled")})},"onClick"),children:S.isPending?"Uninstalling...":"Uninstall"})]})]})}),(0,t.jsx)(Ys,{open:f!==null,onOpenChange:r(E=>{E||x(null)},"onOpenChange"),children:(0,t.jsxs)(Js,{className:"sm:max-w-2xl",children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Error Details"}),(0,t.jsxs)(jn,{children:[f?.manifestJson.displayName??f?.packageName??"Plugin"," hit an error state."]})]}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"rounded-md border border-red-500/25 bg-red-500/[0.06] px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-red-700 dark:text-red-300"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-red-700 dark:text-red-300",children:"What errored"}),(0,t.jsx)("p",{className:"text-red-700/90 dark:text-red-200/90 break-words",children:f?mpe(f):"No error summary available."})]})]})}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:"Full error output"}),(0,t.jsx)("pre",{className:"max-h-(--sz-50vh) overflow-auto rounded-md border bg-muted/40 p-3 text-xs leading-5 whitespace-pre-wrap break-words",children:f?.lastError??"No stored error message."})]})]}),(0,t.jsx)(hr,{children:(0,t.jsx)(L,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Close"})})]})})]})}r(qas,"PluginManager");function Uas(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Bn(),{companyPrefix:a,pluginId:i}=va(),{hideHostPaths:o}=yA(),[l,c]=(0,m.useState)("configuration"),{data:d,isLoading:u}=ee({queryKey:P.plugins.detail(i),queryFn:r(()=>Al.get(i),"queryFn"),enabled:!!i}),{data:h,isLoading:p}=ee({queryKey:P.plugins.health(i),queryFn:r(()=>Al.health(i),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),{data:f}=ee({queryKey:P.plugins.dashboard(i),queryFn:r(()=>Al.dashboard(i),"queryFn"),enabled:!!i,refetchInterval:3e4}),{data:x}=ee({queryKey:P.plugins.logs(i),queryFn:r(()=>Al.logs(i,{limit:50}),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),b=d?.manifestJson?.instanceConfigSchema,v=b&&b.properties&&Object.keys(b.properties).length>0,j=i&&s?P.plugins.config(i,s):["plugins",i??"__missing_plugin__","companies","__missing_company__","config"],{data:N,isLoading:w}=ee({queryKey:j,queryFn:r(()=>Al.getConfig(i,s),"queryFn"),enabled:!!i&&!!v&&!!s}),{slots:k}=gd({slotTypes:["settingsPage"],companyId:s,enabled:!!s}),S=k.filter(z=>z.pluginId===i),C=S.length>0;if((0,m.useEffect)(()=>{n([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Plugins",href:"/company/settings/instance/plugins"},{label:d?.manifestJson?.displayName??d?.packageName??"Plugin Details"}])},[e?.name,n,a,d]),(0,m.useEffect)(()=>{c("configuration")},[i]),u)return(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading plugin details..."});if(!d)return(0,t.jsx)(kn,{to:"/company/settings/instance/plugins",replace:!0});const I=d.status,R=d.status==="ready"?"default":d.status==="error"?"destructive":"secondary",T=d.manifestJson.description||"No description provided.",A=d.manifestJson.capabilities??[],D=d.manifestJson.environmentDrivers??[],M=d.manifestJson.localFolders??[],B=M.length>0&&!o,E=D.map(z=>z.displayName?.trim()||z.driverKey).filter((z,$,q)=>q.indexOf(z)===$).join(", ");return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)(Ke,{to:"/company/settings/instance/plugins",children:(0,t.jsx)(L,{variant:"outline",size:"icon",className:"h-8 w-8",children:(0,t.jsx)(Tl,{className:"h-4 w-4"})})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Zx,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:d.manifestJson.displayName??d.packageName}),(0,t.jsx)(ct,{variant:R,className:"ml-2",children:I}),(0,t.jsxs)(ct,{variant:"outline",className:"ml-1",children:["v",d.manifestJson.version??d.version]})]})]}),(0,t.jsxs)(Ti,{value:l,onValueChange:r(z=>c(z),"onValueChange"),className:"space-y-6",children:[(0,t.jsx)(Mc,{align:"start",items:[{value:"configuration",label:"Configuration"},{value:"status",label:"Status"}],value:l,onValueChange:r(z=>c(z),"onValueChange")}),(0,t.jsx)(ba,{value:"configuration",className:"space-y-6",children:(0,t.jsxs)("div",{className:"space-y-8",children:[(0,t.jsxs)("section",{className:"space-y-5",children:[(0,t.jsx)("h2",{className:"text-base font-semibold",children:"About"}),(0,t.jsxs)("div",{className:"grid gap-8 lg:grid-cols-(--gtc-52)",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-muted-foreground",children:"Description"}),(0,t.jsx)("p",{className:"text-sm leading-6 text-foreground/90",children:T})]}),(0,t.jsxs)("div",{className:"space-y-4 text-sm",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsx)("h3",{className:"font-medium text-muted-foreground",children:"Author"}),(0,t.jsx)("p",{className:"text-foreground",children:d.manifestJson.author})]}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h3",{className:"font-medium text-muted-foreground",children:"Categories"}),(0,t.jsx)("div",{className:"flex flex-wrap gap-2",children:d.categories.length>0?d.categories.map(z=>(0,t.jsx)(ct,{variant:"outline",className:"capitalize",children:z},z)):(0,t.jsx)("span",{className:"text-foreground",children:"None"})})]})]})]})]}),(0,t.jsx)(Bl,{}),(0,t.jsxs)("section",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"space-y-1",children:(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Settings"})}),B?(0,t.jsx)(Kas,{pluginId:i,companyId:s,declarations:M}):null,C?(0,t.jsx)("div",{className:"space-y-3",children:S.map(z=>(0,t.jsx)(Wu,{slot:z,context:{companyId:s,companyPrefix:a??null},missingBehavior:"placeholder"},`${z.pluginKey}:${z.id}`))}):v?(0,t.jsx)(Qas,{pluginId:i,companyId:s,schema:b,initialValues:N?.configJson,isLoading:w,pluginStatus:d.status,supportsConfigTest:d.supportsConfigTest===!0}):D.length>0?(0,t.jsxs)("div",{className:"rounded-md border border-border/60 bg-muted/20 px-4 py-3 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"Configure this plugin from Settings → Environments."}),(0,t.jsxs)("p",{className:"mt-1 text-muted-foreground",children:[E||"This plugin"," registers environment runtime settings there so the execution target stays instance-scoped while secret bindings still resolve through the selected organization context."]}),(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Ke,{to:"/company/settings/instance/environments",children:(0,t.jsx)(L,{variant:"outline",size:"sm",children:"Open Environments"})})})]}):B?null:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This plugin does not require any settings."})]})]})}),(0,t.jsx)(ba,{value:"status",className:"space-y-6",children:(0,t.jsxs)("div",{className:"grid gap-6 xl:grid-cols-(--gtc-39)",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(rn,{children:[(0,t.jsxs)(ro,{children:[(0,t.jsxs)(ko,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(ym,{className:"h-4 w-4"}),"Runtime Dashboard"]}),(0,t.jsx)(Fl,{children:"Worker process, scheduled jobs, and webhook deliveries"})]}),(0,t.jsx)(Xa,{className:"space-y-6",children:f?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[(0,t.jsx)(ym,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Worker Process"]}),f.worker?(0,t.jsxs)("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[(0,t.jsxs)("div",{className:"flex justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Status"}),(0,t.jsx)(ct,{variant:f.worker.status==="running"?"default":"secondary",children:f.worker.status})]}),(0,t.jsxs)("div",{className:"flex justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"PID"}),(0,t.jsx)("span",{className:"font-mono text-xs",children:f.worker.pid??"—"})]}),(0,t.jsxs)("div",{className:"flex justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Uptime"}),(0,t.jsx)("span",{className:"text-xs",children:Yas(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:Jas(f.worker.lastCrashAt)})]})]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No worker process registered."})]}),(0,t.jsx)(Bl,{}),(0,t.jsxs)("div",{children:[(0,t.jsxs)("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[(0,t.jsx)(X0,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Recent Job Runs"]}),f.recentJobRuns.length>0?(0,t.jsx)("div",{className:"space-y-2",children:f.recentJobRuns.map(z=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(Xas,{status:z.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:z.jobKey??z.jobId,children:z.jobKey??z.jobId.slice(0,8)}),(0,t.jsx)(ct,{variant:"outline",className:"px-1 py-0 text-(length:--text-nano)",children:z.trigger})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[z.durationMs!=null?(0,t.jsx)("span",{children:xpe(z.durationMs)}):null,(0,t.jsx)("span",{title:z.createdAt,children:gpe(z.createdAt)})]})]},z.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No job runs recorded yet."})]}),(0,t.jsx)(Bl,{}),(0,t.jsxs)("div",{children:[(0,t.jsxs)("h3",{className:"text-sm font-medium mb-3 flex items-center gap-1.5",children:[(0,t.jsx)(G7,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Recent Webhook Deliveries"]}),f.recentWebhookDeliveries.length>0?(0,t.jsx)("div",{className:"space-y-2",children:f.recentWebhookDeliveries.map(z=>(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[(0,t.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,t.jsx)(Zas,{status:z.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:z.webhookKey,children:z.webhookKey})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[z.durationMs!=null?(0,t.jsx)("span",{children:xpe(z.durationMs)}):null,(0,t.jsx)("span",{title:z.createdAt,children:gpe(z.createdAt)})]})]},z.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No webhook deliveries recorded yet."})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 border-t border-border/50 pt-2 text-xs text-muted-foreground",children:[(0,t.jsx)(ho,{className:"h-3 w-3"}),"Last checked: ",new Date(f.checkedAt).toLocaleTimeString()]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Runtime diagnostics are unavailable right now."})})]}),x&&x.length>0?(0,t.jsxs)(rn,{children:[(0,t.jsxs)(ro,{children:[(0,t.jsxs)(ko,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(fX,{className:"h-4 w-4"}),"Recent Logs"]}),(0,t.jsxs)(Fl,{children:["Last ",x.length," log entries"]})]}),(0,t.jsx)(Xa,{children:(0,t.jsx)("div",{className:"max-h-64 space-y-1 overflow-y-auto font-mono text-xs",children:x.map(z=>(0,t.jsxs)("div",{className:`flex gap-2 py-0.5 ${z.level==="error"?"text-destructive":z.level==="warn"?"text-yellow-600 dark:text-yellow-400":z.level==="debug"?"text-muted-foreground/60":"text-muted-foreground"}`,children:[(0,t.jsx)("span",{className:"shrink-0 text-muted-foreground/50",children:new Date(z.createdAt).toLocaleTimeString()}),(0,t.jsx)(ct,{variant:"outline",className:"h-4 shrink-0 px-1 text-(length:--text-nano)",children:z.level}),(0,t.jsx)("span",{className:"truncate",title:z.message,children:z.message})]},z.id))})})]}):null]}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(rn,{children:[(0,t.jsx)(ro,{children:(0,t.jsxs)(ko,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(fX,{className:"h-4 w-4"}),"Health Status"]})}),(0,t.jsx)(Xa,{children:p?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Checking health..."}):h?(0,t.jsxs)("div",{className:"space-y-4 text-sm",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Overall"}),(0,t.jsx)(ct,{variant:h.healthy?"default":"destructive",children:h.status})]}),h.checks.length>0?(0,t.jsx)("div",{className:"space-y-2 border-t border-border/50 pt-2",children:h.checks.map((z,$)=>(0,t.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,t.jsx)("span",{className:"truncate text-muted-foreground",title:z.name,children:z.name}),z.passed?(0,t.jsx)(iqe,{className:"h-4 w-4 shrink-0 text-green-500"}):(0,t.jsx)(Ec,{className:"h-4 w-4 shrink-0 text-destructive"})]},$))}):null,h.lastError?(0,t.jsx)("div",{className:"break-words rounded border border-destructive/20 bg-destructive/10 p-2 text-xs text-destructive",children:h.lastError}):null]}):(0,t.jsxs)("div",{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{children:"Lifecycle"}),(0,t.jsx)(ct,{variant:R,children:I})]}),(0,t.jsx)("p",{children:"Health checks run once the plugin is ready."}),d.lastError?(0,t.jsx)("div",{className:"break-words rounded border border-destructive/20 bg-destructive/10 p-2 text-xs text-destructive",children:d.lastError}):null]})})]}),(0,t.jsxs)(rn,{children:[(0,t.jsx)(ro,{children:(0,t.jsx)(ko,{className:"text-base",children:"Details"})}),(0,t.jsxs)(Xa,{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Plugin ID"}),(0,t.jsx)("span",{className:"font-mono text-xs text-right",children:d.id})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Plugin Key"}),(0,t.jsx)("span",{className:"font-mono text-xs text-right",children:d.pluginKey})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"NPM Package"}),(0,t.jsx)("span",{className:"max-w-(--sz-170px) truncate text-right text-xs",title:d.packageName,children:d.packageName})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Version"}),(0,t.jsxs)("span",{className:"text-right text-foreground",children:["v",d.manifestJson.version??d.version]})]})]})]}),(0,t.jsxs)(rn,{children:[(0,t.jsx)(ro,{children:(0,t.jsxs)(ko,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(bc,{className:"h-4 w-4"}),"Permissions"]})}),(0,t.jsx)(Xa,{children:A.length>0?(0,t.jsx)("ul",{className:"space-y-2 text-sm text-muted-foreground",children:A.map(z=>(0,t.jsx)("li",{className:"rounded-md bg-muted/40 px-2.5 py-2 font-mono text-xs text-foreground/85",children:z},z))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No special permissions requested."})})]})]})]})})]})]})}r(Uas,"PluginSettings");function Kas({pluginId:e,companyId:s,declarations:n}){const{data:a,isLoading:i,error:o}=ee({queryKey:s?P.plugins.localFolders(e,s):["plugins",e,"companies","none","local-folders"],queryFn:r(()=>Al.listLocalFolders(e,s),"queryFn"),enabled:!!s}),l=new Map((a?.folders??[]).map(c=>[c.folderKey,c]));return s?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Go,{className:"h-4 w-4 text-muted-foreground"}),(0,t.jsx)("h3",{className:"text-sm font-medium",children:"Local folders"})]}),o?(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:o.message||"Failed to load local folder settings."}):null,i?(0,t.jsxs)("div",{className:"flex items-center gap-2 py-3 text-sm text-muted-foreground",children:[(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}),"Loading local folders..."]}):(0,t.jsx)("div",{className:"space-y-3",children:n.map(c=>(0,t.jsx)(Was,{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(Kas,"PluginLocalFoldersSettings");function Was({pluginId:e,companyId:s,declaration:n,status:a}){const i=Pt(),o=a?.path??"",[l,c]=(0,m.useState)(o),[d,u]=(0,m.useState)(null);(0,m.useEffect)(()=>{c(o),u(null)},[o,n.folderKey]);const h=je({mutationFn:r(v=>Al.configureLocalFolder(e,s,n.folderKey,{path:v,access:n.access,requiredDirectories:n.requiredDirectories,requiredFiles:n.requiredFiles}),"mutationFn"),onSuccess:r(v=>{u({type:v.healthy?"success":"error",text:v.healthy?"Local folder saved.":"Local folder saved, but validation still needs attention."}),i.invalidateQueries({queryKey:P.plugins.localFolders(e,s)})},"onSuccess"),onError:r(v=>{u({type:"error",text:v.message||"Failed to save local folder."})},"onError")}),p=l.trim(),f=p!==o,x=a?.access??n.access??"readWrite",b=(0,m.useCallback)(()=>{if(!p){u({type:"error",text:"Local folder path is required."});return}if(!Gas(p)){u({type:"error",text:"Local folder must be a full absolute path."});return}u(null),h.mutate(p)},[h,p]);return(0,t.jsxs)("div",{className:"space-y-4 rounded-md border border-border/70 bg-background px-4 py-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,t.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("h4",{className:"text-sm font-medium",children:n.displayName}),(0,t.jsx)(ct,{variant:"outline",className:"font-mono text-(length:--text-nano)",children:n.folderKey}),(0,t.jsx)(ct,{variant:a?.healthy?"default":"secondary",children:a?.healthy?"Healthy":"Needs attention"})]}),n.description?(0,t.jsx)("p",{className:"max-w-3xl text-sm leading-5 text-muted-foreground",children:n.description}):null]}),(0,t.jsx)(ct,{variant:x==="readWrite"?"default":"outline",children:x==="readWrite"?"Read/write":"Read only"})]}),(0,t.jsxs)("div",{className:"grid gap-3 text-sm sm:grid-cols-3",children:[(0,t.jsx)(fz,{label:"Configured",value:a?.configured?"Yes":"No",ok:!!a?.configured}),(0,t.jsx)(fz,{label:"Readable",value:a?.readable?"Yes":"No",ok:!!a?.readable}),(0,t.jsx)(fz,{label:"Writable",value:x==="read"?"Not requested":a?.writable?"Yes":"No",ok:x==="read"||!!a?.writable})]}),a?.path?(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("div",{className:"text-xs font-medium text-muted-foreground",children:"Configured path"}),(0,t.jsx)("div",{className:"break-all rounded-md bg-muted/60 px-2 py-1.5 font-mono text-xs text-foreground",children:a.path})]}):null,(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsx)("label",{className:"text-xs font-medium text-muted-foreground",htmlFor:`local-folder-${n.folderKey}`,children:"Local folder path"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("input",{id:`local-folder-${n.folderKey}`,className:"min-w-0 flex-1 rounded-md border border-border bg-background px-2.5 py-1.5 font-mono text-sm outline-none focus:border-foreground/40 focus:ring-2 focus:ring-ring/20",value:l,onChange:r(v=>{c(v.target.value),u(null)},"onChange"),placeholder:"/absolute/path/to/folder"}),(0,t.jsx)(Dd,{className:"h-8"}),(0,t.jsxs)(L,{size:"sm",onClick:b,disabled:h.isPending||!f||!s,children:[h.isPending?(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}):(0,t.jsx)(Cf,{className:"h-3.5 w-3.5"}),"Save"]})]})]}),(0,t.jsx)(Vas,{status:a,declaration:n}),a?.problems?.length?(0,t.jsxs)("div",{className:"space-y-2 rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[(0,t.jsx)("div",{className:"font-medium",children:"Validation problems"}),(0,t.jsx)("ul",{className:"space-y-1",children:a.problems.map((v,j)=>(0,t.jsxs)("li",{children:[v.message,v.path?(0,t.jsxs)("span",{className:"font-mono",children:[" ",v.path]}):null]},`${v.code}:${v.path??""}:${j}`))})]}):null,d?(0,t.jsx)("div",{className:`rounded-md border px-3 py-2 text-sm ${d.type==="success"?"border-green-200 bg-green-50 text-green-700 dark:border-green-900 dark:bg-green-950/30 dark:text-green-400":"border-destructive/20 bg-destructive/10 text-destructive"}`,children:d.text}):null]})}r(Was,"PluginLocalFolderRow");function fz({label:e,value:s,ok:n}){return(0,t.jsxs)("div",{className:"flex items-center justify-between rounded-md border border-border/60 px-2.5 py-2",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:e}),(0,t.jsx)(ct,{variant:n?"default":"secondary",children:s})]})}r(fz,"FolderStatusMetric");function Vas({status:e,declaration:s}){const n=e?.requiredDirectories??s.requiredDirectories??[],a=e?.requiredFiles??s.requiredFiles??[],i=e?.missingDirectories??n,o=e?.missingFiles??a,l=Has(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)(fpe,{title:"Required directories",items:n,missingItems:i,missingLabel:"Missing directories",inspectionUnavailable:l}),(0,t.jsx)(fpe,{title:"Required files",items:a,missingItems:o,missingLabel:"Missing files",inspectionUnavailable:l})]})}r(Vas,"FolderRequirements");function Has(e){return!e?.configured||e.readable?!1:e.problems.some(s=>s.code==="missing"||s.code==="not_readable"||s.code==="not_directory")}r(Has,"isRootNotInspected");function fpe({title:e,items:s,missingItems:n,missingLabel:a,inspectionUnavailable:i}){return(0,t.jsxs)("div",{className:"space-y-2 rounded-md border border-border/60 px-3 py-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:e}),i?(0,t.jsx)(ct,{variant:"secondary",className:"text-(length:--text-nano)",children:"Not inspected"}):n.length>0?(0,t.jsxs)(ct,{variant:"destructive",className:"text-(length:--text-nano)",children:[n.length," missing"]}):(0,t.jsx)(ct,{variant:"outline",className:"text-(length:--text-nano)",children:"Present"})]}),s.length>0?(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:s.map(o=>{const l=n.includes(o);return(0,t.jsx)("span",{className:`rounded border px-1.5 py-0.5 font-mono text-(length:--text-micro) ${i?"border-amber-300/60 bg-amber-50 text-amber-700 dark:border-amber-800/70 dark:bg-amber-950/30 dark:text-amber-300":l?"border-destructive/30 bg-destructive/10 text-destructive":"border-border bg-muted/50 text-foreground/80"}`,children:o},o)})}):(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"None declared."}),i?(0,t.jsx)("p",{className:"text-xs text-amber-700 dark:text-amber-300",children:"Configured root was not inspected."}):n.length>0?(0,t.jsxs)("p",{className:"text-xs text-destructive",children:[a,": ",n.join(", ")]}):null]})}r(fpe,"RequirementList");function Gas(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}r(Gas,"isLikelyAbsolutePath");function Qas({pluginId:e,companyId:s,schema:n,initialValues:a,isLoading:i,pluginStatus:o,supportsConfigTest:l}){const c=Pt(),[d,u]=(0,m.useState)(()=>({...bf(n),...a??{}})),h=(0,m.useRef)(!1);(0,m.useEffect)(()=>{h.current=!1,u(bf(n))},[s,e,n]),(0,m.useEffect)(()=>{a&&!h.current&&(h.current=!0,u({...bf(n),...a}))},[a,n]);const[p,f]=(0,m.useState)({}),[x,b]=(0,m.useState)(null),[v,j]=(0,m.useState)(null),N=JSON.stringify(d)!==JSON.stringify({...bf(n),...a??{}}),w=je({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before saving plugin configuration.");return Al.saveConfig(e,s,R)},"mutationFn"),onSuccess:r(()=>{b({type:"success",text:"Configuration saved."}),j(null),s&&c.invalidateQueries({queryKey:P.plugins.config(e,s)}),setTimeout(()=>b(null),3e3)},"onSuccess"),onError:r(R=>{b({type:"error",text:R.message||"Failed to save configuration."})},"onError")}),k=je({mutationFn:r(R=>{if(!s)throw new Error("Select an organization before testing plugin configuration.");return Al.testConfig(e,s,R)},"mutationFn"),onSuccess:r(R=>{R.valid?j({type:"success",text:"Configuration test passed."}):j({type:"error",text:R.message||"Configuration test failed."})},"onSuccess"),onError:r(R=>{j({type:"error",text:R.message||"Configuration test failed."})},"onError")}),S=(0,m.useCallback)(R=>{u(R),f({}),b(null)},[]),C=(0,m.useCallback)(()=>{const R=by(n,d);if(Object.keys(R).length>0){f(R);return}f({}),w.mutate(d)},[n,d,w]),I=(0,m.useCallback)(()=>{const R=by(n,d);if(Object.keys(R).length>0){f(R);return}f({}),j(null),k.mutate(d)},[n,d,k]);return i?(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-4",children:[(0,t.jsx)(rt,{className:"h-4 w-4 animate-spin"}),"Loading configuration..."]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(oA,{schema:n,values:d,onChange:S,errors:p,disabled:w.isPending}),x&&(0,t.jsx)("div",{className:`text-sm p-2 rounded border ${x.type==="success"?"text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-950/30 dark:border-green-900":"text-destructive bg-destructive/10 border-destructive/20"}`,children:x.text}),v&&(0,t.jsx)("div",{className:`text-sm p-2 rounded border ${v.type==="success"?"text-green-700 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-950/30 dark:border-green-900":"text-destructive bg-destructive/10 border-destructive/20"}`,children:v.text}),(0,t.jsxs)("div",{className:"flex items-center gap-2 pt-2",children:[(0,t.jsx)(L,{onClick:C,disabled:w.isPending||!N,size:"sm",children:w.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):"Save Configuration"}),o==="ready"&&l&&(0,t.jsx)(L,{variant:"outline",onClick:I,disabled:k.isPending||!s,size:"sm",children:k.isPending?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(rt,{className:"h-3.5 w-3.5 animate-spin"}),"Testing..."]}):"Test Configuration"})]})]})}r(Qas,"PluginConfigForm");function Yas(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(Yas,"formatUptime");function xpe(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${(e/6e4).toFixed(1)}m`}r(xpe,"formatDuration");function gpe(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(gpe,"formatRelativeTime");function Jas(e){return new Date(e).toLocaleString()}r(Jas,"formatTimestamp");function Xas({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(Xas,"JobStatusDot");function Zas({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(Zas,"DeliveryStatusDot");function xz({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:Bf(e.type)}),(0,t.jsx)(ct,{variant:"outline",children:e.source==="external"?"External":"Built-in"}),e.source==="external"&&(e.isLocalPath?(0,t.jsx)("span",{title:"Installed from local path",children:(0,t.jsx)(Go,{className:"h-4 w-4 text-amber-500"})}):(0,t.jsx)("span",{title:"Installed from npm",children:(0,t.jsx)(Th,{className:"h-4 w-4 text-red-500"})})),e.version&&(0,t.jsxs)(ct,{variant:"secondary",className:"font-mono text-(length:--text-nano)",children:["v",e.version]}),e.overriddenBuiltin&&(0,t.jsx)(ct,{variant:"secondary",className:"text-blue-600 border-blue-400",children:"Overrides built-in"}),u&&(0,t.jsxs)(ct,{variant:"secondary",className:"text-blue-600 border-blue-400",children:["Overridden by ",u]}),e.disabled&&(0,t.jsx)(ct,{variant:"secondary",className:"text-amber-600 border-amber-400",children:f??"Hidden from menus"})]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5",children:[e.type,e.packageName&&e.packageName!==e.type&&(0,t.jsxs)(t.Fragment,{children:[" · ",e.packageName]})," · ",e.modelsCount," models"]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2 shrink-0",children:[o&&(0,t.jsx)(L,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:"Reinstall adapter (pull latest from npm)",disabled:d,onClick:r(()=>o(e.type),"onClick"),children:(0,t.jsx)(po,{className:W("h-4 w-4",d&&"animate-bounce")})}),i&&(0,t.jsx)(L,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:"Reload adapter (hot-swap)",disabled:c,onClick:r(()=>i(e.type),"onClick"),children:(0,t.jsx)(_i,{className:W("h-4 w-4",c&&"animate-spin")})}),(0,t.jsx)(L,{variant:"outline",size:"icon-sm",className:"h-8 w-8",title:e.disabled?h??"Show in agent menus":p??"Hide from agent menus",disabled:l,onClick:r(()=>n(e.type,!e.disabled),"onClick"),children:(0,t.jsx)(B7,{className:W("h-4 w-4",e.disabled?"text-muted-foreground":"text-green-600")})}),s&&(0,t.jsx)(L,{variant:"outline",size:"icon-sm",className:"h-8 w-8 text-destructive hover:text-destructive",title:"Remove adapter",onClick:r(()=>a(e.type),"onClick"),children:(0,t.jsx)(la,{className:"h-4 w-4"})})]})]})})}r(xz,"AdapterRow");function eis(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(eis,"fetchNpmLatestVersion");function tis({adapter:e,open:s,isReinstalling:n,onConfirm:a,onCancel:i}){const{data:o,isLoading:l}=ee({queryKey:["npm-latest-version",e?.packageName],queryFn:r(()=>e?.packageName?eis(e.packageName):null,"queryFn"),enabled:s&&!!e?.packageName,staleTime:6e4}),c=e?.version&&o&&e.version===o;return(0,t.jsx)(Ys,{open:s,onOpenChange:r(d=>{d||i()},"onOpenChange"),children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Reinstall Adapter"}),(0,t.jsxs)(jn,{children:["This will pull the latest version of"," ",(0,t.jsx)("strong",{children:e?.packageName})," from npm and hot-swap the running adapter module. Existing agents will use the new version on their next run."]})]}),(0,t.jsxs)("div",{className:"rounded-md border bg-muted/50 px-4 py-3 text-sm space-y-1",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Package"}),(0,t.jsx)("span",{className:"font-mono",children:e?.packageName})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Current"}),(0,t.jsx)("span",{className:"font-mono",children:e?.version?`v${e.version}`:"unknown"})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)("span",{className:"text-muted-foreground",children:"Latest on npm"}),(0,t.jsx)("span",{className:"font-mono",children:l?"checking...":o?`v${o}`:"unavailable"})]}),c&&(0,t.jsx)("p",{className:"text-xs text-muted-foreground pt-1",children:"Already on the latest version."})]}),(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:i,disabled:n,children:"Cancel"}),(0,t.jsx)(L,{disabled:n,onClick:a,children:n?"Reinstalling...":"Reinstall"})]})]})})}r(tis,"ReinstallDialog");function bpe(){const{selectedCompany:e}=ps(),{setBreadcrumbs:s}=Bn(),n=Pt(),{pushToast:a}=da(),[i,o]=(0,m.useState)(""),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(!1),[h,p]=(0,m.useState)(!1),[f,x]=(0,m.useState)(null),[b,v]=(0,m.useState)(null);(0,m.useEffect)(()=>{s([{label:e?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Adapters"}])},[e?.name,s]);const{data:j,isLoading:N}=ee({queryKey:P.adapters.all,queryFn:r(()=>uh.list(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:P.adapters.all})},"invalidate"),k=je({mutationFn:r(E=>uh.install(E),"mutationFn"),onSuccess:r(E=>{w(),p(!1),o(""),c(""),u(!1),a({title:"Adapter installed",body:`Type "${E.type}" registered successfully.${E.version?` (v${E.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Install failed",body:E.message,tone:"error"})},"onError")}),S=je({mutationFn:r(E=>uh.remove(E),"mutationFn"),onSuccess:r(()=>{w(),a({title:"Adapter removed",tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Removal failed",body:E.message,tone:"error"})},"onError")}),C=je({mutationFn:r(({type:E,disabled:z})=>uh.setDisabled(E,z),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(E=>{a({title:"Toggle failed",body:E.message,tone:"error"})},"onError")}),I=je({mutationFn:r(({type:E,paused:z})=>uh.setOverridePaused(E,z),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(E=>{a({title:"Override toggle failed",body:E.message,tone:"error"})},"onError")}),R=je({mutationFn:r(E=>uh.reload(E),"mutationFn"),onSuccess:r(E=>{w(),Xq(E.type),fte(E.type),a({title:"Adapter reloaded",body:`Type "${E.type}" reloaded.${E.version?` (v${E.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Reload failed",body:E.message,tone:"error"})},"onError")}),T=je({mutationFn:r(E=>uh.reinstall(E),"mutationFn"),onSuccess:r(E=>{w(),Xq(E.type),fte(E.type),a({title:"Adapter reinstalled",body:`Type "${E.type}" updated from npm.${E.version?` (v${E.version})`:""}`,tone:"success"})},"onSuccess"),onError:r(E=>{a({title:"Reinstall failed",body:E.message,tone:"error"})},"onError")}),A=(j??[]).filter(E=>E.source==="builtin"),D=(j??[]).filter(E=>E.source==="external"),M=(j??[]).filter(E=>E.source==="external"&&E.overriddenBuiltin).filter(E=>!A.some(z=>z.type===E.type)).map(E=>({type:E.type,label:Bf(E.type),overriddenBy:[E.packageName,E.version?`v${E.version}`:void 0].filter(Boolean).join(" "),overridePaused:!!E.overridePaused,menuDisabled:!!E.disabled}));if(N)return(0,t.jsx)("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading adapters..."});const B=k.isPending||S.isPending||C.isPending||I.isPending||R.isPending||T.isPending;return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(ym,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Adapters"}),(0,t.jsx)(ct,{variant:"outline",className:"text-amber-600 border-amber-400",children:"Alpha"})]}),(0,t.jsxs)(Ys,{open:h,onOpenChange:p,children:[(0,t.jsx)(Uy,{asChild:!0,children:(0,t.jsxs)(L,{size:"sm",className:"gap-2",children:[(0,t.jsx)(yn,{className:"h-4 w-4"}),"Install Adapter"]})}),(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Install External Adapter"}),(0,t.jsxs)(jn,{children:["Add an adapter from npm or a local path. The adapter package must export ",(0,t.jsx)("code",{className:"text-xs bg-muted px-1 py-0.5 rounded",children:"createServerAdapter()"}),"."]})]}),(0,t.jsxs)("div",{className:"grid gap-4 py-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsxs)("button",{type:"button",className:W("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors",d?"border-border text-muted-foreground hover:text-foreground hover:bg-accent/50":"border-foreground bg-accent text-foreground"),onClick:r(()=>u(!1),"onClick"),children:[(0,t.jsx)(Th,{className:"h-3.5 w-3.5"}),"npm package"]}),(0,t.jsxs)("button",{type:"button",className:W("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition-colors",d?"border-foreground bg-accent text-foreground":"border-border text-muted-foreground hover:text-foreground hover:bg-accent/50"),onClick:r(()=>u(!0),"onClick"),children:[(0,t.jsx)(Go,{className:"h-3.5 w-3.5"}),"Local path"]})]}),d?(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Qs,{htmlFor:"adapterLocalPath",children:"Path to adapter package"}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(ht,{id:"adapterLocalPath",className:"flex-1 font-mono text-xs",placeholder:"/mnt/e/Projects/my-adapter or E:\\Projects\\my-adapter",value:i,onChange:r(E=>o(E.target.value),"onChange")}),(0,t.jsx)(Dd,{})]}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Accepts Linux, WSL, and Windows paths. Windows paths are auto-converted."})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Qs,{htmlFor:"adapterPackageName",children:"Package Name"}),(0,t.jsx)(ht,{id:"adapterPackageName",placeholder:"my-paperclip-adapter",value:i,onChange:r(E=>o(E.target.value),"onChange")})]}),(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Qs,{htmlFor:"adapterVersion",children:"Version (optional)"}),(0,t.jsx)(ht,{id:"adapterVersion",placeholder:"latest",value:l,onChange:r(E=>c(E.target.value),"onChange")})]})]})]}),(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>p(!1),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{onClick:r(()=>k.mutate({packageName:i,version:l||void 0,isLocalPath:d}),"onClick"),disabled:!i||k.isPending,children:k.isPending?"Installing...":"Install"})]})]})]})]}),(0,t.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(Es,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-700"}),(0,t.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,t.jsx)("p",{className:"font-medium text-foreground",children:"External adapters are alpha."}),(0,t.jsx)("p",{className:"text-muted-foreground",children:"The adapter plugin system is under active development. APIs and storage format may change. Use the power icon to hide adapters from agent menus without removing them."})]})]})}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(ym,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"External Adapters"})]}),D.length===0?(0,t.jsx)(rn,{className:"bg-muted/30",children:(0,t.jsxs)(Xa,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(ym,{className:"h-10 w-10 text-muted-foreground mb-4"}),(0,t.jsx)("p",{className:"text-sm font-medium",children:"No external adapters installed"}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Install an adapter package to extend model support."})]})}):(0,t.jsx)(rn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:D.map(E=>{const z=E.overriddenBuiltin,$=z&&!!E.overridePaused,q=z?{...E,disabled:$??!1}:E;return(0,t.jsx)(xz,{adapter:q,canRemove:!0,onToggle:z?(U,O)=>I.mutate({type:U,paused:O}):(U,O)=>C.mutate({type:U,disabled:O}),onRemove:r(U=>x(U),"onRemove"),onReload:r(U=>R.mutate(U),"onReload"),onReinstall:E.isLocalPath?void 0:U=>v(E),isToggling:z?I.isPending:C.isPending,isReloading:R.isPending,isReinstalling:T.isPending,toggleTitleDisabled:z?"Pause external override":void 0,toggleTitleEnabled:z?"Resume external override":void 0,disabledBadgeLabel:z?"Override paused":void 0},E.type)})})})]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(ym,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Built-in Adapters"})]}),A.length===0&&M.length===0?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"No built-in adapters found."}):(0,t.jsx)(rn,{className:"block py-0",children:(0,t.jsxs)("ul",{className:"divide-y",children:[A.map(E=>(0,t.jsx)(xz,{adapter:E,canRemove:!1,onToggle:r((z,$)=>C.mutate({type:z,disabled:$}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:B},E.type)),M.map(E=>(0,t.jsx)(xz,{adapter:{type:E.type,label:E.label,source:"builtin",modelsCount:0,loaded:!0,disabled:E.menuDisabled,capabilities:{supportsInstructionsBundle:!1,supportsSkills:!1,supportsLocalAgentJwt:!1,requiresMaterializedRuntimeSkills:!1,supportsAcp:!1}},canRemove:!1,onToggle:r((z,$)=>C.mutate({type:z,disabled:$}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:B,overriddenBy:E.overridePaused?void 0:E.overriddenBy},E.type))]})})]}),(0,t.jsx)(Ys,{open:f!==null,onOpenChange:r(E=>{E||x(null)},"onOpenChange"),children:(0,t.jsxs)(Js,{children:[(0,t.jsxs)(hn,{children:[(0,t.jsx)(Xs,{children:"Remove Adapter"}),(0,t.jsxs)(jn,{children:["Are you sure you want to remove the ",(0,t.jsx)("strong",{children:f})," adapter? It will be unregistered and removed from the adapter store.",f&&j?.find(E=>E.type===f)?.packageName&&(0,t.jsx)(t.Fragment,{children:" npm packages will be cleaned up from disk."})," ","This action cannot be undone."]})]}),(0,t.jsxs)(hr,{children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Cancel"}),(0,t.jsx)(L,{variant:"destructive",disabled:S.isPending,onClick:r(()=>{f&&S.mutate(f,{onSettled:r(()=>x(null),"onSettled")})},"onClick"),children:S.isPending?"Removing...":"Remove"})]})]})}),(0,t.jsx)(tis,{adapter:b,open:b!==null,isReinstalling:T.isPending,onConfirm:r(()=>{b&&T.mutate(b.type,{onSettled:r(()=>v(null),"onSettled")})},"onConfirm"),onCancel:r(()=>v(null),"onCancel")})]})}r(bpe,"AdapterManager");function vpe(){const e=va(),{companyPrefix:s,pluginId:n,pluginRoutePath:a}=e,i=e["*"],{companies:o,selectedCompanyId:l}=ps(),{setBreadcrumbs:c}=Bn(),d=(0,m.useMemo)(()=>{if(!s)return null;const j=s.toUpperCase();return o.find(N=>N.issuePrefix.toUpperCase()===j)??null},[o,s]),u=!!s&&!d,h=(0,m.useMemo)(()=>d?d.id:s?null:l??null,[d,s,l]),p=(0,m.useMemo)(()=>h?o.find(j=>j.id===h)?.issuePrefix??null:null,[o,h]),{data:f}=ee({queryKey:P.plugins.uiContributions,queryFn:r(()=>Al.listUiContributions(),"queryFn"),enabled:!!h&&(!!n||!!a)}),x=(0,m.useMemo)(()=>{if(!f)return null;if(n){const N=f.find(k=>k.pluginId===n);if(!N)return null;const w=N.slots.find(k=>k.type==="page");return w?{...w,pluginId:N.pluginId,pluginKey:N.pluginKey,pluginDisplayName:N.displayName,pluginVersion:N.version}:null}if(!a)return null;const j=f.flatMap(N=>{const w=N.slots.find(k=>k.type==="page"&&k.routePath===a);return w?[{...w,pluginId:N.pluginId,pluginKey:N.pluginKey,pluginDisplayName:N.displayName,pluginVersion:N.version}]:[]});return j.length!==1?null:j[0]??null},[n,a,f]),b=(0,m.useMemo)(()=>({companyId:h??null,companyPrefix:p}),[h,p]),v=(0,m.useMemo)(()=>{if(!a||!f)return!1;const j=f.flatMap(N=>N.slots.map(w=>({...w,pluginId:N.pluginId,pluginKey:N.pluginKey,pluginDisplayName:N.displayName,pluginVersion:N.version})));return l9(j,a)!==null},[f,a]);if((0,m.useEffect)(()=>{if(x){if(v){c([{label:sis(x,i)}]);return}c([{label:"Plugins",href:"/company/settings/instance/plugins"},{label:x.pluginDisplayName}])}},[x,i,c,v]),!h)return u?(0,t.jsx)(zu,{scope:"invalid_company_prefix",requestedPrefix:s}):(0,t.jsx)("div",{className:"space-y-4",children:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select an organization to view this page."})});if(!f)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading…"});if(!n&&a&&f.filter(j=>j.slots.some(N=>N.type==="page"&&N.routePath===a)).length>1)return(0,t.jsxs)("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:["Multiple plugins declare the route ",(0,t.jsx)("code",{children:a}),". Use the plugin-id route until the conflict is resolved."]});if(!x){if(a)return(0,t.jsx)(zu,{scope:"board"});const j=n?`/company/settings/instance/plugins/${n}`:"/company/settings/instance/plugins";return(0,t.jsx)(kn,{to:j,replace:!0})}return(0,t.jsxs)("div",{className:"space-y-4",children:[!v&&(0,t.jsx)("div",{className:"flex items-center gap-2",children:(0,t.jsx)(L,{variant:"ghost",size:"sm",asChild:!0,children:(0,t.jsxs)(Ke,{to:p?`/${p}/dashboard`:"/dashboard",children:[(0,t.jsx)(Tl,{className:"h-4 w-4 mr-1"}),"Back"]})})}),(0,t.jsx)(Wu,{slot:x,context:b,className:"min-h-(--sz-200px)",missingBehavior:"placeholder"})]})}r(vpe,"PluginPage");function sis(e,s){return nis(s)??e.displayName??e.pluginDisplayName}r(sis,"resolveRouteSidebarPageTitle");function nis(e){const s=(e??"").split("/").filter(Boolean).map(ris);return s.length===0?null:s[0]==="page"&&s.length>1?ype(s.slice(1).join("/"),{preserveCase:!0}):ype(s[0]??null)}r(nis,"titleFromRouteSplat");function ype(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(ype,"titleFromPath");function ris(e){try{return decodeURIComponent(e)}catch{return e}}r(ris,"decodeRouteSegment");var $C="w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-sm leading-5 outline-none focus-visible:ring-2 focus-visible:ring-ring",jpe=r(e=>e.status==="fail"||e.checks.some(s=>s.code==="adapter_auth_missing"),"blocking");function ais(){const{selectedCompanyId:e}=ps(),[s]=fi();return e?(0,t.jsx)(iis,{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(ais,"NewAgentSetup");function iis({companyId:e,name:s,adapterType:n,runnerProvider:a,createdAgentId:i}){const o=Mn(),l=Pt(),{openNewIssue:c}=Yo(),d=VSe(`${e}:new-agent`),u=n==="paperclip_runner",h=u?a==="grok"?"grok_local":a==="claude"?"claude_local":a==="opencode"?"opencode_local":"codex_local":n,p=h==="claude_local"||h==="codex_local"||h==="grok_local"?h:null,f=h==="opencode_local"||h==="pi_local",x=YZe(h),b=f||h==="hermes_local",v=b||!!ute[n],j=!["cursor_cloud","hermes_gateway"].includes(n),[N,w]=(0,m.useState)(""),[k,S]=(0,m.useState)(""),[C,I]=(0,m.useState)(""),[R,T]=(0,m.useState)("kimi"),[A,D]=(0,m.useState)(i?"saved":p?"connect":"runtime"),[M,B]=(0,m.useState)(""),E=u?[]:I5(n,M),[z,$]=(0,m.useState)(""),[q,U]=(0,m.useState)(!1),[O,K]=(0,m.useState)(""),[H,Z]=(0,m.useState)("openrouter"),[se,ne]=(0,m.useState)(""),[fe,X]=(0,m.useState)(null),[re,oe]=(0,m.useState)(()=>h==="opencode_local"?{provider:"openrouter",method:"api_key",mode:"responsible_user"}:void 0),[G,Y]=(0,m.useState)(null),Q=re??G?.aiConnection,[te,ae]=(0,m.useState)(""),[le,he]=(0,m.useState)(""),[ce,ge]=(0,m.useState)(null),me=ee({queryKey:P.agents.detail(i??"new"),queryFn:r(()=>$t.get(i,e),"queryFn"),enabled:!!i,retry:!1}),ie=ce??(me.data?.companyId===e?me.data:null),[ue,ke]=(0,m.useState)(!1),[be,Ie]=(0,m.useState)("idle"),[Ue,at]=(0,m.useState)(null),[dt,de]=(0,m.useState)(null),Be=(0,m.useRef)(0),pt=(0,m.useRef)(!1);(0,m.useEffect)(()=>()=>{Be.current++},[]);const vt=r(()=>{Be.current++,at(null),Ie("idle"),de(null)},"resetTest"),Le=ee({queryKey:P.adapters.all,queryFn:uh.list}),Qe=ee({queryKey:P.agents.list(e),queryFn:r(()=>$t.list(e),"queryFn")}),ut=ee({queryKey:P.environments.list(e),queryFn:r(()=>Pi.list(e),"queryFn")}),Ye=ee({queryKey:P.instance.settings,queryFn:Nr.get}),it=ee({queryKey:P.instance.experimentalSettings,queryFn:Nr.getExperimental}),kt=ee({queryKey:P.instance.generalSettings,queryFn:Nr.getGeneral}),tt=ee({queryKey:P.environments.capabilities(e),queryFn:r(()=>Pi.capabilities(e),"queryFn")}),Pe=ee({queryKey:P.agents.adapterModels(e,h,null,Q?.provider),queryFn:r(()=>$t.adapterModels(e,h,{provider:Q?.provider}),"queryFn"),enabled:!!h&&j,retry:!1}),Ce=ee({queryKey:P.secrets.list(e),queryFn:r(()=>yr.list(e),"queryFn"),enabled:v&&n!=="cursor_cloud"}),He=ee({queryKey:P.secrets.myUserSecrets(e),queryFn:r(()=>yr.listMyUserSecrets(e),"queryFn"),enabled:v&&n!=="cursor_cloud",retry:!1}),Je=zW(kt.data?.executionMode,ut.data??[]),lt=it.data?.enableManagedSandboxOnly===!0;let Ee=null,Xe=null;try{Ee=Je.forced?Je.kubernetesEnvironment?.id??null:iN({agentDefaultEnvironmentId:O||null,instanceDefaultEnvironmentId:Ye.data?.defaultEnvironmentId??null,localDefaultEnvironmentId:lN(ut.data??[]),managedSandboxOnly:lt,managedSandboxEnvironmentId:oN(ut.data??[]),visibleEnvironmentIds:(ut.data??[]).map(Fe=>Fe.id)})}catch(Fe){Xe=Fe instanceof Error?Fe.message:"Could not resolve the environment."}const Ae=ut.data?.find(Fe=>Fe.id===Ee),De=typeof Ae?.config?.provider=="string"?Ae.config.provider:"",_t=Ae?.driver==="sandbox"&&tt.data?.sandboxProviders?.[De]?.supportsLoginPty===!0,ye=ute[n]??x[H]??"API_KEY",gt=He.data?.find(Fe=>Fe.definition.key===ye&&Fe.secret),We=Ce.data?.find(Fe=>Fe.key===ye&&Fe.status==="active"),Ot=n==="cursor_cloud"?null:fe??(We?{type:"secret_ref",secretId:We.id,version:"latest"}:gt?{type:"user_secret_ref",key:ye,version:"latest"}:null),zt=n==="kimi_local"&&!!(se.trim()||Ot),Cs=!!$c(),ze=HSe(n,{cloud:Cs,nativeRunnerEnabled:it.data?.enableNativeRunner===!0})&&Le.data?.some(Fe=>Fe.type===n&&Fe.loaded&&!Fe.disabled&&!Ch(n).comingSoon),ft=!!(ze&&!Xe&&!ut.isPending&&!Ye.isPending&&!it.isPending&&!kt.isPending&&!Qe.isPending&&!tt.isPending&&!ut.error&&!Ye.error&&!it.error&&!kt.error&&!Qe.error&&!tt.error&&(!(lt||Je.forced)||Ee)),Ut=be==="running"||ue;function Ns(Fe=G,st=Ot){const xt={...ab,adapterType:n,model:M||(h==="codex_local"?nN:""),thinkingEffort:z,dangerouslyBypassSandbox:n==="codex_local",envBindings:Fe?.env??{},...u?{adapterSchemaValues:{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{}}}:{}},Oe=iS(n).buildAdapterConfig(xt);return u&&Object.assign(Oe,{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{},...M?{model:M}:{}}),!Q&&!Fe?.aiConnection&&v&&st&&(n==="hermes_gateway"?Oe.apiKey=st:Oe.env={...Oe.env??{},[ye]:st}),n==="cursor_cloud"&&Object.assign(Oe,{repoUrl:te.trim(),...le.trim()?{repoStartingRef:le.trim()}:{}}),n==="hermes_gateway"&&(Oe.apiBaseUrl=N.trim()),zt&&(delete Oe.model,Oe.env={...Oe.env??{},KIMI_MODEL_NAME:{type:"plain",value:k.trim()},KIMI_MODEL_PROVIDER_TYPE:{type:"plain",value:R},...C.trim()?{KIMI_MODEL_BASE_URL:{type:"plain",value:C.trim()}}:{}}),Oe}r(Ns,"buildConfig");function Is(Fe=G){if(f&&(!M.trim()||!M.includes("/")))throw new Error("Choose or enter a model in provider/model format.");if(n==="cursor_cloud"&&!/^https:\/\/github\.com\/[^/]+\/[^/]+/.test(te.trim()))throw new Error("Enter a GitHub repository URL.");if(["cursor_cloud","hermes_gateway"].includes(n)&&!se.trim()&&!Ot)throw new Error(n==="cursor_cloud"?"Enter a Cursor API key.":`Enter ${ye} or select an organization secret.`);if(n==="hermes_gateway")try{const st=new URL(N.trim());if(!["https:","http:"].includes(st.protocol))throw new Error}catch{throw new Error("Enter the Hermes API base URL.")}if(zt&&!k.trim())throw new Error("Enter the Kimi API model name.");return Ns(Fe)}r(Is,"preparedConfig");function Ct(Fe=G){return Q||Fe?.aiConnection?{}:{...Fe?.credentials,...v&&se.trim()?{[ye]:se.trim()}:{}}}r(Ct,"pendingCredentials");async function ds(Fe=G){if(!ft)return!1;const st=++Be.current;Ie("running"),at(null),de(null);try{const xt=await Is(Fe),Oe=await TNe({companyId:e,adapterType:n,providerAdapter:h,adapterConfig:xt,testCredentials:Ct(Fe),aiConnection:re??Fe?.aiConnection,environmentId:Ee});return st!==Be.current?!1:(at(Oe),Ie(jpe(Oe)?"fail":Oe.status),!jpe(Oe)&&(!p||Oe.checks.some(Bt=>Bt.code.endsWith("hello_probe_passed"))))}catch(xt){return st===Be.current&&(de(xt instanceof Error?xt.message:"Could not test the agent."),Ie("fail")),!1}}r(ds,"runTest");async function $e(){if(pt.current||i||ie||!ft||!s.trim()||be==="running"||be==="fail"||p&&!G)return;pt.current=!0,ke(!0),de(null);const Fe=[];let st=!1;try{const xt=Is(),Oe=Ct();if(Object.keys(Oe).length&&!await ds())return;for(const[Yt,hs]of Object.entries(Oe)){const Ts=await(p?zNe:GZe)(e,Yt,hs);Fe.push(Ts),n==="hermes_gateway"&&Yt==="API_SERVER_KEY"?xt.apiKey=Ts.binding:xt.env={...xt.env??{},[Yt]:Ts.binding}}const Bt=Qe.data??[],wt=Bt.find(Yt=>Yt.role==="ceo"&&Yt.status!=="terminated"),Xt=await $t.hire(e,{name:s.trim(),appearance:d.appearance,role:Bt.length?"general":"ceo",...wt?{reportsTo:wt.id}:{},adapterType:n,adapterConfig:xt,defaultEnvironmentId:O||(Je.forced||lt?Ee:null),runtimeConfig:{...L_e({heartbeatEnabled:!1}),...Q?{aiConnection:Q}:{}},budgetMonthlyCents:0,...G?.storedSessionId?{storedSessionId:G.storedSessionId}:{},...G?.applyStoredClaudeLogin?{applyStoredClaudeLogin:!0}:{}});st=!0,ne(""),Y(null),ge(Xt.agent),d.clear(),D("saved"),o(`/agents/new?${new URLSearchParams({name:Xt.agent.name,adapterType:n,runnerProvider:a,createdAgentId:Xt.agent.id})}`,{replace:!0}),l.setQueryData(P.agents.detail(Xt.agent.id),Xt.agent),await Promise.all([l.invalidateQueries({queryKey:P.agents.list(e)}),l.invalidateQueries({queryKey:P.approvals.list(e)})])}catch(xt){de(xt instanceof Error?xt.message:"Could not create the agent.")}finally{if(!st)try{await Promise.all(Fe.map(xt=>xt.remove()))}catch{de(xt=>`${xt?`${xt} `:""}Could not remove an unused setup credential. Remove it from Secrets before retrying.`)}l.invalidateQueries({queryKey:P.secrets.myUserSecrets(e)}),l.invalidateQueries({queryKey:P.secrets.list(e)}),pt.current=!1,ke(!1)}}if(r($e,"finish"),i&&!ie)return(0,t.jsx)("p",{role:me.error?"alert":"status",className:"text-sm text-muted-foreground",children:me.error?"Could not load the created agent. Return to Agents to view it.":"Loading your agent…"});if(!s||!n)return(0,t.jsx)(GSe,{open:!0,initialAdapter:n,onClose:r(()=>o("/agents/all"),"onClose"),onContinue:r(Fe=>o(`/agents/new?${new URLSearchParams(Fe)}`,{replace:!0}),"onContinue")});const xe=[...p?["connect"]:[],"runtime","saved"],Qt={connect:"Connect",runtime:"Configure",saved:"Confirmation"},Dt=ie?.defaultEnvironmentId?ut.data?.find(Fe=>Fe.id===ie.defaultEnvironmentId):Ae,rs=ie?.adapterConfig?.env?.KIMI_MODEL_NAME,ws=ie?.adapterConfig?.model||(typeof rs=="string"?rs:rs?.value)||M||"Default",Bs=n==="cursor_cloud"?"Cursor Cloud":n==="hermes_gateway"?"Hermes Gateway":Dt?Yv(Dt):"Local machine",er=Le.error??ut.error??Ye.error??it.error??kt.error??Qe.error??tt.error;return(0,t.jsx)(fNe,{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)(B_,{appearance:ie?.appearance??d.appearance,size:256,className:"size-48",trackingScope:"page",state:ie||be==="pass"?"success":be==="running"?"loading":"sleepy",muted:!ie&&be!=="pass"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)("h1",{className:"text-2xl font-semibold tracking-tight",children:s}),(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,t.jsx)(KW,{type:h}),(0,t.jsx)("span",{children:Ch(h).label}),u&&(0,t.jsxs)("span",{children:["·"," ",a==="codex"?"Native app server runner":"Paperclip Runner"]})]})]})]}),Xe&&!ut.isPending&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:Xe}),er&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:er.message}),Le.data&&!ze&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"This adapter is unavailable. Choose an enabled adapter."}),(lt||Je.forced)&&!ut.isPending&&!Ee&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"No managed environment is available. Configure an environment before continuing."}),(0,t.jsxs)("div",{className:"flex flex-col gap-8 md:flex-row",children:[(0,t.jsx)("nav",{"aria-label":"Agent setup steps",className:"shrink-0 md:w-44",children:(0,t.jsx)("ol",{className:"flex flex-wrap gap-2 md:flex-col",children:xe.map((Fe,st)=>(0,t.jsx)("li",{children:(0,t.jsxs)("button",{type:"button","aria-current":Fe===A?"step":void 0,disabled:Ut||!!ie||st>xe.indexOf(A),onClick:r(()=>D(Fe),"onClick"),className:W("flex w-full items-center gap-3 rounded-md px-3 py-3 text-left text-sm",Fe===A?"bg-accent font-medium":"text-muted-foreground"),children:[(0,t.jsx)("span",{className:W("flex size-6 shrink-0 items-center justify-center rounded-full border text-xs",Fe===A?"border-foreground bg-foreground text-background":"border-border"),children:st+1}),Qt[Fe]]})},Fe))})}),(0,t.jsx)("div",{className:"min-w-0 flex-1",children:(0,t.jsx)(aS,{mode:"wait",initial:!1,children:(0,t.jsx)(Il.div,{...het,children:A==="connect"&&p?(0,t.jsxs)(rft,{className:"mx-auto",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)($_e,{title:"Connect a model",lede:`Connect ${s} to ${p==="claude_local"?"Claude":p==="grok_local"?"Grok":"OpenAI"}.`,center:!0})}),(0,t.jsx)("div",{className:"mb-5",children:(0,t.jsx)(Ss,{label:"Environment",children:(0,t.jsxs)("select",{"aria-label":"Environment",className:$C,value:O,disabled:Ut||Je.forced,onChange:r(Fe=>{K(Fe.target.value),Y(null),vt()},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Bs]}),(ut.data??[]).filter(Fe=>Fe.status==="active"&&(!lt||Fe.driver!=="local")).map(Fe=>(0,t.jsx)("option",{value:Fe.id,children:Yv(Fe)},Fe.id))]})})}),(0,t.jsx)(XSe,{companyId:e,adapterType:p,environmentId:Ee,canLogin:_t,localEnvironment:Ae?.driver==="local",onBack:r(()=>o("/agents/all"),"onBack"),testConnection:ds,testError:dt??(Ue?.checks.find(Fe=>Fe.level==="error")??Ue?.checks.find(Fe=>Fe.code.includes("hello_probe")&&Fe.level==="warn"))?.message,onConnected:r(Fe=>{Y(Fe),vt(),D("runtime")},"onConnected")},Ee??"local")]}):A==="saved"&&ie?(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-6 rounded-lg border border-border p-6",children:[(0,t.jsxs)("h2",{className:"flex items-center gap-3 text-lg font-semibold",children:[(0,t.jsx)(gs,{className:"size-5"}),ie.status==="pending_approval"?"Agent submitted for approval":"Your agent is ready"]}),(0,t.jsxs)("dl",{className:"grid grid-cols-2 gap-4 text-sm",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Adapter"}),(0,t.jsx)("dd",{children:Ch(n).label}),j&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Model"}),(0,t.jsx)("dd",{className:"break-all",children:String(ws)})]}),(0,t.jsx)("dt",{className:"text-muted-foreground",children:"Environment"}),(0,t.jsx)("dd",{children:Bs})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:ie.status==="pending_approval"?"An organization administrator must approve this agent before it can work.":"Assign a task when you’re ready for this agent to work."})]}),(0,t.jsxs)("div",{className:"flex flex-wrap justify-between gap-3",children:[(0,t.jsxs)(L,{variant:"outline",onClick:r(()=>o(`${Cm(ie)}/runtime`),"onClick"),children:[(0,t.jsx)(U7,{className:"size-4"}),"Edit configuration"]}),(0,t.jsxs)(L,{disabled:ie.status==="pending_approval",onClick:r(()=>c({assigneeAgentId:ie.id,status:"todo"}),"onClick"),children:["Assign ",ie.name," a Task",(0,t.jsx)(pl,{className:"size-4"})]})]})]}):(0,t.jsxs)("form",{className:"space-y-8",onSubmit:r(Fe=>{Fe.preventDefault(),$e()},"onSubmit"),children:[(0,t.jsx)("h2",{className:"text-xl font-semibold",children:"Configure your agent"}),(0,t.jsxs)("fieldset",{disabled:Ut,className:"space-y-8",children:[(0,t.jsxs)("section",{className:"space-y-5",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:"Runtime"}),SW(h)&&(G&&!Q?(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Using the connection selected in the Connect step."}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>D("connect"),"onClick"),children:"Change connection"})]}):(0,t.jsx)(ANe,{companyId:e,agentName:s,adapterType:h,model:M,environmentId:Ee??void 0,value:Q,onChange:r(Fe=>{Fe.mode!=="router"&&oe(Fe),vt()},"onChange")})),Pe.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"Could not load models. Retry or enter a model ID manually."}),(j&&!zt||E.length>0)&&(0,t.jsxs)("div",{className:"grid items-start gap-5 sm:grid-cols-2",children:[j&&!zt&&(0,t.jsx)(UW,{models:Pe.data??[],value:M,onChange:r(Fe=>{B(Fe),z&&!I5(n,Fe).includes(z)&&$("");const st=Fe.split("/")[0];f&&BNe[st]&&st!==H&&(Z(st),ne(""),X(null)),vt()},"onChange"),open:q,onOpenChange:U,allowDefault:!f,required:f,creatable:!0,groupByProvider:f,preserveOrder:PW(h)}),E.length>0&&(0,t.jsx)(Ss,{label:"Thinking effort",children:(0,t.jsxs)("select",{"aria-label":"Thinking effort",className:$C,value:z,onChange:r(Fe=>{$(Fe.target.value),vt()},"onChange"),children:[(0,t.jsx)("option",{value:"",children:"Auto"}),E.map(Fe=>(0,t.jsx)("option",{value:Fe,children:Fe},Fe))]})})]}),mte[n]&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:mte[n]}),j&&Pe.error&&(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Couldn’t load models. You can enter a model ID manually."}),v&&!Q&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[b&&(0,t.jsx)(Ss,{label:"API key provider",children:(0,t.jsx)("select",{"aria-label":"API key provider",className:$C,value:H,onChange:r(Fe=>{Z(Fe.target.value),B(""),ne(""),X(null),vt()},"onChange"),children:Object.keys(x).map(Fe=>(0,t.jsx)("option",{value:Fe,children:Fe==="openrouter"?"OpenRouter":Fe==="openai"?"OpenAI":Fe==="anthropic"?"Anthropic":{google:"Google",xai:"xAI",groq:"Groq",opencode:"OpenCode"}[Fe]??Fe},Fe))})}),(0,t.jsx)("div",{className:n==="cursor_cloud"?"sm:col-span-2":void 0,children:(0,t.jsx)(Ss,{label:ye,children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(ht,{"aria-label":ye,type:"password",autoComplete:"off",value:se,onChange:r(Fe=>{ne(Fe.target.value),X(null),vt()},"onChange"),placeholder:Ot?"Using saved key":["cursor_cloud","hermes_gateway"].includes(n)?"Required":"Optional if already configured"}),n==="cursor_cloud"&&(0,t.jsx)("a",{href:"https://cursor.com/dashboard/api?section=user-keys#user-api-keys",target:"_blank",rel:"noopener noreferrer",className:"shrink-0 text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground",children:"get api key"})]})})}),n!=="cursor_cloud"&&(0,t.jsx)("div",{className:b?"sm:col-span-2":void 0,children:(0,t.jsx)(Ss,{label:"Or use an organization secret",children:(0,t.jsx)(LW,{secretId:Ot&&typeof Ot=="object"&&Ot.type==="secret_ref"?Ot.secretId:"",secrets:Ce.data??[],disabled:Ut,onSelect:r(Fe=>{X({type:"secret_ref",secretId:Fe,version:"latest"}),ne(""),vt()},"onSelect")})})}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground sm:col-span-2",children:["New keys are saved as organization secrets when you finish setup.",f&&` Use a ${H}/model ID.`]})]}),n==="hermes_gateway"&&(0,t.jsx)(Ss,{label:"Hermes API base URL",children:(0,t.jsx)(ht,{"aria-label":"Hermes API base URL",value:N,onChange:r(Fe=>{w(Fe.target.value),vt()},"onChange"),placeholder:"https://hermes.example.com"})}),zt&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Kimi API model name",children:(0,t.jsx)(ht,{"aria-label":"Kimi API model name",value:k,onChange:r(Fe=>{S(Fe.target.value),vt()},"onChange"),placeholder:"kimi-for-coding"})}),(0,t.jsx)(Ss,{label:"Kimi API protocol",children:(0,t.jsx)("select",{"aria-label":"Kimi API protocol",className:$C,value:R,onChange:r(Fe=>{T(Fe.target.value),vt()},"onChange"),children:["kimi","anthropic","openai"].map(Fe=>(0,t.jsx)("option",{children:Fe},Fe))})}),(0,t.jsx)(Ss,{label:"Kimi API base URL",hint:"Optional override for your provider endpoint.",children:(0,t.jsx)(ht,{"aria-label":"Kimi API base URL",value:C,onChange:r(Fe=>{I(Fe.target.value),vt()},"onChange"),placeholder:"Provider default"})})]}),n==="cursor_cloud"&&(0,t.jsxs)("div",{className:"grid gap-5 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"GitHub repository",children:(0,t.jsx)(ht,{"aria-label":"GitHub repository",value:te,onChange:r(Fe=>{ae(Fe.target.value),vt()},"onChange"),placeholder:"https://github.com/your-org/repo"})}),(0,t.jsx)(Ss,{label:"Branch",children:(0,t.jsx)(ht,{"aria-label":"Branch",placeholder:"Repository default",value:le,onChange:r(Fe=>{he(Fe.target.value),vt()},"onChange")})})]})]}),!["cursor_cloud","hermes_gateway"].includes(n)&&(0,t.jsxs)("section",{className:"space-y-5",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:"Environment"}),(0,t.jsxs)("select",{"aria-label":"Environment",className:$C,value:O,disabled:Je.forced,onChange:r(Fe=>{K(Fe.target.value),Y(null),vt(),p&&D("connect")},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Bs]}),(ut.data??[]).filter(Fe=>Fe.status==="active"&&(!lt||Fe.driver!=="local")).map(Fe=>(0,t.jsx)("option",{value:Fe.id,children:Yv(Fe)},Fe.id))]})]})]}),(0,t.jsx)(qNe,{state:be,result:Ue,error:dt,disabled:!ft||Ut,onTest:r(()=>{ds()},"onTest")}),dt&&be!=="fail"&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:dt}),(0,t.jsxs)("div",{className:"flex justify-between border-t border-border py-5",children:[p?(0,t.jsxs)(L,{type:"button",variant:"ghost",disabled:Ut,onClick:r(()=>D("connect"),"onClick"),children:[(0,t.jsx)(Tl,{className:"size-4"}),"Connection"]}):(0,t.jsx)("span",{}),(0,t.jsxs)(L,{type:"submit",disabled:!ft||Ut||be==="fail"||!!(p&&!G),children:[ue?"Creating…":"Finish setup",(0,t.jsx)(gs,{className:"size-4"})]})]})]})},A)})})]})]})})}r(iis,"Setup");function ois(){const{setBreadcrumbs:e}=Bn();return(0,m.useEffect)(()=>{e([{label:"Agents",href:"/agents"},{label:"New agent"}])},[e]),(0,t.jsx)(ais,{})}r(ois,"NewAgent");var iM="paperclip:pending-invite-token";function GG(){return typeof window<"u"&&typeof window.localStorage<"u"}r(GG,"canUseStorage");function wpe(e){const s=e.trim();if(!(!s||!GG()))try{window.localStorage.setItem(iM,s)}catch{}}r(wpe,"rememberPendingInviteToken");function WR(e){if(GG())try{const s=window.localStorage.getItem(iM);if(e&&s!==e.trim())return;window.localStorage.removeItem(iM)}catch{}}r(WR,"clearPendingInviteToken");function lis(){if(!GG())return null;try{const e=window.localStorage.getItem(iM)?.trim();return e?`/invite/${e}`:null}catch{return null}}r(lis,"getRememberedInvitePath");var kpe=[" ",".","·","▪","▫","○"],cis=1e3/24,VR=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function Npe(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(Npe,"measureChar");function dis(e){let s=0;for(const n of e)s=Math.max(s,n.length);return{width:s,height:e.length}}r(dis,"spriteSize");function uis(){const e=(0,m.useRef)(null),s=(0,m.useRef)(null);return(0,m.useEffect)(()=>{if(!e.current)return;const n=e.current,a=window.matchMedia("(prefers-reduced-motion: reduce)");let i=document.visibilityState!=="hidden",o=!1,l=0,c=0,d=0,u=0,h=7,p=11,f=new Float32Array(0),x=new Float32Array(0),b=new Float32Array(0),v=new Uint16Array(0),j=[],N="";function w(E){const z=Math.floor(Math.max(0,Math.min(.999,E))*kpe.length);return kpe[z]??" "}r(w,"toGlyph");function k(){const E=Math.max(0,Math.ceil(n.clientWidth/Math.max(1,h))),z=Math.max(0,Math.ceil(n.clientHeight/Math.max(1,p)));if(E===d&&z===u)return;d=E,u=z;const $=d*u;f=new Float32Array($),x=new Float32Array(d),b=new Float32Array(u),v=new Uint16Array($),j=j.filter(q=>q.x>-q.width-2&&q.x<d+2&&q.y>-q.height-2&&q.y<u+2),N=""}r(k,"rebuildGrid");function S(){if(d<=0||u<=0){n.textContent="";return}const E=Array.from({length:u},()=>Array.from({length:d},()=>" "));for(let U=0;U<u;U++)for(let O=0;O<d;O++){const K=(Math.sin(O*.11+U*.04)+Math.cos(U*.08-O*.02))*.18+.22;E[U][O]=w(K)}const z=18,$=13;for(let U=1;U<u-9;U+=$){const O=Math.floor(U/$)%2===0?2:10;for(let K=O;K<d-10;K+=z){const H=VR[(K+U)%VR.length];for(let Z=0;Z<H.length;Z++){const se=H[Z];for(let ne=0;ne<se.length;ne++){const fe=se[ne]??" ";if(fe===" ")continue;const X=U+Z,re=K+ne;X<0||X>=u||re<0||re>=d||(E[X][re]=fe)}}}}const q=E.map(U=>U.join("")).join(`
|
|
774
774
|
`);n.textContent=q,N=q}r(S,"drawStaticFrame");function C(){const E=VR[Math.floor(Math.random()*VR.length)],z=dis(E),$=Math.random();let q=0,U=0,O=0,K=0;$<.68?(q=Math.random()<.5?-z.width-1:d+1,U=Math.random()*Math.max(1,u-z.height),O=q<0?.04+Math.random()*.05:-(.04+Math.random()*.05),K=(Math.random()-.5)*.014):(q=Math.random()*Math.max(1,d-z.width),U=Math.random()<.5?-z.height-1:u+1,O=(Math.random()-.5)*.014,K=U<0?.028+Math.random()*.034:-(.028+Math.random()*.034)),j.push({x:q,y:U,vx:O,vy:K,life:0,maxLife:260+Math.random()*220,drift:(Math.random()-.5)*1.2,sprite:E,width:z.width,height:z.height})}r(C,"spawnClip");function I(E,z){const $=Math.round(E.x),q=Math.round(E.y);for(let U=0;U<E.sprite.length;U++){const O=E.sprite[U],K=q+U;if(!(K<0||K>=u))for(let H=0;H<O.length;H++){const Z=O[H]??" ";if(Z===" ")continue;const se=$+H;if(se<0||se>=d)continue;const ne=K*d+se,fe=Z==="│"||Z==="─"?.8:.92;f[ne]=Math.max(f[ne]??0,z*fe),v[ne]=Z.charCodeAt(0)}}}r(I,"stampClip");function R(E){if(!o||(s.current=requestAnimationFrame(R),E-l<cis||d<=0||u<=0))return;const z=Math.min(2,l===0?1:(E-l)/16.6667);l=E,c+=z;const $=d*u,q=Math.max(3,Math.floor($/2200));for(;j.length<q;)C();for(let O=0;O<f.length;O++)f[O]*=.92;v.fill(0);for(let O=j.length-1;O>=0;O--){const K=j[O];K.life+=z;const H=Math.sin((K.y+K.drift+c*.12)*.09)*.0018,Z=Math.cos((K.x-K.drift-c*.09)*.08)*.0014;if(K.vx=(K.vx+H)*.998,K.vy=(K.vy+Z)*.998,K.x+=K.vx*z,K.y+=K.vy*z,K.life>=K.maxLife||K.x<-K.width-2||K.x>d+2||K.y<-K.height-2||K.y>u+2){j.splice(O,1);continue}const se=K.life/K.maxLife;I(K,se<.12?se/.12:se>.88?(1-se)/.12:1)}for(let O=0;O<d;O++)x[O]=Math.sin(O*.08+c*.06);for(let O=0;O<u;O++)b[O]=Math.cos(O*.1-c*.05);let U="";for(let O=0;O<u;O++){for(let K=0;K<d;K++){const H=O*d+K,Z=v[H];if(Z>0){U+=String.fromCharCode(Z);continue}const se=(x[K]+b[O])*.08+.1,ne=Math.max(f[H]??0,se*.45);U+=w(ne)}O<u-1&&(U+=`
|
|
775
|
-
`)}U!==N&&(n.textContent=U,N=U)}r(R,"step");function T(){const E=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),E&&S();return}if(!i||!E){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(T,"syncLoop");const A=new ResizeObserver(()=>{const E=Npe(n);h=E.w,p=E.h,k(),T()});A.observe(n);const D=r(()=>{i=document.visibilityState!=="hidden",T()},"onVisibilityChange");document.addEventListener("visibilitychange",D);const M=r(()=>{T()},"onMotionChange");a.addEventListener("change",M);const B=Npe(n);return h=B.w,p=B.h,k(),T(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),A.disconnect(),document.removeEventListener("visibilitychange",D),a.removeEventListener("change",M)}},[]),(0,t.jsx)("pre",{ref:e,className:"w-full h-full m-0 p-0 overflow-hidden text-muted-foreground/60 select-none leading-none",style:{fontSize:"var(--text-micro)",fontFamily:"monospace"},"aria-hidden":"true"})}r(uis,"AsciiArtAnimation");function mis({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(mis,"PaperclipLockup");function his(){const e=Pt(),s=Mn(),[n]=fi(),[a,i]=(0,m.useState)("sign_in"),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),x="auth-error",b=(0,m.useMemo)(()=>ACe(n.get("next")||lis()||"/"),[n]),v=ee({queryKey:P.health,queryFn:r(()=>du.get(),"queryFn"),retry:!1}),{data:j,isLoading:N,error:w}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{j&&(kV(),s(b,{replace:!0}))},[j,s,b]);const k=je({mutationFn:r(async()=>{if(a==="sign_in"){await Oa.signInEmail({email:c.trim(),password:u});return}await Oa.signUpEmail({name:o.trim(),email:c.trim(),password:u})},"mutationFn"),onSuccess:r(async()=>{f(null),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.resetQueries({queryKey:P.companies.all}),s(b,{replace:!0})},"onSuccess"),onError:r(C=>{f(C instanceof Error?C.message:"Authentication failed")},"onError")}),S=c.trim().length>0&&u.trim().length>0&&(a==="sign_in"||o.trim().length>0&&u.trim().length>=8);return v.isLoading||N||j?(0,t.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,t.jsx)($m,{className:"min-h-0"})}):v.error||w?(0,t.jsx)("p",{role:"alert",className:"p-6 text-sm text-destructive",children:"Unable to check sign-in. Refresh and try again."}):v.data?.cloud?(0,t.jsx)(NV,{cloud:v.data.cloud,returnTo:b}):(0,t.jsxs)("div",{className:"fixed inset-0 flex bg-background",children:[(0,t.jsx)("div",{className:"absolute top-4 right-4 z-10",children:(0,t.jsx)(yk,{})}),(0,t.jsx)("div",{className:"w-full md:w-1/2 flex flex-col overflow-y-auto",children:(0,t.jsxs)("div",{className:"w-full max-w-md mx-auto my-auto px-8 py-12",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(mis,{className:"h-5 w-auto"})}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:a==="sign_in"?"Sign in to Paperclip":"Create your Paperclip account"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:a==="sign_in"?"Use your email and password to access this instance.":"Create an account for this instance. Email confirmation is not required in v1."}),(0,t.jsxs)("form",{className:"mt-6 space-y-4",method:"post",action:a==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(C=>{if(C.preventDefault(),!k.isPending){if(!S){f("Please fill in all required fields.");return}k.mutate()}},"onSubmit"),children:[a==="sign_up"&&(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"name",className:"text-xs text-muted-foreground mb-1 block",children:"Name"}),(0,t.jsx)("input",{id:"name",name:"name",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",value:o,onChange:r(C=>l(C.target.value),"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:!0})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"email",className:"text-xs text-muted-foreground mb-1 block",children:"Email"}),(0,t.jsx)("input",{id:"email",name:"email",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"email",value:c,onChange:r(C=>d(C.target.value),"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:a==="sign_in"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"password",className:"text-xs text-muted-foreground mb-1 block",children:"Password"}),(0,t.jsx)("input",{id:"password",name:"password",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"password",value:u,onChange:r(C=>h(C.target.value),"onChange"),autoComplete:a==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0})]}),p&&(0,t.jsx)("p",{id:x,role:"alert",className:"text-xs text-destructive",children:p}),(0,t.jsx)(L,{type:"submit",disabled:k.isPending,"aria-disabled":!S||k.isPending,className:`w-full ${!S&&!k.isPending?"opacity-50":""}`,children:k.isPending?"Working…":a==="sign_in"?"Sign In":"Create Account"})]}),(0,t.jsxs)("div",{className:"mt-5 text-sm text-muted-foreground",children:[a==="sign_in"?"Need an account?":"Already have an account?"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2",onClick:r(()=>{f(null),i(a==="sign_in"?"sign_up":"sign_in")},"onClick"),children:a==="sign_in"?"Create one":"Sign in"})]})]})}),(0,t.jsx)("div",{className:"hidden md:block w-1/2 overflow-hidden",children:(0,t.jsx)(uis,{})})]})}r(his,"AuthPage");function pis(){const e=Pt(),s=va(),[n]=fi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),c=ee({queryKey:["board-claim",a,i],queryFn:r(()=>pr.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>pr.claimBoard(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.invalidateQueries({queryKey:P.companies.all}),await e.invalidateQueries({queryKey:P.companies.stats}),await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid board claim URL."});if(c.isLoading||l.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading claim challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Claim challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const u=c.data;return u?u.status==="claimed"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate organization ownership access from local trusted mode."}),d.error&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to claim board ownership"}),(0,t.jsx)(L,{className:"mt-5",onClick:r(()=>d.mutate(),"onClick"),disabled:d.isPending,children:d.isPending?"Claiming…":"Claim ownership"})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Claim challenge unavailable."})}r(pis,"BoardClaimPage");function fis(){const e=Pt(),s=va(),[n]=fi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),c=ee({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>pr.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>pr.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await c.refetch()},"onSuccess")}),u=je({mutationFn:r(()=>pr.cancelCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid CLI auth URL."});if(l.isLoading||c.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading CLI auth challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"CLI auth challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const h=c.data;return h?h.status==="approved"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"CLI access approved"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The Paperclip CLI can now finish authentication on the requesting machine."}),(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Command: ",(0,t.jsx)("span",{className:"font-mono text-foreground",children:h.command})]})]})}):h.status==="cancelled"||h.status==="expired"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h.status==="expired"?"CLI auth challenge expired":"CLI auth challenge cancelled"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Start the CLI auth flow again from your terminal to generate a new approval request."})]})}):h.requiresSignIn||!l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Approve Paperclip CLI access"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local Paperclip CLI process is requesting board access to this instance."}),(0,t.jsxs)("div",{className:"mt-5 space-y-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Command"}),(0,t.jsx)("div",{className:"font-mono text-foreground",children:h.command})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Client"}),(0,t.jsx)("div",{className:"text-foreground",children:h.clientName??"paperclip-pro cli"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested access"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),h.requestedCompanyName&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested organization"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedCompanyName})]})]}),(d.error||u.error)&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:(d.error??u.error)instanceof Error?(d.error??u.error).message:"Failed to update CLI auth challenge"}),!h.canApprove&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),(0,t.jsxs)("div",{className:"mt-5 flex gap-3",children:[(0,t.jsx)(L,{onClick:r(()=>d.mutate(),"onClick"),disabled:!h.canApprove||d.isPending||u.isPending,children:d.isPending?"Approving...":"Approve CLI access"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>u.mutate(),"onClick"),disabled:d.isPending||u.isPending,children:u.isPending?"Cancelling...":"Cancel"})]})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"CLI auth challenge unavailable."})}r(fis,"CliAuthPage");var xis=i$e.filter(e=>e!=="paperclip_runner"),Spe=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function gis(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(gis,"readNestedString");var Sw="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",Cpe="border border-zinc-800 bg-zinc-950/95 p-6",_pe="flex-1 border px-3 py-2 text-sm transition-colors";function bis(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(bis,"formatHumanRole");function E4e(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(E4e,"getAuthErrorCode");function vis(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(vis,"getAuthErrorMessage");function yis(e,s,n){const a=E4e(e),i=vis(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(yis,"mapInviteAuthFeedback");function Ipe(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(Ipe,"isBootstrapAcceptancePayload");function jis(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(jis,"isApprovedHumanJoinPayload");function Y8({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(tS,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(Y8,"InviteCompanyLogo");function Ape({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)(Y8,{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(Ape,"AwaitingJoinApprovalPanel");function wis(){const e=Pt(),s=Mn(),{setSelectedCompanyId:n}=ps(),a=(va().token??"").trim(),[i,o]=(0,m.useState)("sign_up"),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(""),[b,v]=(0,m.useState)("claude_local"),[j,N]=(0,m.useState)(""),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),[I,R]=(0,m.useState)(null),[T,A]=(0,m.useState)(!1),D="invite-auth-error",M=ee({queryKey:P.health,queryFn:r(()=>du.get(),"queryFn"),retry:!1}),B=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),E=ee({queryKey:P.access.invite(a),queryFn:r(()=>pr.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),z=r7({enabled:!!B.data&&!!E.data?.companyId,staleTime:0}),$=M.data?.deploymentMode!=="local_trusted"?z.isFetchedAfterMount:!0,q=$?z.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&wpe(a)},[a]),(0,m.useEffect)(()=>{A(!1)},[a]),(0,m.useEffect)(()=>{if(!$)return;const ge=z.data?.companies;!ge||!E.data?.companyId||ge.some(me=>me.id===E.data.companyId)&&WR(a)},[z.data,E.data,$,a]);const U=E.data,O=!!B.data&&!!U?.companyId&&!$,K=!!U?.companyId&&q.some(ge=>ge.id===U?.companyId),H=U?.companyName?.trim()||"this Paperclip company",Z=U?.companyLogoUrl?.trim()||null,se=U?.invitedByUserName?.trim()||null,ne=U?.inviteMessage?.trim()||null,fe=bis(U?.humanRole),X=U?.joinRequestStatus??null,re=U?.joinRequestType??null,oe=re==="human"&&(X==="pending_approval"||X==="approved"),G=M.data?.deploymentMode==="authenticated"&&!B.data&&U?.allowedJoinTypes!=="agent",Y=U?.inviteType!=="bootstrap_ceo"&&U?.allowedJoinTypes==="agent",Q=!!B.data&&!Y&&U?.inviteType!=="bootstrap_ceo"&&(!X||oe)&&!O&&!K&&!w&&S===null,te=B.data?.user.name?.trim()||B.data?.user.email?.trim()||"this account",ae=d.trim().length>0&&h.trim().length>0&&(i==="sign_in"||l.trim().length>0&&h.trim().length>=8),le=je({mutationFn:r(async()=>{if(!U)throw new Error("Invite not found");if(O)throw new Error("Checking your organization access. Try again in a moment.");if(K)throw new Error("This account already belongs to the organization.");return U.inviteType==="bootstrap_ceo"||U.allowedJoinTypes!=="agent"?pr.acceptInvite(a,{requestType:"human"}):pr.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:b,capabilities:j.trim()||null})},"mutationFn"),onSuccess:r(async ge=>{C(null),WR(a);const me=Ipe(ge);k({kind:me?"bootstrap":"join",payload:ge}),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.access.currentBoardAccess}),await e.invalidateQueries({queryKey:P.companies.all}),U?.companyId&&jis(ge,Y)&&(n(U.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(ge=>{C(ge instanceof Error?ge.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Q||T||le.isPending||(A(!0),C(null),le.mutate())},[le,T,Q]);const he=je({mutationFn:r(async()=>{if(i==="sign_in"){await Oa.signInEmail({email:d.trim(),password:h});return}await Oa.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),wpe(a),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.invalidateQueries({queryKey:P.access.currentBoardAccess});const{companies:ge}=await w$e(e);if(U?.companyId&&ge.some(me=>me.id===U.companyId)){WR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!U||U.inviteType!=="bootstrap_ceo"))try{Ipe(await le.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ge=>{const me=yis(ge,i,d);E4e(ge)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(me)},"onError")}),ce=(0,m.useMemo)(()=>U?K?"Open organization":U.inviteType==="bootstrap_ceo"?"Accept invite":Y?"Submit request":B.data?"Accept invite":"Continue":"Continue",[U,K,B.data,Y]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(E.isLoading||M.isLoading||B.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(O)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Checking your access..."});if(E.error||!U)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This invite may be expired, revoked, or already used."})]})});if(X==="approved"&&re==="human"&&K)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Opening organization..."});if(X==="pending_approval"&&!oe)return(0,t.jsx)(Ape,{companyDisplayName:H,companyLogoUrl:Z,invitedByUserName:se});if(X&&!oe)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:X==="rejected"?"This join request was not approved.":"This invite has already been used."})]})});if(w?.kind==="bootstrap")return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Bootstrap complete"}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(L,{asChild:!0,className:"rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ge=w.payload,me=typeof ge.claimSecret=="string"?ge.claimSecret:null,ie=typeof ge.claimApiKeyPath=="string"?ge.claimApiKeyPath:null,ue=gis(ge.onboarding,["textInstructions","url"]);return!Y&&ge.status==="approved"?(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(Y8,{companyDisplayName:H,companyLogoUrl:Z,className:"h-12 w-12 border border-zinc-800 rounded-none"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"You joined the organization"})]}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(L,{asChild:!0,className:"w-full rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(Ape,{companyDisplayName:H,companyLogoUrl:Z,invitedByUserName:se,claimSecret:me,claimApiKeyPath:ie,onboardingTextUrl:ue})}return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsx)("div",{className:"mx-auto max-w-5xl",children:(0,t.jsxs)("div",{className:"grid gap-6 lg:grid-cols-(--gtc-36)",children:[(0,t.jsxs)("section",{className:`${Cpe} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(Y8,{companyDisplayName:H,companyLogoUrl:Z,className:"h-16 w-16 rounded-none border border-zinc-800"}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("p",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"You've been invited to join Paperclip"}),(0,t.jsx)("h1",{className:"mt-2 text-2xl font-semibold",children:U.inviteType==="bootstrap_ceo"?"Set up Paperclip":`Join ${H}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:Y?"Review the invite details, then submit the agent information below to start the join request.":G?"Create your Paperclip account first. If you already have one, switch to sign in and continue the invite with the same email.":"Your account is ready. Review the invite details, then accept it to continue."})]})]}),(0,t.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Organization"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:H})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invited by"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:se??"Paperclip board"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Requested access"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:Y?"Agent join request":fe??"Organization access"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invite expires"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:Id(U.expiresAt)})]})]}),ne?(0,t.jsxs)("div",{className:"border border-amber-500/40 bg-amber-500/10 p-4",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-amber-200/80",children:"Message from inviter"}),(0,t.jsx)("p",{className:"mt-2 text-sm leading-6 text-amber-50",children:ne})]}):null,B.data?(0,t.jsxs)("div",{className:"border border-emerald-500/40 bg-emerald-500/10 p-4 text-sm text-emerald-50",children:["Signed in as ",(0,t.jsx)("span",{className:"font-medium",children:te}),"."]}):null]}),(0,t.jsx)("section",{className:`${Cpe} h-fit`,children:Y?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Submit agent details"}),(0,t.jsxs)("p",{className:"mt-1 text-sm text-zinc-400",children:["This invite will create an approval request for a new agent in ",H,"."]})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Agent name"}),(0,t.jsx)("input",{className:Sw,value:f,onChange:r(ge=>x(ge.target.value),"onChange")})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Adapter type"}),(0,t.jsx)("select",{className:Sw,value:b,onChange:r(ge=>v(ge.target.value),"onChange"),children:xis.map(ge=>(0,t.jsxs)("option",{value:ge,disabled:!Spe.has(ge),children:[Bf(ge),Spe.has(ge)?"":" (Coming soon)"]},ge))})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Capabilities"}),(0,t.jsx)("textarea",{className:Sw,rows:4,value:j,onChange:r(ge=>N(ge.target.value),"onChange")})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,(0,t.jsx)(L,{className:"w-full rounded-none",disabled:le.isPending||f.trim().length===0,onClick:r(()=>le.mutate(),"onClick"),children:le.isPending?"Working...":ce})]}):G?(0,t.jsxs)("div",{className:"space-y-5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:i==="sign_up"?"Create your account":"Sign in to continue"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:i==="sign_up"?`Start with a Paperclip account. After that, you'll come right back here to accept the invite for ${H}.`:"Use the Paperclip account that already matches this invite. If you do not have one yet, switch back to create account."})]}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)("button",{type:"button",className:`${_pe} ${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:`${_pe} ${i==="sign_in"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{R(null),o("sign_in")},"onClick"),children:"I already have an account"})]}),(0,t.jsxs)("form",{className:"space-y-4",method:"post",action:i==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(ge=>{if(ge.preventDefault(),!he.isPending){if(!ae){R({tone:"error",message:"Please fill in all required fields."});return}he.mutate()}},"onSubmit"),"data-testid":"invite-inline-auth",children:[i==="sign_up"?(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-name",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Name"}),(0,t.jsx)("input",{id:"invite-name",name:"name",className:Sw,value:l,onChange:r(ge=>{c(ge.target.value),R(null)},"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D:void 0,autoFocus:!0})]}):null,(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-email",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Email"}),(0,t.jsx)("input",{id:"invite-email",name:"email",type:"email",className:Sw,value:d,onChange:r(ge=>{u(ge.target.value),R(null)},"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D:void 0,autoFocus:i==="sign_in"})]}),(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-password",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Password"}),(0,t.jsx)("input",{id:"invite-password",name:"password",type:"password",className:Sw,value:h,onChange:r(ge=>{p(ge.target.value),R(null)},"onChange"),autoComplete:i==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D:void 0})]}),I?(0,t.jsx)("p",{id:D,role:"alert",className:`text-xs ${I.tone==="info"?"text-amber-300":"text-red-400"}`,children:I.message}):null,(0,t.jsx)(L,{type:"submit",className:"w-full rounded-none",disabled:he.isPending,"aria-disabled":!ae||he.isPending,children:he.isPending?"Working...":i==="sign_in"?"Sign in and continue":"Create account and continue"})]}),(0,t.jsx)("p",{className:"text-xs leading-5 text-zinc-500",children:i==="sign_up"?"Already signed up before? Use the existing-account option instead so the invite lands on the right Paperclip user.":"No account yet? Switch back to create account so you can accept the invite with a new login."})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:K?"Already in this organization":Q?"Completing organization access":U.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Q?`Granting your access to ${H}.`:K?`This account already belongs to ${H}.`:`This will ${U.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${H}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Q?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:le.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)(L,{className:"w-full rounded-none",disabled:le.isPending,onClick:r(()=>{if(K&&U.companyId){WR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}le.mutate()},"onClick"),children:le.isPending?"Working...":ce})]})})]})})})}r(wis,"InviteLandingPage");var kis=15e3,Nis={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Sis(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Sis,"useNoIndexMeta");function J8(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(J8,"sharePath");var Cis=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function _is(e,s){const n=Cis.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(_is,"publicShareImageSrc");function OC({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(OC,"Section");function X8({actor:e}){return(0,t.jsx)(Hl,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(X8,"ActorIdentity");function Z8({value:e}){return(0,t.jsx)("time",{dateTime:e,title:Rr(e),className:"text-xs text-muted-foreground",children:cr(e)})}r(Z8,"Timestamp");function Iis({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(Iis,"ActiveRunPill");function P4e({attachments:e}){return(0,t.jsx)(D9,{children:e.map(s=>{const n=owe({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=L9(s.byteSize);return(0,t.jsxs)(T9,{size:"sm",children:[(0,t.jsx)(R9,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(E9,{children:[(0,t.jsx)(P9,{className:"max-w-48",children:s.filename}),(0,t.jsx)(M9,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(nwe,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(P4e,"AttachmentList");function Ais({related:e,token:s,isSharedRoot:n}){const a=e.identifier?`${e.identifier} · ${e.title}`:e.title,i=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Xi,{status:e.status,size:"sm"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:a})]});return(0,t.jsxs)("li",{className:"flex items-center gap-2 text-sm",children:[(0,t.jsx)("span",{className:"w-20 shrink-0 text-xs text-muted-foreground",children:Nis[e.relation]}),e.navigable?(0,t.jsx)(ld,{to:n?J8(s,e.id):J8(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(Ais,"RelatedIssueRow");function Tis({comment:e,resolveImageSrc:s}){return e.kind==="redacted"?(0,t.jsxs)("li",{"data-testid":"public-share-redacted-comment",className:"flex flex-wrap items-center gap-2 rounded-lg border border-dashed border-border px-3 py-2",children:[(0,t.jsx)(X8,{actor:e.author}),(0,t.jsx)(Z8,{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)(X8,{actor:e.author}),(0,t.jsx)(Z8,{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)(P4e,{attachments:e.attachments}):null]})}r(Tis,"TimelineEntry");function Ris({document:e,resolveImageSrc:s}){return(0,t.jsxs)("details",{className:"group rounded-lg border border-border bg-card",children:[(0,t.jsxs)("summary",{className:"flex cursor-pointer items-center gap-2 px-3 py-2 text-sm",children:[(0,t.jsx)(Ha,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.title??e.key}),(0,t.jsx)(Z8,{value:e.updatedAt})]}),(0,t.jsxs)("div",{className:"space-y-3 border-t border-border px-3 py-3",children:[(0,t.jsxs)("a",{href:e.pdfUrl,download:!0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(po,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(Sn,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(Ris,"DocumentCard");function Eis({product:e}){return(0,t.jsxs)("li",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border border-border bg-card px-3 py-2 text-sm",children:[(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.title}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:[e.type.replace(/_/g," ")," · ",e.status.replace(/_/g," ")]}),e.url?(0,t.jsxs)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Vn,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Open"]}):null,e.downloadUrl?(0,t.jsxs)("a",{href:e.downloadUrl,download:!0,rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(po,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(Eis,"WorkProductRow");function Tpe({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(Tpe,"CenteredNotice");function Pis({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>_is(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)(tS,{companyName:n.name,logoUrl:n.logoUrl,logoFit:"contain",className:"h-8 w-8 shrink-0 rounded-md"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-sm font-medium",children:n.name}),(0,t.jsx)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:"Read-only view"})]})}),(0,t.jsxs)("main",{className:"mx-auto max-w-3xl space-y-8 px-4 py-5",children:[e.isSharedRoot?null:(0,t.jsxs)(ld,{to:J8(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Tl,{className:"h-4 w-4","aria-hidden":!0}),"Back to main task"]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground",children:[a.identifier?(0,t.jsx)("span",{children:a.identifier}):null,a.projectName?(0,t.jsx)("span",{children:a.projectName}):null]}),(0,t.jsx)("h1",{className:"break-words text-xl font-semibold",children:a.title}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsx)(sp,{status:a.status}),(0,t.jsx)(Xfe,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(X8,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(Iis,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",Rr(a.createdAt)," · Updated ",cr(a.updatedAt),a.completedAt?` · Completed ${Rr(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(Sn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)(OC,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(Ais,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(OC,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(Ris,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(OC,{title:"Attachments",children:(0,t.jsx)(P4e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(OC,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(Eis,{product:o},o.id))})}):null,(0,t.jsx)(OC,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(Tis,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(Pis,"PublicIssueShareContent");function Rpe(){const{token:e="",issueId:s}=va();Sis();const n=Sze.test(e),a=ee({queryKey:P.publicShare.view(e,s??null),queryFn:r(()=>s?Dk.getPublicShareIssue(e,s):Dk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?kis:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Tpe,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(Pis,{view:a.data,token:e}):a.isError?(0,t.jsx)(Tpe,{title:"Couldn't load this page",body:"Check your connection and try again.",action:(0,t.jsx)(L,{variant:"outline",size:"sm",className:"mt-2",onClick:r(()=>{a.refetch()},"onClick"),children:"Try again"})}):(0,t.jsx)("div",{className:"h-dvh overflow-y-auto px-4 py-6","aria-busy":"true",children:(0,t.jsxs)("div",{className:"mx-auto max-w-3xl space-y-4",children:[(0,t.jsx)(vn,{className:"h-6 w-1/2"}),(0,t.jsx)(vn,{className:"h-4 w-1/3"}),(0,t.jsx)(vn,{className:"h-24 w-full"})]})})}r(Rpe,"PublicIssueSharePage");function Mis(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Bn(),{pushToast:a}=xi(),i=Pt(),[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=ee({queryKey:P.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>pr.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=je({mutationFn:r(f=>pr.approveJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.joinRequests(s,`${o}:${c}`)}),await i.invalidateQueries({queryKey:P.access.companyMembers(s)}),await i.invalidateQueries({queryKey:P.access.companyUserDirectory(s)}),a({title:"Join request approved",tone:"success"})},"onSuccess")}),p=je({mutationFn:r(f=>pr.rejectJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.joinRequests(s,`${o}:${c}`)}),a({title:"Join request rejected",tone:"success"})},"onSuccess")});if(!s)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Select an organization to review join requests."});if(u.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading join requests…"});if(u.error){const f=u.error instanceof dn&&u.error.status===403?"You do not have permission to review join requests for this organization.":u.error instanceof Error?u.error.message:"Failed to load join requests.";return(0,t.jsx)("div",{className:"text-sm text-destructive",children:f})}return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Jqe,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Join Request Queue"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Review human and agent join requests outside the mixed inbox feed. This queue uses the same approval mutations as the inline inbox cards."})]}),(0,t.jsxs)(rn,{className:"flex-row flex-wrap gap-3 p-4",children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Status"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(f=>l(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"pending_approval",children:"Pending approval"}),(0,t.jsx)("option",{value:"approved",children:"Approved"}),(0,t.jsx)("option",{value:"rejected",children:"Rejected"})]})]}),(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Request type"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:c,onChange:r(f=>d(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"all",children:"All"}),(0,t.jsx)("option",{value:"human",children:"Human"}),(0,t.jsx)("option",{value:"agent",children:"Agent"})]})]})]}),(0,t.jsx)("div",{className:"space-y-4",children:(u.data??[]).length===0?(0,t.jsx)("div",{className:"rounded-xl border border-dashed border-border px-4 py-8 text-sm text-muted-foreground",children:"No join requests match the current filters."}):u.data.map(f=>(0,t.jsxs)(rn,{className:"block p-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(ct,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(ct,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(ct,{variant:"outline",children:f.adapterType}):null]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-base font-medium",children:f.requestType==="human"?f.requesterUser?.name||f.requestEmailSnapshot||f.requestingUserId||"Unknown human requester":f.agentName||"Unknown agent requester"}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:f.requestType==="human"?f.requesterUser?.email||f.requestEmailSnapshot||f.requestingUserId:f.capabilities||f.requestIp})]})]}),f.status==="pending_approval"?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>p.mutate(f.id),"onClick"),disabled:p.isPending,children:"Reject"}),(0,t.jsx)(L,{onClick:r(()=>h.mutate(f.id),"onClick"),disabled:h.isPending,children:"Approve"})]}):null]}),(0,t.jsxs)("div",{className:"mt-4 grid gap-3 text-sm text-muted-foreground md:grid-cols-2",children:[(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Invite context"}),(0,t.jsx)("div",{className:"mt-2",children:f.invite?`${f.invite.allowedJoinTypes} join invite${f.invite.humanRole?` • default role ${f.invite.humanRole}`:""}`:"Invite metadata unavailable"}),f.invite?.inviteMessage?(0,t.jsx)("div",{className:"mt-2 text-foreground",children:f.invite.inviteMessage}):null]}),(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Request details"}),(0,t.jsxs)("div",{className:"mt-2",children:["Submitted ",new Date(f.createdAt).toLocaleString()]}),(0,t.jsxs)("div",{children:["Source IP ",f.requestIp]}),f.requestType==="agent"&&f.capabilities?(0,t.jsx)("div",{children:f.capabilities}):null]})]})]},f.id))})]})}r(Mis,"JoinRequestQueue");var Dis=(0,m.lazy)(()=>Jc(()=>import("./CompanyExport-BlNlzmA0.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]))),Lis=(0,m.lazy)(()=>Jc(()=>import("./Agents.production-DSa6Vl3y.js").then(e=>({default:e.Agents})),__vite__mapDeps([25,5,7,9,8,10,11,12,13,26,27,28,29,30,31,32,33,23,24]))),$is=(0,m.lazy)(()=>Jc(()=>import("./Routines.production-Dt1_0n4r.js").then(e=>({default:e.Routines})),__vite__mapDeps([34,5,7,8,9,10,11,12,13,35,14,36,37,28,26,38,39,40,20,41,42,15,16,17,18,29,43,44,30,45,46,22,31,47,33,48,49,50,51,23,24,27]))),Epe=(0,m.lazy)(()=>Jc(()=>import("./RoutineDetail.production-CpuZ5sxp.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([52,5,7,8,9,10,11,12,13,35,14,36,37,28,26,38,39,40,20,41,42,15,16,17,18,29,43,44,30,45,46,22,31,47,33,48,49,50,51,23,24,53]))),Ois=(0,m.lazy)(()=>Jc(()=>import("./CompanySkills.production-Wzc95Tf4.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([54,5,7,8,9,10,11,12,13,14,36,37,28,26,38,39,40,20,41,27,15,16,17,18,55,53,31,44,21,19,56,47,48,50,23,24]))),Fis=(0,m.lazy)(()=>Jc(()=>import("./CompanyActivity.production-CXZY_w67.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([57,5,7,8,9,10,11,12,13,26,27,28,43,37,20,44,48,49,51]))),Bis=(0,m.lazy)(()=>Jc(()=>import("./Costs.production-Dgazqe6X.js").then(e=>({default:e.Costs})),__vite__mapDeps([58,5,7,27,28,13,12,44,41,50,26,51,23,24]))),zis=(0,m.lazy)(()=>Jc(()=>import("./OrgChart.production-BEhpdEr9.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([59,5,7,8,9,10,11,12,13,26,45,46,51,23,24])));function h0({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)($m,{}),children:e})}r(h0,"ProductionSurface");function qis(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(kn,{to:"dashboard",replace:!0})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(ISt,{})}),(0,t.jsx)(nt,{path:"dashboard/live",element:(0,t.jsx)(ASt,{})}),(0,t.jsx)(nt,{path:"timeline",element:e?(0,t.jsx)(Yp,{to:"/activity/timeline"}):(0,t.jsx)(G2e,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(L4e,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(fCt,{})}),(0,t.jsx)(nt,{path:"company/settings",element:(0,t.jsx)(T7t,{})}),(0,t.jsx)(nt,{path:"company/settings/environments",element:(0,t.jsx)(kn,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(kn,{to:"/company/export",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.members"}),children:[(0,t.jsx)(nt,{path:"company/settings/members",element:(0,t.jsx)(XHt,{})}),(0,t.jsx)(nt,{path:"company/settings/access",element:(0,t.jsx)(ZHt,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.invites"}),children:(0,t.jsx)(nt,{path:"company/settings/invites",element:(0,t.jsx)(kn,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.export"}),children:(0,t.jsx)(nt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)($m,{}),children:(0,t.jsx)(Dis,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(But,{}),children:(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.import"}),children:(0,t.jsx)(nt,{path:"company/import",element:(0,t.jsx)(Mrs,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.secrets"}),children:(0,t.jsx)(nt,{path:"company/settings/secrets",element:(0,t.jsx)(Ans,{})})}),(0,t.jsx)(nt,{path:"company/settings/tools",element:(0,t.jsx)(Dpe,{})}),(0,t.jsx)(nt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(Dpe,{})}),(0,t.jsx)(nt,{path:"tools",element:(0,t.jsx)(Lpe,{})}),(0,t.jsx)(nt,{path:"tools/:tab",element:(0,t.jsx)(Lpe,{})}),(0,t.jsx)(nt,{path:"apps",element:(0,t.jsx)(VQt,{})}),(0,t.jsx)(nt,{path:"apps/browse",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connections",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/byo",element:(0,t.jsx)(rMe,{byoOnly:!0})}),(0,t.jsx)(nt,{path:"apps/vercel-connect",element:(0,t.jsx)(Ppe,{credentialSource:"vercel_connect"})}),(0,t.jsx)(nt,{path:"apps/connect",element:(0,t.jsx)(Ppe,{})}),(0,t.jsx)(nt,{path:"apps/chat/connect",element:(0,t.jsx)(VB,{children:(0,t.jsx)(aJt,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(VB,{children:(0,t.jsx)(kn,{to:"settings",replace:!0})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(VB,{children:(0,t.jsx)(hXt,{})})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/review",element:(0,t.jsx)(jXt,{})}),(0,t.jsx)(nt,{path:"apps/attention",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways",element:(0,t.jsx)(Lme,{})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(kn,{to:"overview",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(JXt,{})}),(0,t.jsx)(nt,{path:"apps/advanced",element:(0,t.jsx)(ime,{})}),(0,t.jsx)(nt,{path:"apps/advanced/gateways",element:(0,t.jsx)(Lme,{})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(ume,{mode:"new"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(ume,{mode:"edit"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(bQt,{})}),(0,t.jsx)(nt,{path:"apps/advanced/audit",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/:tab",element:(0,t.jsx)(ime,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId",element:(0,t.jsx)(Pme,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(Pme,{})}),(0,t.jsx)(nt,{path:"apps/:connectionId",element:(0,t.jsx)(kn,{to:"permissions",replace:!0})}),(0,t.jsx)(nt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(vYt,{})}),(0,t.jsx)(nt,{path:"company/settings/instance",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.profile"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/profile",element:(0,t.jsx)(Bas,{})})}),(0,t.jsx)(nt,{path:"company/settings/instance/general",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.environments"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/environments",element:(0,t.jsx)(PB,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(PB,{mode:"create"})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(PB,{mode:"edit"})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.access"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/access",element:(0,t.jsx)(Eas,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.experimental"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(Ras,{})})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(qas,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(Uas,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.adapters"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(bpe,{})})}),(0,t.jsx)(nt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(WHt,{})}),(0,t.jsx)(nt,{path:"skills/sources",element:(0,t.jsx)(lhe,{})}),(0,t.jsx)(nt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(lhe,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(az,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(az,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(az,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M4e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:e?(0,t.jsx)(mes,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Ois,{})})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"plugins/:pluginId",element:(0,t.jsx)(vpe,{})}),(0,t.jsx)(nt,{path:"org",element:e?(0,t.jsx)(kn,{to:"/agents/all",replace:!0}):(0,t.jsx)(h0,{children:(0,t.jsx)(zis,{})})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(kn,{to:"/agents/all",replace:!0})}),mH.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:e?(0,t.jsx)(qCt,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Lis,{})})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(ois,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(lF,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(lF,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(lF,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(sAt,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(mO,{}),children:(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(YTt,{})})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(mO,{}),children:(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(ZTt,{})})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(wEt,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"search",element:(0,t.jsx)(qEt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(oh,{view:"all"})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(oh,{view:"active"})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(oh,{view:"backlog"})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(oh,{view:"done"})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(oh,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})})]}),(0,t.jsx)(nt,{path:"chats",element:(0,t.jsx)(B4t,{})}),(0,t.jsx)(nt,{path:"chats/:agentRef",element:(0,t.jsx)(q4t,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(D4t,{})}),null,(0,t.jsx)(nt,{path:"routines",element:e?(0,t.jsx)(jDt,{}):(0,t.jsx)(h0,{children:(0,t.jsx)($is,{})})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(rne,{children:(0,t.jsx)(imt,{})})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(rne,{children:(0,t.jsx)(Upt,{})})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(Fut,{children:(0,t.jsx)(Xqt,{})})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(ane,{children:(0,t.jsx)(rce,{})})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(ane,{children:(0,t.jsx)(rce,{})})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)($pe,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)($pe,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(s0,{children:(0,t.jsx)(F$t,{})})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(s0,{children:(0,t.jsx)(z$t,{})})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(s0,{children:(0,t.jsx)(QF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(s0,{children:(0,t.jsx)(QF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(s0,{children:(0,t.jsx)(QF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(s0,{children:(0,t.jsx)(MOt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(s0,{children:(0,t.jsx)(a$t,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(s0,{children:(0,t.jsx)(s$t,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:e?(0,t.jsx)(ide,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Epe,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(ide,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Epe,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(mO,{}),children:(0,t.jsxs)(nt,{element:(0,t.jsx)(qut,{}),children:[(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(vw,{})})]})}),(0,t.jsx)(nt,{path:"goals",element:(0,t.jsx)(GUt,{})}),(0,t.jsx)(nt,{path:"goals/:goalId",element:(0,t.jsx)(aKt,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(dde,{})}),(0,t.jsx)(nt,{path:"approvals",element:(0,t.jsx)(kn,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(nt,{path:"approvals/pending",element:(0,t.jsx)(mde,{})}),(0,t.jsx)(nt,{path:"approvals/all",element:(0,t.jsx)(mde,{})}),(0,t.jsx)(nt,{path:"approvals/:approvalId",element:(0,t.jsx)(iKt,{})}),(0,t.jsx)(nt,{path:"activity",element:e?(0,t.jsx)(HKt,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Fis,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"activity/runs",element:(0,t.jsx)(i1,{section:"runs"})}),(0,t.jsx)(nt,{path:"activity/costs",element:(0,t.jsx)(i1,{section:"costs"})}),(0,t.jsx)(nt,{path:"activity/budgets",element:(0,t.jsx)(i1,{section:"budgets"})}),(0,t.jsx)(nt,{path:"activity/timeline",element:(0,t.jsx)(i1,{section:"timeline"})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(Yp,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(nt,{path:"audit/activity",element:(0,t.jsx)(Yp,{to:"/activity"})}),(0,t.jsx)(nt,{path:"audit/runs",element:(0,t.jsx)(Yp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"audit/costs",element:(0,t.jsx)(Yp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"audit/budgets",element:(0,t.jsx)(Yp,{to:"/activity/budgets"})}),(0,t.jsx)(nt,{path:"audit/timeline",element:(0,t.jsx)(Yp,{to:"/activity/timeline"})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(Yp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(Yp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(Yp,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(h0,{children:(0,t.jsx)(Bis,{})})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(kn,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(nt,{element:(0,t.jsx)(act,{}),children:[(0,t.jsx)(nt,{path:"board-chat",element:(0,t.jsx)(c7t,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(dde,{})})]}),null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(M8t,{})}),(0,t.jsx)(nt,{path:"decisions/queues/:key",element:(0,t.jsx)(O8t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(Mpe,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(oh,{view:"mine"})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(oh,{view:"recent"})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(oh,{view:"unread"})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(oh,{view:"blocked"})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(oh,{view:"everything"})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(oh,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(Mpe,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(kn,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(nt,{path:"inbox/requests",element:(0,t.jsx)(Mis,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(wUt,{})}),(0,t.jsx)(nt,{path:"design-guide",element:(0,t.jsx)(_as,{})}),(0,t.jsx)(nt,{path:"instance/settings/adapters",element:(0,t.jsx)(bpe,{})}),(0,t.jsx)(nt,{path:":pluginRoutePath/*",element:(0,t.jsx)(vpe,{})}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(zu,{scope:"board"})})]})}r(qis,"boardRoutes");function Ppe({credentialSource:e="paperclip_vault"}={}){const s=na(),n=new URLSearchParams(s.search),{enabled:a}=oS();return mit(n,{chatConnectorsEnabled:a})?(0,t.jsx)(rMe,{credentialSource:e}):(0,t.jsx)(kn,{to:"/apps",replace:!0})}r(Ppe,"AppsConnectEntryRoute");function Mpe(){const{enabled:e}=yc(),{enabled:s}=nA();return e&&s?(0,t.jsx)(oh,{view:tOe(YJ())}):(0,t.jsx)(kn,{to:`/inbox/${YJ()}`,replace:!0})}r(Mpe,"InboxRootRedirect");function oh({view:e}){const s=na(),n=new URLSearchParams(s.search);return n.set(QR,e),(0,t.jsx)(kn,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(oh,"TaskViewRedirect");function M4e(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i,skillId:o}=va();if(a)return null;const l=(i?s.find(c=>c.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;return!l||!o?(0,t.jsx)(kn,{to:"/skills/studio",replace:!0}):(0,t.jsx)(kn,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(M4e,"LegacySkillStudioRedirect");function Rv(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i}=va(),{hidden:o}=cu();if(a)return(0,t.jsx)($m,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return QW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(QG,{});const c=A8e(Dye(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(kn,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(Rv,"LegacySettingsRedirect");function Dpe(){const{tab:e}=va();return(0,t.jsx)(kn,{to:D4e(e),replace:!0})}r(Dpe,"LegacyToolsSettingsRedirect");function Lpe(){const{tab:e}=va();return(0,t.jsx)(kn,{to:D4e(e),replace:!0})}r(Lpe,"LegacyToolsRedirect");function D4e(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(D4e,"legacyToolsRedirectTarget");function L4e(){const{companies:e}=ps(),{openOnboarding:s}=Yo(),{t:n}=cye(),a=$c(),i=ICe(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=kM(),{companyPrefix:c}=va(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(got({onboardingOpen:o,routeDismissed:l}))return null;const u=d?`Add another agent to ${d.name}`:e.length>0?"Create another organization":"Create your first organization",h=d?"Run onboarding again to add an agent and a starter task for this organization.":e.length>0?"Run onboarding again to create another organization and seed its first agent.":"Get started by creating an organization and your first agent.";return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:u}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:h}),(0,t.jsx)("div",{className:"mt-4",children:!d&&a&&!i?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)(L,{onClick:r(()=>d?s({initialStep:O5(),companyId:d.id}):a&&i?Lm(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(L4e,"OnboardingRoutePage");function Uis(){const{companies:e,selectedCompany:s,loading:n}=ps(),a=na();if(n)return(0,t.jsx)($m,{});const i=s??e[0]??null;return i?(0,t.jsx)(kn,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):QW({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(QG,{})}r(Uis,"CompanyRootRedirect");function $pe(){const{cardId:e}=va(),s=eOe(),n=s?`/${s}`:"";return(0,t.jsx)(kn,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r($pe,"StatusCardsLegacyRedirect");function Yp({to:e,forceAgentMode:s=!1}){const n=na(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(kn,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(Yp,"AuditCompatibilityRedirect");function wa(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps();if(a)return(0,t.jsx)($m,{});const i=n??s[0]??null;return i?(0,t.jsx)(kn,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):QW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(QG,{})}r(wa,"UnprefixedBoardRedirect");function QG(){const{openOnboarding:e}=Yo(),{t:s}=cye(),n=$c(),a=ICe(n?.cloudBaseUrl??null);return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:s("app.noCompanies.title",{defaultValue:"Create your first organization"})}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:s("app.noCompanies.description",{defaultValue:"Get started by creating an organization."})}),(0,t.jsx)("div",{className:"mt-4",children:n&&!a?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:s("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)(L,{onClick:r(()=>n&&a?Lm(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(QG,"NoCompaniesStartPage");function Kis(){const{enabled:e,loaded:s}=yc(),{enabled:n}=nA();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(q$e,{children:[(0,t.jsx)(nt,{path:"oauth-handoff",element:(0,t.jsx)(AXt,{})}),(0,t.jsx)(nt,{path:"auth",element:(0,t.jsx)(his,{})}),(0,t.jsx)(nt,{path:"board-claim/:token",element:(0,t.jsx)(pis,{})}),(0,t.jsx)(nt,{path:"cli-auth/:id",element:(0,t.jsx)(fis,{})}),(0,t.jsx)(nt,{path:"invite/:token",element:(0,t.jsx)(wis,{})}),(0,t.jsx)(nt,{path:"s/:token",element:(0,t.jsx)(Rpe,{})}),(0,t.jsx)(nt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(Rpe,{})}),(0,t.jsx)(nt,{element:s?(0,t.jsx)(Xne,{allowMembershipRequest:!0}):(0,t.jsx)($m,{}),children:(0,t.jsx)(nt,{path:"chat-identity/confirm",element:(0,t.jsx)(vXt,{})})}),(0,t.jsx)(nt,{path:"tests/perf/long-thread",element:(0,t.jsx)(Z4t,{})}),(0,t.jsx)(nt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(zHt,{})}),(0,t.jsx)(nt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(qHt,{})}),(0,t.jsx)(nt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(KHt,{})}),(0,t.jsxs)(nt,{element:s?(0,t.jsx)(Xne,{}):(0,t.jsx)($m,{}),children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(Uis,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(L4e,{})}),(0,t.jsx)(nt,{path:"instance",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"instance/settings",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"instance/settings/*",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"inbox/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"routines",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(wa,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"audit/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"activity",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"activity/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(wa,{})})]}):null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M4e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(wa,{})}),mH.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:(0,t.jsx)(wa,{})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:":companyPrefix",element:e?(0,t.jsx)(klt,{}):(0,t.jsx)(sct,{}),children:qis(e,n)}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(zu,{scope:"global"})})]})]}),(0,t.jsx)(bft,{}),(0,t.jsx)(nlt,{})]})}r(Kis,"App");var Wis=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){wCe(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 Vis(){const{data:e}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return Dot(s,n),()=>{Lot()}},[s,n]),null}r(Vis,"SentryGate");function His(e){let s=wg();kie(s),FU(s,e.userId);const n=tRe(()=>{const o=wg();o!==s&&(s=o,kie(o),FU(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=b2t(o.data);l&&(l.type==="navigate"?e.navigate(l.url):x2t(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(His,"startNotificationRuntime");function Gis(){const e=Mn(),s=(0,m.useRef)(e),{data:n}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),a=n?.user?.id??n?.session?.userId??null;return(0,m.useEffect)(()=>{s.current=e},[e]),(0,m.useEffect)(()=>{if(a)return His({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(Gis,"NotificationRuntime");function Qis(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(Qis,"managedRoutineToRow");function Yis({routines:e,agents:s=[],projects:n=[],pluginDisplayName:a=null,emptyMessage:i="No managed routines.",runningRoutineKey:o=null,statusMutationRoutineKey:l=null,reconcilingRoutineKey:c=null,resettingRoutineKey:d=null,onRunNow:u,onToggleEnabled:h,onReconcile:p,onReset:f}){const x=new Map(s.map(v=>[v.id,v])),b=new Map(n.map(v=>[v.id,{name:v.name,color:v.color}]));return e.length===0?(0,t.jsx)("div",{className:"rounded-lg border border-border px-3 py-8 text-center text-sm text-muted-foreground",children:i}):(0,t.jsx)("div",{className:"rounded-lg border border-border",children:e.map(v=>{const j=Qis(v),N=v.href??(v.routineId?`/routines/${v.routineId}`:"/routines"),w=v.missingRefs??[],k=!!(v.routineId&&v.resourceKey&&w.length===0),S=v.managedByPluginDisplayName??a,C=!!(p||f);return(0,t.jsxs)("div",{className:"last:[&_a]:border-b-0",children:[(0,t.jsx)(zEe,{routine:j,projectById:b,agentById:x,runningRoutineId:o,statusMutationRoutineId:l,href:N,configureLabel:"Configure",managedByLabel:S?`Managed by ${S}`:null,runNowButton:!0,hideArchiveAction:!0,disableRunNow:!k,disableToggle:!k,secondaryDetails:(0,t.jsxs)("span",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[v.resourceKey?(0,t.jsx)("span",{children:v.resourceKey}):null,v.cronExpression?(0,t.jsxs)("span",{children:["Schedule ",v.cronExpression]}):null]}),onRunNow:r(()=>u?.(v),"onRunNow"),onToggleEnabled:r(()=>h?.(v,j.status==="active"),"onToggleEnabled")}),C?(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 pb-3 text-xs text-muted-foreground last:border-b-0",onClick:r(I=>{I.preventDefault(),I.stopPropagation()},"onClick"),children:[(0,t.jsx)("span",{children:w.length?`Missing ${w.map(I=>`${I.resourceKind}:${I.resourceKey}`).join(", ")}`:"Routine defaults can be repaired."}),(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[p?(0,t.jsx)(L,{size:"sm",variant:"ghost",disabled:c===v.key,onClick:r(()=>p(v),"onClick"),children:c===v.key?"Reconciling...":"Reconcile"}):null,f?(0,t.jsx)(L,{size:"sm",variant:"ghost",disabled:d===v.key,onClick:r(()=>f(v),"onClick"),children:d===v.key?"Resetting...":"Reset"}):null]})]}):null]},v.key)})})}r(Yis,"ManagedRoutinesList");function Ope(e){return new Set(e??[])}r(Ope,"toPathSet");function Jis({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(hj,{...l,selectedFile:n,expandedDirs:Ope(e),checkedFiles:s?Ope(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(Jis,"PluginSdkFileTree");function Xis(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return Jc(()=>import("./MarkdownEditor-DCE_KC27.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([36,5,7,9,14,37,28,10,26,38])),()=>{a=!0}},[]),s?(0,m.createElement)(s,e):(0,m.createElement)("textarea",{className:e.className,value:e.value,placeholder:e.placeholder,readOnly:e.readOnly,onBlur:e.onBlur,onChange:r(a=>e.onChange(a.currentTarget.value),"onChange")})}r(Xis,"PluginSdkMarkdownEditor");function Zis(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(Zis,"compactIssueFilters");function eos({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=Pt(),d=(0,m.useMemo)(()=>Zis({...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}=ee({queryKey:P.agents.list(e??"__no-company__"),queryFn:r(()=>$t.list(e),"queryFn"),enabled:!!e}),{data:x}=ee({queryKey:P.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>pa.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),b=P.liveRuns(e??"__no-company__"),v=No({companyId:e,resourceKey:"live-runs",queryKey:b,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:j,dataUpdatedAt:N}=ee({queryKey:b,queryFn:r(()=>Jr.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});So(v,j,N);const{data:w,isLoading:k,error:S}=ee({queryKey:p,queryFn:r(()=>St.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>Sg(j,w),[w,j]),I=je({mutationFn:r(({id:R,data:T})=>St.update(R,T),"mutationFn"),onSuccess:r(()=>{e&&(c.invalidateQueries({queryKey:["plugins","sdk-ui","issues-list",e]}),c.invalidateQueries({queryKey:P.issues.list(e)}),h&&(c.invalidateQueries({queryKey:P.issues.listByProject(e,h)}),u&&c.invalidateQueries({queryKey:P.issues.listPluginOperationsByProject(e,h,u)})))},"onSuccess")});return e?(0,m.createElement)(mg,{issues:w??[],isLoading:k,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((R,T)=>I.mutate({id:R,data:T}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(eos,"PluginSdkIssuesList");function tos({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=o9(),f=e??p.companyId??null,{data:x}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),enabled:c}),b=x?.user?.id??x?.session?.userId??null,{data:v}=ee({queryKey:P.agents.list(f??"__no-company__"),queryFn:r(()=>$t.list(f),"queryFn"),enabled:!!f}),{data:j}=ee({queryKey:P.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>pr.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),N=(0,m.useMemo)(()=>jz(),[]),w=(0,m.useMemo)(()=>N.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[N]),k=(0,m.useMemo)(()=>uy((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?nxe(b):[],...c?HN(j?.users,{excludeUserIds:[b]}):[],...k.map(R=>({id:xh({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[j?.users,b,c,k]),C=Uv(s),I=C.assigneeAgentId?k.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)($u,{value:s,options:S,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const T=Uv(R);T.assigneeAgentId&&dy(T.assigneeAgentId),T.assigneeUserId&&i_(T.assigneeUserId),n(R,T)},"onChange"),renderTriggerValue:r(R=>R?I?(0,m.createElement)(oM,null,(0,m.createElement)(F5,{icon:I.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label)):(0,m.createElement)("span",{className:"truncate"},R.label):(0,m.createElement)("span",{className:"text-muted-foreground"},a),"renderTriggerValue"),renderOption:r(R=>{if(!R.id)return(0,m.createElement)("span",{className:"truncate"},R.label);const T=Uv(R.id),A=T.assigneeAgentId?k.find(D=>D.id===T.assigneeAgentId):null;return(0,m.createElement)(oM,null,A?(0,m.createElement)(F5,{icon:A.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(Qc,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(tos,"PluginSdkAssigneePicker");function sos({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=o9(),p=e??h.companyId??null,{data:f}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:b}=ee({queryKey:P.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>pa.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(b??[]).filter(S=>c||!S.archivedAt),[c,b]),{orderedProjects:j}=Qy({projects:v,companyId:p,userId:x}),N=(0,m.useMemo)(()=>cy(),[]),w=(0,m.useMemo)(()=>j.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[j]),k=j.find(S=>S.id===s)??null;return(0,m.createElement)($u,{value:s,options:w,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&J0(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!k?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(oM,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:k.color??"#6366f1"}}),(0,m.createElement)("span",{className:"truncate"},S.label)),"renderTriggerValue"),renderOption:r(S=>{if(!S.id)return(0,m.createElement)("span",{className:"truncate"},S.label);const C=j.find(I=>I.id===S.id);return(0,m.createElement)(oM,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(sos,"PluginSdkProjectPicker");function oM({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(oM,"FragmentSafe");function nos({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(nos,"PluginSdkStatusBadge");function ros({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(ros,"PluginSdkDataTable");function aos({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(aos,"PluginSdkKeyValueList");function ios({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(ios,"PluginSdkMetricCard");function oos({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(oos,"PluginSdkJsonTree");function los({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(los,"PluginSdkSpinner");var cos=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 dos(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:O8e,usePluginAction:F8e,useHostContext:o9,useHostLocation:z8e,useHostNavigation:B8e,usePluginStream:U8e,usePluginToast:q8e,copyTextToClipboard:fa,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(Sn,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:ios,StatusBadge:nos,DataTable:ros,KeyValueList:aos,JsonTree:oos,Spinner:los,ErrorBoundary:cos,MarkdownEditor:Xis,FileTree:Jis,IssuesList:eos,AssigneePicker:tos,ProjectPicker:sos,ManagedRoutinesList:Yis}}}r(dos,"initPluginBridge");var uos=1e4;function mos(e=uos){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(mos,"startPerfMeasureReaper");var hos=Fy((e=>{function s(q,U){var O=q.length;q.push(U);e:for(;0<O;){var K=O-1>>>1,H=q[K];if(0<i(H,U))q[K]=U,q[O]=H,O=K;else break e}}r(s,"push");function n(q){return q.length===0?null:q[0]}r(n,"peek");function a(q){if(q.length===0)return null;var U=q[0],O=q.pop();if(O!==U){q[0]=O;e:for(var K=0,H=q.length,Z=H>>>1;K<Z;){var se=2*(K+1)-1,ne=q[se],fe=se+1,X=q[fe];if(0>i(ne,O))fe<H&&0>i(X,ne)?(q[K]=X,q[fe]=O,K=fe):(q[K]=ne,q[se]=O,K=se);else if(fe<H&&0>i(X,O))q[K]=X,q[fe]=O,K=fe;else break e}}return U}r(a,"pop");function i(q,U){var O=q.sortIndex-U.sortIndex;return O!==0?O:q.id-U.id}if(r(i,"compare"),e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var l=Date,c=l.now();e.unstable_now=function(){return l.now()-c}}var d=[],u=[],h=1,p=null,f=3,x=!1,b=!1,v=!1,j=!1,N=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function S(q){for(var U=n(u);U!==null;){if(U.callback===null)a(u);else if(U.startTime<=q)a(u),U.sortIndex=U.expirationTime,s(d,U);else break;U=n(u)}}r(S,"advanceTimers");function C(q){if(v=!1,S(q),!b)if(n(d)!==null)b=!0,I||(I=!0,B());else{var U=n(u);U!==null&&$(C,U.startTime-q)}}r(C,"handleTimeout");var I=!1,R=-1,T=5,A=-1;function D(){return j?!0:!(e.unstable_now()-A<T)}r(D,"shouldYieldToHost");function M(){if(j=!1,I){var q=e.unstable_now();A=q;var U=!0;try{e:{b=!1,v&&(v=!1,w(R),R=-1),x=!0;var O=f;try{t:{for(S(q),p=n(d);p!==null&&!(p.expirationTime>q&&D());){var K=p.callback;if(typeof K=="function"){p.callback=null,f=p.priorityLevel;var H=K(p.expirationTime<=q);if(q=e.unstable_now(),typeof H=="function"){p.callback=H,S(q),U=!0;break t}p===n(d)&&a(d),S(q)}else a(d);p=n(d)}if(p!==null)U=!0;else{var Z=n(u);Z!==null&&$(C,Z.startTime-q),U=!1}}break e}finally{p=null,f=O,x=!1}U=void 0}}finally{U?B():I=!1}}}r(M,"performWorkUntilDeadline");var B;if(typeof k=="function")B=r(function(){k(M)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var E=new MessageChannel,z=E.port2;E.port1.onmessage=M,B=r(function(){z.postMessage(null)},"schedulePerformWorkUntilDeadline")}else B=r(function(){N(M,0)},"schedulePerformWorkUntilDeadline");function $(q,U){R=N(function(){q(e.unstable_now())},U)}r($,"requestHostTimeout"),e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125<q||(T=0<q?Math.floor(1e3/q):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(q){switch(f){case 1:case 2:case 3:var U=3;break;default:U=f}var O=f;f=U;try{return q()}finally{f=O}},e.unstable_requestPaint=function(){j=!0},e.unstable_runWithPriority=function(q,U){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var O=f;f=q;try{return U()}finally{f=O}},e.unstable_scheduleCallback=function(q,U,O){var K=e.unstable_now();switch(typeof O=="object"&&O!==null?(O=O.delay,O=typeof O=="number"&&0<O?K+O:K):O=K,q){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=O+H,q={id:h++,callback:U,priorityLevel:q,startTime:O,expirationTime:H,sortIndex:-1},O>K?(q.sortIndex=O,s(u,q),n(d)===null&&q===n(u)&&(v?(w(R),R=-1):v=!0,$(C,O-K))):(q.sortIndex=H,s(d,q),b||x||(b=!0,I||(I=!0,B()))),q},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(q){var U=f;return function(){var O=f;f=U;try{return q.apply(this,arguments)}finally{f=O}}}})),pos=Fy(((e,s)=>{s.exports=hos()})),fos=Fy((e=>{var s=pos(),n=s7(),a=Wpe();function i(g){var y="https://react.dev/errors/"+g;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var _=2;_<arguments.length;_++)y+="&args[]="+encodeURIComponent(arguments[_])}return"Minified React error #"+g+"; visit "+y+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}r(i,"formatProdErrorMessage");function o(g){return!(!g||g.nodeType!==1&&g.nodeType!==9&&g.nodeType!==11)}r(o,"isValidContainer");function l(g){var y=g,_=g;if(g.alternate)for(;y.return;)y=y.return;else{g=y;do y=g,(y.flags&4098)!==0&&(_=y.return),g=y.return;while(g)}return y.tag===3?_:null}r(l,"getNearestMountedFiber");function c(g){if(g.tag===13){var y=g.memoizedState;if(y===null&&(g=g.alternate,g!==null&&(y=g.memoizedState)),y!==null)return y.dehydrated}return null}r(c,"getSuspenseInstanceFromFiber");function d(g){if(g.tag===31){var y=g.memoizedState;if(y===null&&(g=g.alternate,g!==null&&(y=g.memoizedState)),y!==null)return y.dehydrated}return null}r(d,"getActivityInstanceFromFiber");function u(g){if(l(g)!==g)throw Error(i(188))}r(u,"assertIsMounted");function h(g){var y=g.alternate;if(!y){if(y=l(g),y===null)throw Error(i(188));return y!==g?null:g}for(var _=g,F=y;;){var V=_.return;if(V===null)break;var J=V.alternate;if(J===null){if(F=V.return,F!==null){_=F;continue}break}if(V.child===J.child){for(J=V.child;J;){if(J===_)return u(V),g;if(J===F)return u(V),y;J=J.sibling}throw Error(i(188))}if(_.return!==F.return)_=V,F=J;else{for(var ve=!1,qe=V.child;qe;){if(qe===_){ve=!0,_=V,F=J;break}if(qe===F){ve=!0,F=V,_=J;break}qe=qe.sibling}if(!ve){for(qe=J.child;qe;){if(qe===_){ve=!0,_=J,F=V;break}if(qe===F){ve=!0,F=J,_=V;break}qe=qe.sibling}if(!ve)throw Error(i(189))}}if(_.alternate!==F)throw Error(i(190))}if(_.tag!==3)throw Error(i(188));return _.stateNode.current===_?g:y}r(h,"findCurrentFiberUsingSlowPath");function p(g){var y=g.tag;if(y===5||y===26||y===27||y===6)return g;for(g=g.child;g!==null;){if(y=p(g),y!==null)return y;g=g.sibling}return null}r(p,"findCurrentHostFiberImpl");var f=Object.assign,x=Symbol.for("react.element"),b=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),j=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),k=Symbol.for("react.consumer"),S=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),R=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),D=Symbol.for("react.activity"),M=Symbol.for("react.memo_cache_sentinel"),B=Symbol.iterator;function E(g){return g===null||typeof g!="object"?null:(g=B&&g[B]||g["@@iterator"],typeof g=="function"?g:null)}r(E,"getIteratorFn");var z=Symbol.for("react.client.reference");function $(g){if(g==null)return null;if(typeof g=="function")return g.$$typeof===z?null:g.displayName||g.name||null;if(typeof g=="string")return g;switch(g){case j:return"Fragment";case w:return"Profiler";case N:return"StrictMode";case I:return"Suspense";case R:return"SuspenseList";case D:return"Activity"}if(typeof g=="object")switch(g.$$typeof){case v:return"Portal";case S:return g.displayName||"Context";case k:return(g._context.displayName||"Context")+".Consumer";case C:var y=g.render;return g=g.displayName,g||(g=y.displayName||y.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case T:return y=g.displayName||null,y!==null?y:$(g.type)||"Memo";case A:y=g._payload,g=g._init;try{return $(g(y))}catch{}}return null}r($,"getComponentNameFromType");var q=Array.isArray,U=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},H=[],Z=-1;function se(g){return{current:g}}r(se,"createCursor");function ne(g){0>Z||(g.current=H[Z],H[Z]=null,Z--)}r(ne,"pop");function fe(g,y){Z++,H[Z]=g.current,g.current=y}r(fe,"push");var X=se(null),re=se(null),oe=se(null),G=se(null);function Y(g,y){switch(fe(oe,y),fe(re,g),fe(X,null),y.nodeType){case 9:case 11:g=(g=y.documentElement)&&(g=g.namespaceURI)?XY(g):0;break;default:if(g=y.tagName,y=y.namespaceURI)y=XY(y),g=ZY(y,g);else switch(g){case"svg":g=1;break;case"math":g=2;break;default:g=0}}ne(X),fe(X,g)}r(Y,"pushHostContainer");function Q(){ne(X),ne(re),ne(oe)}r(Q,"popHostContainer");function te(g){g.memoizedState!==null&&fe(G,g);var y=X.current,_=ZY(y,g.type);y!==_&&(fe(re,g),fe(X,_))}r(te,"pushHostContext");function ae(g){re.current===g&&(ne(X),ne(re)),G.current===g&&(ne(G),US._currentValue=K)}r(ae,"popHostContext");var le,he;function ce(g){if(le===void 0)try{throw Error()}catch(_){var y=_.stack.trim().match(/\n( *(at )?)/);le=y&&y[1]||"",he=-1<_.stack.indexOf(`
|
|
775
|
+
`)}U!==N&&(n.textContent=U,N=U)}r(R,"step");function T(){const E=d>0&&u>0;if(a.matches){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null),E&&S();return}if(!i||!E){o&&(o=!1,s.current!==null&&cancelAnimationFrame(s.current),s.current=null);return}o||(o=!0,l=0,s.current=requestAnimationFrame(R))}r(T,"syncLoop");const A=new ResizeObserver(()=>{const E=Npe(n);h=E.w,p=E.h,k(),T()});A.observe(n);const D=r(()=>{i=document.visibilityState!=="hidden",T()},"onVisibilityChange");document.addEventListener("visibilitychange",D);const M=r(()=>{T()},"onMotionChange");a.addEventListener("change",M);const B=Npe(n);return h=B.w,p=B.h,k(),T(),()=>{o=!1,s.current!==null&&cancelAnimationFrame(s.current),A.disconnect(),document.removeEventListener("visibilitychange",D),a.removeEventListener("change",M)}},[]),(0,t.jsx)("pre",{ref:e,className:"w-full h-full m-0 p-0 overflow-hidden text-muted-foreground/60 select-none leading-none",style:{fontSize:"var(--text-micro)",fontFamily:"monospace"},"aria-hidden":"true"})}r(uis,"AsciiArtAnimation");function mis({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(mis,"PaperclipLockup");function his(){const e=Pt(),s=Mn(),[n]=fi(),[a,i]=(0,m.useState)("sign_in"),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),x="auth-error",b=(0,m.useMemo)(()=>ACe(n.get("next")||lis()||"/"),[n]),v=ee({queryKey:P.health,queryFn:r(()=>du.get(),"queryFn"),retry:!1}),{data:j,isLoading:N,error:w}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{j&&(kV(),s(b,{replace:!0}))},[j,s,b]);const k=je({mutationFn:r(async()=>{if(a==="sign_in"){await Oa.signInEmail({email:c.trim(),password:u});return}await Oa.signUpEmail({name:o.trim(),email:c.trim(),password:u})},"mutationFn"),onSuccess:r(async()=>{f(null),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.resetQueries({queryKey:P.companies.all}),s(b,{replace:!0})},"onSuccess"),onError:r(C=>{f(C instanceof Error?C.message:"Authentication failed")},"onError")}),S=c.trim().length>0&&u.trim().length>0&&(a==="sign_in"||o.trim().length>0&&u.trim().length>=8);return v.isLoading||N||j?(0,t.jsx)("div",{className:"fixed inset-0 flex items-center justify-center",children:(0,t.jsx)($m,{className:"min-h-0"})}):v.error||w?(0,t.jsx)("p",{role:"alert",className:"p-6 text-sm text-destructive",children:"Unable to check sign-in. Refresh and try again."}):v.data?.cloud?(0,t.jsx)(NV,{cloud:v.data.cloud,returnTo:b}):(0,t.jsxs)("div",{className:"fixed inset-0 flex bg-background",children:[(0,t.jsx)("div",{className:"absolute top-4 right-4 z-10",children:(0,t.jsx)(yk,{})}),(0,t.jsx)("div",{className:"w-full md:w-1/2 flex flex-col overflow-y-auto",children:(0,t.jsxs)("div",{className:"w-full max-w-md mx-auto my-auto px-8 py-12",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(mis,{className:"h-5 w-auto"})}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:a==="sign_in"?"Sign in to Paperclip":"Create your Paperclip account"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:a==="sign_in"?"Use your email and password to access this instance.":"Create an account for this instance. Email confirmation is not required in v1."}),(0,t.jsxs)("form",{className:"mt-6 space-y-4",method:"post",action:a==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(C=>{if(C.preventDefault(),!k.isPending){if(!S){f("Please fill in all required fields.");return}k.mutate()}},"onSubmit"),children:[a==="sign_up"&&(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"name",className:"text-xs text-muted-foreground mb-1 block",children:"Name"}),(0,t.jsx)("input",{id:"name",name:"name",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",value:o,onChange:r(C=>l(C.target.value),"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:!0})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"email",className:"text-xs text-muted-foreground mb-1 block",children:"Email"}),(0,t.jsx)("input",{id:"email",name:"email",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"email",value:c,onChange:r(C=>d(C.target.value),"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0,autoFocus:a==="sign_in"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{htmlFor:"password",className:"text-xs text-muted-foreground mb-1 block",children:"Password"}),(0,t.jsx)("input",{id:"password",name:"password",className:"w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50",type:"password",value:u,onChange:r(C=>h(C.target.value),"onChange"),autoComplete:a==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":p?!0:void 0,"aria-describedby":p?x:void 0})]}),p&&(0,t.jsx)("p",{id:x,role:"alert",className:"text-xs text-destructive",children:p}),(0,t.jsx)(L,{type:"submit",disabled:k.isPending,"aria-disabled":!S||k.isPending,className:`w-full ${!S&&!k.isPending?"opacity-50":""}`,children:k.isPending?"Working…":a==="sign_in"?"Sign In":"Create Account"})]}),(0,t.jsxs)("div",{className:"mt-5 text-sm text-muted-foreground",children:[a==="sign_in"?"Need an account?":"Already have an account?"," ",(0,t.jsx)("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2",onClick:r(()=>{f(null),i(a==="sign_in"?"sign_up":"sign_in")},"onClick"),children:a==="sign_in"?"Create one":"Sign in"})]})]})}),(0,t.jsx)("div",{className:"hidden md:block w-1/2 overflow-hidden",children:(0,t.jsx)(uis,{})})]})}r(his,"AuthPage");function pis(){const e=Pt(),s=va(),[n]=fi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),c=ee({queryKey:["board-claim",a,i],queryFn:r(()=>pr.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>pr.claimBoard(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.invalidateQueries({queryKey:P.companies.all}),await e.invalidateQueries({queryKey:P.companies.stats}),await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid board claim URL."});if(c.isLoading||l.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading claim challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Claim challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const u=c.data;return u?u.status==="claimed"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate organization ownership access from local trusted mode."}),d.error&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to claim board ownership"}),(0,t.jsx)(L,{className:"mt-5",onClick:r(()=>d.mutate(),"onClick"),disabled:d.isPending,children:d.isPending?"Claiming…":"Claim ownership"})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Claim challenge unavailable."})}r(pis,"BoardClaimPage");function fis(){const e=Pt(),s=va(),[n]=fi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),c=ee({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>pr.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>pr.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await c.refetch()},"onSuccess")}),u=je({mutationFn:r(()=>pr.cancelCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid CLI auth URL."});if(l.isLoading||c.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading CLI auth challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"CLI auth challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const h=c.data;return h?h.status==="approved"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"CLI access approved"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The Paperclip CLI can now finish authentication on the requesting machine."}),(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Command: ",(0,t.jsx)("span",{className:"font-mono text-foreground",children:h.command})]})]})}):h.status==="cancelled"||h.status==="expired"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h.status==="expired"?"CLI auth challenge expired":"CLI auth challenge cancelled"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Start the CLI auth flow again from your terminal to generate a new approval request."})]})}):h.requiresSignIn||!l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(Ke,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(rn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Approve Paperclip CLI access"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local Paperclip CLI process is requesting board access to this instance."}),(0,t.jsxs)("div",{className:"mt-5 space-y-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Command"}),(0,t.jsx)("div",{className:"font-mono text-foreground",children:h.command})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Client"}),(0,t.jsx)("div",{className:"text-foreground",children:h.clientName??"paperclip-pro cli"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested access"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),h.requestedCompanyName&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested organization"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedCompanyName})]})]}),(d.error||u.error)&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:(d.error??u.error)instanceof Error?(d.error??u.error).message:"Failed to update CLI auth challenge"}),!h.canApprove&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),(0,t.jsxs)("div",{className:"mt-5 flex gap-3",children:[(0,t.jsx)(L,{onClick:r(()=>d.mutate(),"onClick"),disabled:!h.canApprove||d.isPending||u.isPending,children:d.isPending?"Approving...":"Approve CLI access"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>u.mutate(),"onClick"),disabled:d.isPending||u.isPending,children:u.isPending?"Cancelling...":"Cancel"})]})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"CLI auth challenge unavailable."})}r(fis,"CliAuthPage");var xis=i$e.filter(e=>e!=="paperclip_runner"),Spe=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function gis(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(gis,"readNestedString");var Sw="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",Cpe="border border-zinc-800 bg-zinc-950/95 p-6",_pe="flex-1 border px-3 py-2 text-sm transition-colors";function bis(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(bis,"formatHumanRole");function E4e(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(E4e,"getAuthErrorCode");function vis(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(vis,"getAuthErrorMessage");function yis(e,s,n){const a=E4e(e),i=vis(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(yis,"mapInviteAuthFeedback");function Ipe(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(Ipe,"isBootstrapAcceptancePayload");function jis(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(jis,"isApprovedHumanJoinPayload");function Y8({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(tS,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(Y8,"InviteCompanyLogo");function Ape({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)(Y8,{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(Ape,"AwaitingJoinApprovalPanel");function wis(){const e=Pt(),s=Mn(),{setSelectedCompanyId:n}=ps(),a=(va().token??"").trim(),[i,o]=(0,m.useState)("sign_up"),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(""),[b,v]=(0,m.useState)("claude_local"),[j,N]=(0,m.useState)(""),[w,k]=(0,m.useState)(null),[S,C]=(0,m.useState)(null),[I,R]=(0,m.useState)(null),[T,A]=(0,m.useState)(!1),D="invite-auth-error",M=ee({queryKey:P.health,queryFn:r(()=>du.get(),"queryFn"),retry:!1}),B=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),E=ee({queryKey:P.access.invite(a),queryFn:r(()=>pr.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),z=r7({enabled:!!B.data&&!!E.data?.companyId,staleTime:0}),$=M.data?.deploymentMode!=="local_trusted"?z.isFetchedAfterMount:!0,q=$?z.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&wpe(a)},[a]),(0,m.useEffect)(()=>{A(!1)},[a]),(0,m.useEffect)(()=>{if(!$)return;const ge=z.data?.companies;!ge||!E.data?.companyId||ge.some(me=>me.id===E.data.companyId)&&WR(a)},[z.data,E.data,$,a]);const U=E.data,O=!!B.data&&!!U?.companyId&&!$,K=!!U?.companyId&&q.some(ge=>ge.id===U?.companyId),H=U?.companyName?.trim()||"this Paperclip company",Z=U?.companyLogoUrl?.trim()||null,se=U?.invitedByUserName?.trim()||null,ne=U?.inviteMessage?.trim()||null,fe=bis(U?.humanRole),X=U?.joinRequestStatus??null,re=U?.joinRequestType??null,oe=re==="human"&&(X==="pending_approval"||X==="approved"),G=M.data?.deploymentMode==="authenticated"&&!B.data&&U?.allowedJoinTypes!=="agent",Y=U?.inviteType!=="bootstrap_ceo"&&U?.allowedJoinTypes==="agent",Q=!!B.data&&!Y&&U?.inviteType!=="bootstrap_ceo"&&(!X||oe)&&!O&&!K&&!w&&S===null,te=B.data?.user.name?.trim()||B.data?.user.email?.trim()||"this account",ae=d.trim().length>0&&h.trim().length>0&&(i==="sign_in"||l.trim().length>0&&h.trim().length>=8),le=je({mutationFn:r(async()=>{if(!U)throw new Error("Invite not found");if(O)throw new Error("Checking your organization access. Try again in a moment.");if(K)throw new Error("This account already belongs to the organization.");return U.inviteType==="bootstrap_ceo"||U.allowedJoinTypes!=="agent"?pr.acceptInvite(a,{requestType:"human"}):pr.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:b,capabilities:j.trim()||null})},"mutationFn"),onSuccess:r(async ge=>{C(null),WR(a);const me=Ipe(ge);k({kind:me?"bootstrap":"join",payload:ge}),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.access.currentBoardAccess}),await e.invalidateQueries({queryKey:P.companies.all}),U?.companyId&&jis(ge,Y)&&(n(U.companyId,{source:"manual"}),s("/",{replace:!0}))},"onSuccess"),onError:r(ge=>{C(ge instanceof Error?ge.message:"Failed to accept invite")},"onError")});(0,m.useEffect)(()=>{!Q||T||le.isPending||(A(!0),C(null),le.mutate())},[le,T,Q]);const he=je({mutationFn:r(async()=>{if(i==="sign_in"){await Oa.signInEmail({email:d.trim(),password:h});return}await Oa.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{R(null),wpe(a),await e.invalidateQueries({queryKey:P.auth.session}),await e.invalidateQueries({queryKey:P.health}),await e.invalidateQueries({queryKey:P.access.currentBoardAccess});const{companies:ge}=await w$e(e);if(U?.companyId&&ge.some(me=>me.id===U.companyId)){WR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!U||U.inviteType!=="bootstrap_ceo"))try{Ipe(await le.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ge=>{const me=yis(ge,i,d);E4e(ge)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),R(me)},"onError")}),ce=(0,m.useMemo)(()=>U?K?"Open organization":U.inviteType==="bootstrap_ceo"?"Accept invite":Y?"Submit request":B.data?"Accept invite":"Continue":"Continue",[U,K,B.data,Y]);if(!a)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid invite token."});if(E.isLoading||M.isLoading||B.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(O)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Checking your access..."});if(E.error||!U)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This invite may be expired, revoked, or already used."})]})});if(X==="approved"&&re==="human"&&K)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Opening organization..."});if(X==="pending_approval"&&!oe)return(0,t.jsx)(Ape,{companyDisplayName:H,companyLogoUrl:Z,invitedByUserName:se});if(X&&!oe)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"border border-border bg-card p-6","data-testid":"invite-error",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Invite not available"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:X==="rejected"?"This join request was not approved.":"This invite has already been used."})]})});if(w?.kind==="bootstrap")return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Bootstrap complete"}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(L,{asChild:!0,className:"rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ge=w.payload,me=typeof ge.claimSecret=="string"?ge.claimSecret:null,ie=typeof ge.claimApiKeyPath=="string"?ge.claimApiKeyPath:null,ue=gis(ge.onboarding,["textInstructions","url"]);return!Y&&ge.status==="approved"?(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsxs)("div",{className:"mx-auto max-w-md border border-zinc-800 bg-zinc-950 p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(Y8,{companyDisplayName:H,companyLogoUrl:Z,className:"h-12 w-12 border border-zinc-800 rounded-none"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"You joined the organization"})]}),(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(L,{asChild:!0,className:"w-full rounded-none",children:(0,t.jsx)(Ke,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(Ape,{companyDisplayName:H,companyLogoUrl:Z,invitedByUserName:se,claimSecret:me,claimApiKeyPath:ie,onboardingTextUrl:ue})}return(0,t.jsx)("div",{className:"min-h-screen bg-zinc-950 px-6 py-12 text-zinc-100",children:(0,t.jsx)("div",{className:"mx-auto max-w-5xl",children:(0,t.jsxs)("div",{className:"grid gap-6 lg:grid-cols-(--gtc-36)",children:[(0,t.jsxs)("section",{className:`${Cpe} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(Y8,{companyDisplayName:H,companyLogoUrl:Z,className:"h-16 w-16 rounded-none border border-zinc-800"}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("p",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"You've been invited to join Paperclip"}),(0,t.jsx)("h1",{className:"mt-2 text-2xl font-semibold",children:U.inviteType==="bootstrap_ceo"?"Set up Paperclip":`Join ${H}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:Y?"Review the invite details, then submit the agent information below to start the join request.":G?"Create your Paperclip account first. If you already have one, switch to sign in and continue the invite with the same email.":"Your account is ready. Review the invite details, then accept it to continue."})]})]}),(0,t.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2",children:[(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Organization"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:H})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invited by"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:se??"Paperclip board"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Requested access"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:Y?"Agent join request":fe??"Organization access"})]}),(0,t.jsxs)("div",{className:"border border-zinc-800 p-3",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-zinc-500",children:"Invite expires"}),(0,t.jsx)("div",{className:"mt-1 text-sm text-zinc-100",children:Id(U.expiresAt)})]})]}),ne?(0,t.jsxs)("div",{className:"border border-amber-500/40 bg-amber-500/10 p-4",children:[(0,t.jsx)("div",{className:"text-xs uppercase tracking-(--tracking-caps) text-amber-200/80",children:"Message from inviter"}),(0,t.jsx)("p",{className:"mt-2 text-sm leading-6 text-amber-50",children:ne})]}):null,B.data?(0,t.jsxs)("div",{className:"border border-emerald-500/40 bg-emerald-500/10 p-4 text-sm text-emerald-50",children:["Signed in as ",(0,t.jsx)("span",{className:"font-medium",children:te}),"."]}):null]}),(0,t.jsx)("section",{className:`${Cpe} h-fit`,children:Y?(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:"Submit agent details"}),(0,t.jsxs)("p",{className:"mt-1 text-sm text-zinc-400",children:["This invite will create an approval request for a new agent in ",H,"."]})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Agent name"}),(0,t.jsx)("input",{className:Sw,value:f,onChange:r(ge=>x(ge.target.value),"onChange")})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Adapter type"}),(0,t.jsx)("select",{className:Sw,value:b,onChange:r(ge=>v(ge.target.value),"onChange"),children:xis.map(ge=>(0,t.jsxs)("option",{value:ge,disabled:!Spe.has(ge),children:[Bf(ge),Spe.has(ge)?"":" (Coming soon)"]},ge))})]}),(0,t.jsxs)("label",{className:"block text-sm",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Capabilities"}),(0,t.jsx)("textarea",{className:Sw,rows:4,value:j,onChange:r(ge=>N(ge.target.value),"onChange")})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,(0,t.jsx)(L,{className:"w-full rounded-none",disabled:le.isPending||f.trim().length===0,onClick:r(()=>le.mutate(),"onClick"),children:le.isPending?"Working...":ce})]}):G?(0,t.jsxs)("div",{className:"space-y-5",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:i==="sign_up"?"Create your account":"Sign in to continue"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:i==="sign_up"?`Start with a Paperclip account. After that, you'll come right back here to accept the invite for ${H}.`:"Use the Paperclip account that already matches this invite. If you do not have one yet, switch back to create account."})]}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)("button",{type:"button",className:`${_pe} ${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:`${_pe} ${i==="sign_in"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{R(null),o("sign_in")},"onClick"),children:"I already have an account"})]}),(0,t.jsxs)("form",{className:"space-y-4",method:"post",action:i==="sign_up"?"/api/auth/sign-up/email":"/api/auth/sign-in/email",onSubmit:r(ge=>{if(ge.preventDefault(),!he.isPending){if(!ae){R({tone:"error",message:"Please fill in all required fields."});return}he.mutate()}},"onSubmit"),"data-testid":"invite-inline-auth",children:[i==="sign_up"?(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-name",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Name"}),(0,t.jsx)("input",{id:"invite-name",name:"name",className:Sw,value:l,onChange:r(ge=>{c(ge.target.value),R(null)},"onChange"),autoComplete:"name",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D:void 0,autoFocus:!0})]}):null,(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-email",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Email"}),(0,t.jsx)("input",{id:"invite-email",name:"email",type:"email",className:Sw,value:d,onChange:r(ge=>{u(ge.target.value),R(null)},"onChange"),autoComplete:"username",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D:void 0,autoFocus:i==="sign_in"})]}),(0,t.jsxs)("label",{className:"block text-sm",htmlFor:"invite-password",children:[(0,t.jsx)("span",{className:"mb-1 block text-zinc-400",children:"Password"}),(0,t.jsx)("input",{id:"invite-password",name:"password",type:"password",className:Sw,value:h,onChange:r(ge=>{p(ge.target.value),R(null)},"onChange"),autoComplete:i==="sign_in"?"current-password":"new-password",required:!0,"aria-required":"true","aria-invalid":I?.tone==="error"?!0:void 0,"aria-describedby":I?D:void 0})]}),I?(0,t.jsx)("p",{id:D,role:"alert",className:`text-xs ${I.tone==="info"?"text-amber-300":"text-red-400"}`,children:I.message}):null,(0,t.jsx)(L,{type:"submit",className:"w-full rounded-none",disabled:he.isPending,"aria-disabled":!ae||he.isPending,children:he.isPending?"Working...":i==="sign_in"?"Sign in and continue":"Create account and continue"})]}),(0,t.jsx)("p",{className:"text-xs leading-5 text-zinc-500",children:i==="sign_up"?"Already signed up before? Use the existing-account option instead so the invite lands on the right Paperclip user.":"No account yet? Switch back to create account so you can accept the invite with a new login."})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:K?"Already in this organization":Q?"Completing organization access":U.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Q?`Granting your access to ${H}.`:K?`This account already belongs to ${H}.`:`This will ${U.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${H}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Q?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:le.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)(L,{className:"w-full rounded-none",disabled:le.isPending,onClick:r(()=>{if(K&&U.companyId){WR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}le.mutate()},"onClick"),children:le.isPending?"Working...":ce})]})})]})})})}r(wis,"InviteLandingPage");var kis=15e3,Nis={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Sis(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Sis,"useNoIndexMeta");function J8(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(J8,"sharePath");var Cis=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function _is(e,s){const n=Cis.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(_is,"publicShareImageSrc");function OC({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(OC,"Section");function X8({actor:e}){return(0,t.jsx)(Hl,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(X8,"ActorIdentity");function Z8({value:e}){return(0,t.jsx)("time",{dateTime:e,title:Rr(e),className:"text-xs text-muted-foreground",children:cr(e)})}r(Z8,"Timestamp");function Iis({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(Iis,"ActiveRunPill");function P4e({attachments:e}){return(0,t.jsx)(D9,{children:e.map(s=>{const n=owe({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=L9(s.byteSize);return(0,t.jsxs)(T9,{size:"sm",children:[(0,t.jsx)(R9,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(E9,{children:[(0,t.jsx)(P9,{className:"max-w-48",children:s.filename}),(0,t.jsx)(M9,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(nwe,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(P4e,"AttachmentList");function Ais({related:e,token:s,isSharedRoot:n}){const a=e.identifier?`${e.identifier} · ${e.title}`:e.title,i=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Xi,{status:e.status,size:"sm"}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:a})]});return(0,t.jsxs)("li",{className:"flex items-center gap-2 text-sm",children:[(0,t.jsx)("span",{className:"w-20 shrink-0 text-xs text-muted-foreground",children:Nis[e.relation]}),e.navigable?(0,t.jsx)(ld,{to:n?J8(s,e.id):J8(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(Ais,"RelatedIssueRow");function Tis({comment:e,resolveImageSrc:s}){return e.kind==="redacted"?(0,t.jsxs)("li",{"data-testid":"public-share-redacted-comment",className:"flex flex-wrap items-center gap-2 rounded-lg border border-dashed border-border px-3 py-2",children:[(0,t.jsx)(X8,{actor:e.author}),(0,t.jsx)(Z8,{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)(X8,{actor:e.author}),(0,t.jsx)(Z8,{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)(P4e,{attachments:e.attachments}):null]})}r(Tis,"TimelineEntry");function Ris({document:e,resolveImageSrc:s}){return(0,t.jsxs)("details",{className:"group rounded-lg border border-border bg-card",children:[(0,t.jsxs)("summary",{className:"flex cursor-pointer items-center gap-2 px-3 py-2 text-sm",children:[(0,t.jsx)(Ha,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.title??e.key}),(0,t.jsx)(Z8,{value:e.updatedAt})]}),(0,t.jsxs)("div",{className:"space-y-3 border-t border-border px-3 py-3",children:[(0,t.jsxs)("a",{href:e.pdfUrl,download:!0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(po,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(Sn,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(Ris,"DocumentCard");function Eis({product:e}){return(0,t.jsxs)("li",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border border-border bg-card px-3 py-2 text-sm",children:[(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.title}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground",children:[e.type.replace(/_/g," ")," · ",e.status.replace(/_/g," ")]}),e.url?(0,t.jsxs)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Vn,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Open"]}):null,e.downloadUrl?(0,t.jsxs)("a",{href:e.downloadUrl,download:!0,rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(po,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(Eis,"WorkProductRow");function Tpe({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(Tpe,"CenteredNotice");function Pis({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>_is(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)(tS,{companyName:n.name,logoUrl:n.logoUrl,logoFit:"contain",className:"h-8 w-8 shrink-0 rounded-md"}),(0,t.jsx)("span",{className:"min-w-0 truncate text-sm font-medium",children:n.name}),(0,t.jsx)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:"Read-only view"})]})}),(0,t.jsxs)("main",{className:"mx-auto max-w-3xl space-y-8 px-4 py-5",children:[e.isSharedRoot?null:(0,t.jsxs)(ld,{to:J8(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(Tl,{className:"h-4 w-4","aria-hidden":!0}),"Back to main task"]}),(0,t.jsxs)("section",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground",children:[a.identifier?(0,t.jsx)("span",{children:a.identifier}):null,a.projectName?(0,t.jsx)("span",{children:a.projectName}):null]}),(0,t.jsx)("h1",{className:"break-words text-xl font-semibold",children:a.title}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,t.jsx)(sp,{status:a.status}),(0,t.jsx)(Xfe,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(X8,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(Iis,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",Rr(a.createdAt)," · Updated ",cr(a.updatedAt),a.completedAt?` · Completed ${Rr(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(Sn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)(OC,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(Ais,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(OC,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(Ris,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(OC,{title:"Attachments",children:(0,t.jsx)(P4e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(OC,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(Eis,{product:o},o.id))})}):null,(0,t.jsx)(OC,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(Tis,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(Pis,"PublicIssueShareContent");function Rpe(){const{token:e="",issueId:s}=va();Sis();const n=Sze.test(e),a=ee({queryKey:P.publicShare.view(e,s??null),queryFn:r(()=>s?Dk.getPublicShareIssue(e,s):Dk.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?kis:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Tpe,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(Pis,{view:a.data,token:e}):a.isError?(0,t.jsx)(Tpe,{title:"Couldn't load this page",body:"Check your connection and try again.",action:(0,t.jsx)(L,{variant:"outline",size:"sm",className:"mt-2",onClick:r(()=>{a.refetch()},"onClick"),children:"Try again"})}):(0,t.jsx)("div",{className:"h-dvh overflow-y-auto px-4 py-6","aria-busy":"true",children:(0,t.jsxs)("div",{className:"mx-auto max-w-3xl space-y-4",children:[(0,t.jsx)(vn,{className:"h-6 w-1/2"}),(0,t.jsx)(vn,{className:"h-4 w-1/3"}),(0,t.jsx)(vn,{className:"h-24 w-full"})]})})}r(Rpe,"PublicIssueSharePage");function Mis(){const{selectedCompany:e,selectedCompanyId:s}=ps(),{setBreadcrumbs:n}=Bn(),{pushToast:a}=xi(),i=Pt(),[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=ee({queryKey:P.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>pr.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=je({mutationFn:r(f=>pr.approveJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.joinRequests(s,`${o}:${c}`)}),await i.invalidateQueries({queryKey:P.access.companyMembers(s)}),await i.invalidateQueries({queryKey:P.access.companyUserDirectory(s)}),a({title:"Join request approved",tone:"success"})},"onSuccess")}),p=je({mutationFn:r(f=>pr.rejectJoinRequest(s,f),"mutationFn"),onSuccess:r(async()=>{await i.invalidateQueries({queryKey:P.access.joinRequests(s,`${o}:${c}`)}),a({title:"Join request rejected",tone:"success"})},"onSuccess")});if(!s)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Select an organization to review join requests."});if(u.isLoading)return(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading join requests…"});if(u.error){const f=u.error instanceof dn&&u.error.status===403?"You do not have permission to review join requests for this organization.":u.error instanceof Error?u.error.message:"Failed to load join requests.";return(0,t.jsx)("div",{className:"text-sm text-destructive",children:f})}return(0,t.jsxs)("div",{className:"max-w-6xl space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Jqe,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Join Request Queue"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Review human and agent join requests outside the mixed inbox feed. This queue uses the same approval mutations as the inline inbox cards."})]}),(0,t.jsxs)(rn,{className:"flex-row flex-wrap gap-3 p-4",children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Status"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(f=>l(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"pending_approval",children:"Pending approval"}),(0,t.jsx)("option",{value:"approved",children:"Approved"}),(0,t.jsx)("option",{value:"rejected",children:"Rejected"})]})]}),(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Request type"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:c,onChange:r(f=>d(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"all",children:"All"}),(0,t.jsx)("option",{value:"human",children:"Human"}),(0,t.jsx)("option",{value:"agent",children:"Agent"})]})]})]}),(0,t.jsx)("div",{className:"space-y-4",children:(u.data??[]).length===0?(0,t.jsx)("div",{className:"rounded-xl border border-dashed border-border px-4 py-8 text-sm text-muted-foreground",children:"No join requests match the current filters."}):u.data.map(f=>(0,t.jsxs)(rn,{className:"block p-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(ct,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(ct,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(ct,{variant:"outline",children:f.adapterType}):null]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-base font-medium",children:f.requestType==="human"?f.requesterUser?.name||f.requestEmailSnapshot||f.requestingUserId||"Unknown human requester":f.agentName||"Unknown agent requester"}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:f.requestType==="human"?f.requesterUser?.email||f.requestEmailSnapshot||f.requestingUserId:f.capabilities||f.requestIp})]})]}),f.status==="pending_approval"?(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(L,{variant:"outline",onClick:r(()=>p.mutate(f.id),"onClick"),disabled:p.isPending,children:"Reject"}),(0,t.jsx)(L,{onClick:r(()=>h.mutate(f.id),"onClick"),disabled:h.isPending,children:"Approve"})]}):null]}),(0,t.jsxs)("div",{className:"mt-4 grid gap-3 text-sm text-muted-foreground md:grid-cols-2",children:[(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Invite context"}),(0,t.jsx)("div",{className:"mt-2",children:f.invite?`${f.invite.allowedJoinTypes} join invite${f.invite.humanRole?` • default role ${f.invite.humanRole}`:""}`:"Invite metadata unavailable"}),f.invite?.inviteMessage?(0,t.jsx)("div",{className:"mt-2 text-foreground",children:f.invite.inviteMessage}):null]}),(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-background px-3 py-2",children:[(0,t.jsx)("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Request details"}),(0,t.jsxs)("div",{className:"mt-2",children:["Submitted ",new Date(f.createdAt).toLocaleString()]}),(0,t.jsxs)("div",{children:["Source IP ",f.requestIp]}),f.requestType==="agent"&&f.capabilities?(0,t.jsx)("div",{children:f.capabilities}):null]})]})]},f.id))})]})}r(Mis,"JoinRequestQueue");var Dis=(0,m.lazy)(()=>Jc(()=>import("./CompanyExport-CbGWtqna.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]))),Lis=(0,m.lazy)(()=>Jc(()=>import("./Agents.production-BDrotnkr.js").then(e=>({default:e.Agents})),__vite__mapDeps([25,5,7,9,8,10,11,12,13,26,27,28,29,30,31,32,33,23,24]))),$is=(0,m.lazy)(()=>Jc(()=>import("./Routines.production-CrrER4oK.js").then(e=>({default:e.Routines})),__vite__mapDeps([34,5,7,8,9,10,11,12,13,35,14,36,37,28,26,38,39,40,20,41,42,15,16,17,18,29,43,44,30,45,46,22,31,47,33,48,49,50,51,23,24,27]))),Epe=(0,m.lazy)(()=>Jc(()=>import("./RoutineDetail.production-BLcjq7J0.js").then(e=>({default:e.RoutineDetail})),__vite__mapDeps([52,5,7,8,9,10,11,12,13,35,14,36,37,28,26,38,39,40,20,41,42,15,16,17,18,29,43,44,30,45,46,22,31,47,33,48,49,50,51,23,24,53]))),Ois=(0,m.lazy)(()=>Jc(()=>import("./CompanySkills.production-DTqClYmE.js").then(e=>({default:e.CompanySkills})),__vite__mapDeps([54,5,7,8,9,10,11,12,13,14,36,37,28,26,38,39,40,20,41,27,15,16,17,18,55,53,31,44,21,19,56,47,48,50,23,24]))),Fis=(0,m.lazy)(()=>Jc(()=>import("./CompanyActivity.production-DVFoP5Wf.js").then(e=>({default:e.CompanyActivity})),__vite__mapDeps([57,5,7,8,9,10,11,12,13,26,27,28,43,37,20,44,48,49,51]))),Bis=(0,m.lazy)(()=>Jc(()=>import("./Costs.production-ClgsqTtT.js").then(e=>({default:e.Costs})),__vite__mapDeps([58,5,7,27,28,13,12,44,41,50,26,51,23,24]))),zis=(0,m.lazy)(()=>Jc(()=>import("./OrgChart.production-D8k1dx4P.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([59,5,7,8,9,10,11,12,13,26,45,46,51,23,24])));function h0({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)($m,{}),children:e})}r(h0,"ProductionSurface");function qis(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(kn,{to:"dashboard",replace:!0})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(ISt,{})}),(0,t.jsx)(nt,{path:"dashboard/live",element:(0,t.jsx)(ASt,{})}),(0,t.jsx)(nt,{path:"timeline",element:e?(0,t.jsx)(Yp,{to:"/activity/timeline"}):(0,t.jsx)(G2e,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(L4e,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(fCt,{})}),(0,t.jsx)(nt,{path:"company/settings",element:(0,t.jsx)(T7t,{})}),(0,t.jsx)(nt,{path:"company/settings/environments",element:(0,t.jsx)(kn,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(kn,{to:"/company/export",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.members"}),children:[(0,t.jsx)(nt,{path:"company/settings/members",element:(0,t.jsx)(XHt,{})}),(0,t.jsx)(nt,{path:"company/settings/access",element:(0,t.jsx)(ZHt,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.invites"}),children:(0,t.jsx)(nt,{path:"company/settings/invites",element:(0,t.jsx)(kn,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.export"}),children:(0,t.jsx)(nt,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)($m,{}),children:(0,t.jsx)(Dis,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(But,{}),children:(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.import"}),children:(0,t.jsx)(nt,{path:"company/import",element:(0,t.jsx)(Mrs,{})})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"company.secrets"}),children:(0,t.jsx)(nt,{path:"company/settings/secrets",element:(0,t.jsx)(Ans,{})})}),(0,t.jsx)(nt,{path:"company/settings/tools",element:(0,t.jsx)(Dpe,{})}),(0,t.jsx)(nt,{path:"company/settings/tools/:tab",element:(0,t.jsx)(Dpe,{})}),(0,t.jsx)(nt,{path:"tools",element:(0,t.jsx)(Lpe,{})}),(0,t.jsx)(nt,{path:"tools/:tab",element:(0,t.jsx)(Lpe,{})}),(0,t.jsx)(nt,{path:"apps",element:(0,t.jsx)(VQt,{})}),(0,t.jsx)(nt,{path:"apps/browse",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connections",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/byo",element:(0,t.jsx)(rMe,{byoOnly:!0})}),(0,t.jsx)(nt,{path:"apps/vercel-connect",element:(0,t.jsx)(Ppe,{credentialSource:"vercel_connect"})}),(0,t.jsx)(nt,{path:"apps/connect",element:(0,t.jsx)(Ppe,{})}),(0,t.jsx)(nt,{path:"apps/chat/connect",element:(0,t.jsx)(VB,{children:(0,t.jsx)(aJt,{})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId",element:(0,t.jsx)(VB,{children:(0,t.jsx)(kn,{to:"settings",replace:!0})})}),(0,t.jsx)(nt,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(VB,{children:(0,t.jsx)(hXt,{})})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/review",element:(0,t.jsx)(jXt,{})}),(0,t.jsx)(nt,{path:"apps/attention",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways",element:(0,t.jsx)(Lme,{})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(kn,{to:"overview",replace:!0})}),(0,t.jsx)(nt,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(JXt,{})}),(0,t.jsx)(nt,{path:"apps/advanced",element:(0,t.jsx)(ime,{})}),(0,t.jsx)(nt,{path:"apps/advanced/gateways",element:(0,t.jsx)(Lme,{})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(ume,{mode:"new"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(ume,{mode:"edit"})}),(0,t.jsx)(nt,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(bQt,{})}),(0,t.jsx)(nt,{path:"apps/advanced/audit",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(kn,{to:"/apps",replace:!0})}),(0,t.jsx)(nt,{path:"apps/advanced/:tab",element:(0,t.jsx)(ime,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId",element:(0,t.jsx)(Pme,{})}),(0,t.jsx)(nt,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(Pme,{})}),(0,t.jsx)(nt,{path:"apps/:connectionId",element:(0,t.jsx)(kn,{to:"permissions",replace:!0})}),(0,t.jsx)(nt,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(vYt,{})}),(0,t.jsx)(nt,{path:"company/settings/instance",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.profile"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/profile",element:(0,t.jsx)(Bas,{})})}),(0,t.jsx)(nt,{path:"company/settings/instance/general",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(nt,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(kn,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.environments"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/environments",element:(0,t.jsx)(PB,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(PB,{mode:"create"})}),(0,t.jsx)(nt,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(PB,{mode:"edit"})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.access"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/access",element:(0,t.jsx)(Eas,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.experimental"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/experimental",element:(0,t.jsx)(Ras,{})})}),(0,t.jsxs)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(nt,{path:"company/settings/instance/plugins",element:(0,t.jsx)(qas,{})}),(0,t.jsx)(nt,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(Uas,{})})]}),(0,t.jsx)(nt,{element:(0,t.jsx)(Hh,{pageKey:"instance.adapters"}),children:(0,t.jsx)(nt,{path:"company/settings/instance/adapters",element:(0,t.jsx)(bpe,{})})}),(0,t.jsx)(nt,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(WHt,{})}),(0,t.jsx)(nt,{path:"skills/sources",element:(0,t.jsx)(lhe,{})}),(0,t.jsx)(nt,{path:"skills/sources/:sourceId",element:(0,t.jsx)(lhe,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(az,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(az,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(az,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M4e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:e?(0,t.jsx)(mes,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Ois,{})})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"plugins/:pluginId",element:(0,t.jsx)(vpe,{})}),(0,t.jsx)(nt,{path:"org",element:e?(0,t.jsx)(kn,{to:"/agents/all",replace:!0}):(0,t.jsx)(h0,{children:(0,t.jsx)(zis,{})})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(kn,{to:"/agents/all",replace:!0})}),mH.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:e?(0,t.jsx)(qCt,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Lis,{})})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(ois,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(lF,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(lF,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(lF,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(sAt,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(mO,{}),children:(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(YTt,{})})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/budget",element:(0,t.jsx)(Xb,{})}),(0,t.jsx)(nt,{element:(0,t.jsx)(mO,{}),children:(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(ZTt,{})})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(wEt,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"search",element:(0,t.jsx)(qEt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(oh,{view:"all"})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(oh,{view:"active"})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(oh,{view:"backlog"})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(oh,{view:"done"})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(oh,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"issues/all",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/active",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/backlog",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/done",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})}),(0,t.jsx)(nt,{path:"issues/recent",element:(0,t.jsx)(kn,{to:"/issues",replace:!0})})]}),(0,t.jsx)(nt,{path:"chats",element:(0,t.jsx)(B4t,{})}),(0,t.jsx)(nt,{path:"chats/:agentRef",element:(0,t.jsx)(q4t,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(D4t,{})}),null,(0,t.jsx)(nt,{path:"routines",element:e?(0,t.jsx)(jDt,{}):(0,t.jsx)(h0,{children:(0,t.jsx)($is,{})})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(rne,{children:(0,t.jsx)(imt,{})})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(rne,{children:(0,t.jsx)(Upt,{})})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(Fut,{children:(0,t.jsx)(Xqt,{})})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(ane,{children:(0,t.jsx)(rce,{})})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(ane,{children:(0,t.jsx)(rce,{})})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)($pe,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)($pe,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(s0,{children:(0,t.jsx)(F$t,{})})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(s0,{children:(0,t.jsx)(z$t,{})})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(s0,{children:(0,t.jsx)(QF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(s0,{children:(0,t.jsx)(QF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(s0,{children:(0,t.jsx)(QF,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(s0,{children:(0,t.jsx)(MOt,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(s0,{children:(0,t.jsx)(a$t,{})})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(s0,{children:(0,t.jsx)(s$t,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:e?(0,t.jsx)(ide,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Epe,{})})}),(0,t.jsx)(nt,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(ide,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Epe,{})})}),(0,t.jsx)(nt,{element:(0,t.jsx)(mO,{}),children:(0,t.jsxs)(nt,{element:(0,t.jsx)(qut,{}),children:[(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(vw,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(vw,{})})]})}),(0,t.jsx)(nt,{path:"goals",element:(0,t.jsx)(GUt,{})}),(0,t.jsx)(nt,{path:"goals/:goalId",element:(0,t.jsx)(aKt,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(dde,{})}),(0,t.jsx)(nt,{path:"approvals",element:(0,t.jsx)(kn,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(nt,{path:"approvals/pending",element:(0,t.jsx)(mde,{})}),(0,t.jsx)(nt,{path:"approvals/all",element:(0,t.jsx)(mde,{})}),(0,t.jsx)(nt,{path:"approvals/:approvalId",element:(0,t.jsx)(iKt,{})}),(0,t.jsx)(nt,{path:"activity",element:e?(0,t.jsx)(HKt,{}):(0,t.jsx)(h0,{children:(0,t.jsx)(Fis,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"activity/runs",element:(0,t.jsx)(i1,{section:"runs"})}),(0,t.jsx)(nt,{path:"activity/costs",element:(0,t.jsx)(i1,{section:"costs"})}),(0,t.jsx)(nt,{path:"activity/budgets",element:(0,t.jsx)(i1,{section:"budgets"})}),(0,t.jsx)(nt,{path:"activity/timeline",element:(0,t.jsx)(i1,{section:"timeline"})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(Yp,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(nt,{path:"audit/activity",element:(0,t.jsx)(Yp,{to:"/activity"})}),(0,t.jsx)(nt,{path:"audit/runs",element:(0,t.jsx)(Yp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"audit/costs",element:(0,t.jsx)(Yp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"audit/budgets",element:(0,t.jsx)(Yp,{to:"/activity/budgets"})}),(0,t.jsx)(nt,{path:"audit/timeline",element:(0,t.jsx)(Yp,{to:"/activity/timeline"})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(Yp,{to:"/activity/runs"})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(Yp,{to:"/activity/costs"})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(Yp,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(h0,{children:(0,t.jsx)(Bis,{})})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(kn,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(nt,{element:(0,t.jsx)(act,{}),children:[(0,t.jsx)(nt,{path:"board-chat",element:(0,t.jsx)(c7t,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(dde,{})})]}),null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(M8t,{})}),(0,t.jsx)(nt,{path:"decisions/queues/:key",element:(0,t.jsx)(O8t,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(Mpe,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(oh,{view:"mine"})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(oh,{view:"recent"})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(oh,{view:"unread"})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(oh,{view:"blocked"})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(oh,{view:"everything"})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(oh,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"inbox",element:(0,t.jsx)(Mpe,{})}),(0,t.jsx)(nt,{path:"inbox/mine",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/recent",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/unread",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/blocked",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/all",element:(0,t.jsx)(Pw,{})}),(0,t.jsx)(nt,{path:"inbox/new",element:(0,t.jsx)(kn,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(nt,{path:"inbox/requests",element:(0,t.jsx)(Mis,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(wUt,{})}),(0,t.jsx)(nt,{path:"design-guide",element:(0,t.jsx)(_as,{})}),(0,t.jsx)(nt,{path:"instance/settings/adapters",element:(0,t.jsx)(bpe,{})}),(0,t.jsx)(nt,{path:":pluginRoutePath/*",element:(0,t.jsx)(vpe,{})}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(zu,{scope:"board"})})]})}r(qis,"boardRoutes");function Ppe({credentialSource:e="paperclip_vault"}={}){const s=na(),n=new URLSearchParams(s.search),{enabled:a}=oS();return mit(n,{chatConnectorsEnabled:a})?(0,t.jsx)(rMe,{credentialSource:e}):(0,t.jsx)(kn,{to:"/apps",replace:!0})}r(Ppe,"AppsConnectEntryRoute");function Mpe(){const{enabled:e}=yc(),{enabled:s}=nA();return e&&s?(0,t.jsx)(oh,{view:tOe(YJ())}):(0,t.jsx)(kn,{to:`/inbox/${YJ()}`,replace:!0})}r(Mpe,"InboxRootRedirect");function oh({view:e}){const s=na(),n=new URLSearchParams(s.search);return n.set(QR,e),(0,t.jsx)(kn,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(oh,"TaskViewRedirect");function M4e(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i,skillId:o}=va();if(a)return null;const l=(i?s.find(c=>c.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;return!l||!o?(0,t.jsx)(kn,{to:"/skills/studio",replace:!0}):(0,t.jsx)(kn,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(M4e,"LegacySkillStudioRedirect");function Rv(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps(),{companyPrefix:i}=va(),{hidden:o}=cu();if(a)return(0,t.jsx)($m,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return QW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(QG,{});const c=A8e(Dye(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(kn,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(Rv,"LegacySettingsRedirect");function Dpe(){const{tab:e}=va();return(0,t.jsx)(kn,{to:D4e(e),replace:!0})}r(Dpe,"LegacyToolsSettingsRedirect");function Lpe(){const{tab:e}=va();return(0,t.jsx)(kn,{to:D4e(e),replace:!0})}r(Lpe,"LegacyToolsRedirect");function D4e(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(D4e,"legacyToolsRedirectTarget");function L4e(){const{companies:e}=ps(),{openOnboarding:s}=Yo(),{t:n}=cye(),a=$c(),i=ICe(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=kM(),{companyPrefix:c}=va(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(got({onboardingOpen:o,routeDismissed:l}))return null;const u=d?`Add another agent to ${d.name}`:e.length>0?"Create another organization":"Create your first organization",h=d?"Run onboarding again to add an agent and a starter task for this organization.":e.length>0?"Run onboarding again to create another organization and seed its first agent.":"Get started by creating an organization and your first agent.";return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:u}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:h}),(0,t.jsx)("div",{className:"mt-4",children:!d&&a&&!i?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:n("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)(L,{onClick:r(()=>d?s({initialStep:O5(),companyId:d.id}):a&&i?Lm(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(L4e,"OnboardingRoutePage");function Uis(){const{companies:e,selectedCompany:s,loading:n}=ps(),a=na();if(n)return(0,t.jsx)($m,{});const i=s??e[0]??null;return i?(0,t.jsx)(kn,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):QW({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(QG,{})}r(Uis,"CompanyRootRedirect");function $pe(){const{cardId:e}=va(),s=eOe(),n=s?`/${s}`:"";return(0,t.jsx)(kn,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r($pe,"StatusCardsLegacyRedirect");function Yp({to:e,forceAgentMode:s=!1}){const n=na(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(kn,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(Yp,"AuditCompatibilityRedirect");function wa(){const e=na(),{companies:s,selectedCompany:n,loading:a}=ps();if(a)return(0,t.jsx)($m,{});const i=n??s[0]??null;return i?(0,t.jsx)(kn,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):QW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(kn,{to:"/onboarding",replace:!0}):(0,t.jsx)(QG,{})}r(wa,"UnprefixedBoardRedirect");function QG(){const{openOnboarding:e}=Yo(),{t:s}=cye(),n=$c(),a=ICe(n?.cloudBaseUrl??null);return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)("div",{className:"rounded-lg border border-border bg-card p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:s("app.noCompanies.title",{defaultValue:"Create your first organization"})}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:s("app.noCompanies.description",{defaultValue:"Get started by creating an organization."})}),(0,t.jsx)("div",{className:"mt-4",children:n&&!a?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:s("app.cloudCreateUnavailable",{defaultValue:"Organizations are created in Paperclip Cloud. This instance can't reach it right now — try again from your Cloud portfolio."})}):(0,t.jsx)(L,{onClick:r(()=>n&&a?Lm(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(QG,"NoCompaniesStartPage");function Kis(){const{enabled:e,loaded:s}=yc(),{enabled:n}=nA();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(q$e,{children:[(0,t.jsx)(nt,{path:"oauth-handoff",element:(0,t.jsx)(AXt,{})}),(0,t.jsx)(nt,{path:"auth",element:(0,t.jsx)(his,{})}),(0,t.jsx)(nt,{path:"board-claim/:token",element:(0,t.jsx)(pis,{})}),(0,t.jsx)(nt,{path:"cli-auth/:id",element:(0,t.jsx)(fis,{})}),(0,t.jsx)(nt,{path:"invite/:token",element:(0,t.jsx)(wis,{})}),(0,t.jsx)(nt,{path:"s/:token",element:(0,t.jsx)(Rpe,{})}),(0,t.jsx)(nt,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(Rpe,{})}),(0,t.jsx)(nt,{element:s?(0,t.jsx)(Xne,{allowMembershipRequest:!0}):(0,t.jsx)($m,{}),children:(0,t.jsx)(nt,{path:"chat-identity/confirm",element:(0,t.jsx)(vXt,{})})}),(0,t.jsx)(nt,{path:"tests/perf/long-thread",element:(0,t.jsx)(Z4t,{})}),(0,t.jsx)(nt,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(zHt,{})}),(0,t.jsx)(nt,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(qHt,{})}),(0,t.jsx)(nt,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(KHt,{})}),(0,t.jsxs)(nt,{element:s?(0,t.jsx)(Xne,{}):(0,t.jsx)($m,{}),children:[(0,t.jsx)(nt,{index:!0,element:(0,t.jsx)(Uis,{})}),(0,t.jsx)(nt,{path:"onboarding",element:(0,t.jsx)(L4e,{})}),(0,t.jsx)(nt,{path:"instance",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"instance/settings",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"instance/settings/*",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"companies",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"dashboard",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"inbox/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"issues",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"tasks",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"issues/:issueId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"routines",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"routines/:routineId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"review-queue",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"learnings",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"cases",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"cases/:caseIdentifier",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pixels-office",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status/:cardId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status-cards",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"status-cards/:cardId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"artifacts",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"audit",element:(0,t.jsx)(wa,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(nt,{path:"audit/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"activity",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"activity/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"runs",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"costs",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"budgets",element:(0,t.jsx)(wa,{})})]}):null,(0,t.jsx)(nt,{path:"decisions",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"u/:userSlug",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio/new",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/studio/:skillId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"skills/:skillId/studio",element:(0,t.jsx)(M4e,{})}),(0,t.jsx)(nt,{path:"skills/*",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"settings",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"settings/*",element:(0,t.jsx)(Rv,{})}),(0,t.jsx)(nt,{path:"agents",element:(0,t.jsx)(wa,{})}),mH.map(a=>(0,t.jsx)(nt,{path:`agents/${a}`,element:(0,t.jsx)(wa,{})},a)),(0,t.jsx)(nt,{path:"agents/new",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/:tab",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/overview",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"projects/:projectId/configuration",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"workspaces",element:(0,t.jsx)(wa,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Zj,{})}),(0,t.jsx)(nt,{path:":companyPrefix",element:e?(0,t.jsx)(klt,{}):(0,t.jsx)(sct,{}),children:qis(e,n)}),(0,t.jsx)(nt,{path:"*",element:(0,t.jsx)(zu,{scope:"global"})})]})]}),(0,t.jsx)(bft,{}),(0,t.jsx)(nlt,{})]})}r(Kis,"App");var Wis=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){wCe(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 Vis(){const{data:e}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return Dot(s,n),()=>{Lot()}},[s,n]),null}r(Vis,"SentryGate");function His(e){let s=wg();kie(s),FU(s,e.userId);const n=tRe(()=>{const o=wg();o!==s&&(s=o,kie(o),FU(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=b2t(o.data);l&&(l.type==="navigate"?e.navigate(l.url):x2t(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(His,"startNotificationRuntime");function Gis(){const e=Mn(),s=(0,m.useRef)(e),{data:n}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),retry:!1}),a=n?.user?.id??n?.session?.userId??null;return(0,m.useEffect)(()=>{s.current=e},[e]),(0,m.useEffect)(()=>{if(a)return His({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(Gis,"NotificationRuntime");function Qis(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(Qis,"managedRoutineToRow");function Yis({routines:e,agents:s=[],projects:n=[],pluginDisplayName:a=null,emptyMessage:i="No managed routines.",runningRoutineKey:o=null,statusMutationRoutineKey:l=null,reconcilingRoutineKey:c=null,resettingRoutineKey:d=null,onRunNow:u,onToggleEnabled:h,onReconcile:p,onReset:f}){const x=new Map(s.map(v=>[v.id,v])),b=new Map(n.map(v=>[v.id,{name:v.name,color:v.color}]));return e.length===0?(0,t.jsx)("div",{className:"rounded-lg border border-border px-3 py-8 text-center text-sm text-muted-foreground",children:i}):(0,t.jsx)("div",{className:"rounded-lg border border-border",children:e.map(v=>{const j=Qis(v),N=v.href??(v.routineId?`/routines/${v.routineId}`:"/routines"),w=v.missingRefs??[],k=!!(v.routineId&&v.resourceKey&&w.length===0),S=v.managedByPluginDisplayName??a,C=!!(p||f);return(0,t.jsxs)("div",{className:"last:[&_a]:border-b-0",children:[(0,t.jsx)(zEe,{routine:j,projectById:b,agentById:x,runningRoutineId:o,statusMutationRoutineId:l,href:N,configureLabel:"Configure",managedByLabel:S?`Managed by ${S}`:null,runNowButton:!0,hideArchiveAction:!0,disableRunNow:!k,disableToggle:!k,secondaryDetails:(0,t.jsxs)("span",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[v.resourceKey?(0,t.jsx)("span",{children:v.resourceKey}):null,v.cronExpression?(0,t.jsxs)("span",{children:["Schedule ",v.cronExpression]}):null]}),onRunNow:r(()=>u?.(v),"onRunNow"),onToggleEnabled:r(()=>h?.(v,j.status==="active"),"onToggleEnabled")}),C?(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 pb-3 text-xs text-muted-foreground last:border-b-0",onClick:r(I=>{I.preventDefault(),I.stopPropagation()},"onClick"),children:[(0,t.jsx)("span",{children:w.length?`Missing ${w.map(I=>`${I.resourceKind}:${I.resourceKey}`).join(", ")}`:"Routine defaults can be repaired."}),(0,t.jsxs)("span",{className:"flex items-center gap-2",children:[p?(0,t.jsx)(L,{size:"sm",variant:"ghost",disabled:c===v.key,onClick:r(()=>p(v),"onClick"),children:c===v.key?"Reconciling...":"Reconcile"}):null,f?(0,t.jsx)(L,{size:"sm",variant:"ghost",disabled:d===v.key,onClick:r(()=>f(v),"onClick"),children:d===v.key?"Resetting...":"Reset"}):null]})]}):null]},v.key)})})}r(Yis,"ManagedRoutinesList");function Ope(e){return new Set(e??[])}r(Ope,"toPathSet");function Jis({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(hj,{...l,selectedFile:n,expandedDirs:Ope(e),checkedFiles:s?Ope(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(Jis,"PluginSdkFileTree");function Xis(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return Jc(()=>import("./MarkdownEditor-DCE_KC27.js").then(i=>i.n).then(i=>{a||n(()=>i.MarkdownEditor)}),__vite__mapDeps([36,5,7,9,14,37,28,10,26,38])),()=>{a=!0}},[]),s?(0,m.createElement)(s,e):(0,m.createElement)("textarea",{className:e.className,value:e.value,placeholder:e.placeholder,readOnly:e.readOnly,onBlur:e.onBlur,onChange:r(a=>e.onChange(a.currentTarget.value),"onChange")})}r(Xis,"PluginSdkMarkdownEditor");function Zis(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(Zis,"compactIssueFilters");function eos({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=Pt(),d=(0,m.useMemo)(()=>Zis({...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}=ee({queryKey:P.agents.list(e??"__no-company__"),queryFn:r(()=>$t.list(e),"queryFn"),enabled:!!e}),{data:x}=ee({queryKey:P.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>pa.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),b=P.liveRuns(e??"__no-company__"),v=No({companyId:e,resourceKey:"live-runs",queryKey:b,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:j,dataUpdatedAt:N}=ee({queryKey:b,queryFn:r(()=>Jr.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});So(v,j,N);const{data:w,isLoading:k,error:S}=ee({queryKey:p,queryFn:r(()=>St.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>Sg(j,w),[w,j]),I=je({mutationFn:r(({id:R,data:T})=>St.update(R,T),"mutationFn"),onSuccess:r(()=>{e&&(c.invalidateQueries({queryKey:["plugins","sdk-ui","issues-list",e]}),c.invalidateQueries({queryKey:P.issues.list(e)}),h&&(c.invalidateQueries({queryKey:P.issues.listByProject(e,h)}),u&&c.invalidateQueries({queryKey:P.issues.listPluginOperationsByProject(e,h,u)})))},"onSuccess")});return e?(0,m.createElement)(mg,{issues:w??[],isLoading:k,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((R,T)=>I.mutate({id:R,data:T}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(eos,"PluginSdkIssuesList");function tos({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=o9(),f=e??p.companyId??null,{data:x}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn"),enabled:c}),b=x?.user?.id??x?.session?.userId??null,{data:v}=ee({queryKey:P.agents.list(f??"__no-company__"),queryFn:r(()=>$t.list(f),"queryFn"),enabled:!!f}),{data:j}=ee({queryKey:P.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>pr.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),N=(0,m.useMemo)(()=>jz(),[]),w=(0,m.useMemo)(()=>N.map(R=>R.startsWith("agent:")?R.slice(6):null).filter(R=>!!R),[N]),k=(0,m.useMemo)(()=>uy((v??[]).filter(R=>d||R.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?nxe(b):[],...c?HN(j?.users,{excludeUserIds:[b]}):[],...k.map(R=>({id:xh({assigneeAgentId:R.id}),label:R.name,searchText:`${R.name} ${R.role} ${R.title??""}`}))],[j?.users,b,c,k]),C=Uv(s),I=C.assigneeAgentId?k.find(R=>R.id===C.assigneeAgentId):null;return(0,m.createElement)($u,{value:s,options:S,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(R=>{const T=Uv(R);T.assigneeAgentId&&dy(T.assigneeAgentId),T.assigneeUserId&&i_(T.assigneeUserId),n(R,T)},"onChange"),renderTriggerValue:r(R=>R?I?(0,m.createElement)(oM,null,(0,m.createElement)(F5,{icon:I.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label)):(0,m.createElement)("span",{className:"truncate"},R.label):(0,m.createElement)("span",{className:"text-muted-foreground"},a),"renderTriggerValue"),renderOption:r(R=>{if(!R.id)return(0,m.createElement)("span",{className:"truncate"},R.label);const T=Uv(R.id),A=T.assigneeAgentId?k.find(D=>D.id===T.assigneeAgentId):null;return(0,m.createElement)(oM,null,A?(0,m.createElement)(F5,{icon:A.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(Qc,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},R.label))},"renderOption")})}r(tos,"PluginSdkAssigneePicker");function sos({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=o9(),p=e??h.companyId??null,{data:f}=ee({queryKey:P.auth.session,queryFn:r(()=>Oa.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:b}=ee({queryKey:P.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>pa.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(b??[]).filter(S=>c||!S.archivedAt),[c,b]),{orderedProjects:j}=Qy({projects:v,companyId:p,userId:x}),N=(0,m.useMemo)(()=>cy(),[]),w=(0,m.useMemo)(()=>j.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[j]),k=j.find(S=>S.id===s)??null;return(0,m.createElement)($u,{value:s,options:w,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&J0(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!k?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(oM,null,(0,m.createElement)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:k.color??"#6366f1"}}),(0,m.createElement)("span",{className:"truncate"},S.label)),"renderTriggerValue"),renderOption:r(S=>{if(!S.id)return(0,m.createElement)("span",{className:"truncate"},S.label);const C=j.find(I=>I.id===S.id);return(0,m.createElement)(oM,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(sos,"PluginSdkProjectPicker");function oM({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(oM,"FragmentSafe");function nos({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(nos,"PluginSdkStatusBadge");function ros({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(ros,"PluginSdkDataTable");function aos({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(aos,"PluginSdkKeyValueList");function ios({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(ios,"PluginSdkMetricCard");function oos({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(oos,"PluginSdkJsonTree");function los({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(los,"PluginSdkSpinner");var cos=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 dos(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:O8e,usePluginAction:F8e,useHostContext:o9,useHostLocation:z8e,useHostNavigation:B8e,usePluginStream:U8e,usePluginToast:q8e,copyTextToClipboard:fa,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(Sn,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:ios,StatusBadge:nos,DataTable:ros,KeyValueList:aos,JsonTree:oos,Spinner:los,ErrorBoundary:cos,MarkdownEditor:Xis,FileTree:Jis,IssuesList:eos,AssigneePicker:tos,ProjectPicker:sos,ManagedRoutinesList:Yis}}}r(dos,"initPluginBridge");var uos=1e4;function mos(e=uos){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(mos,"startPerfMeasureReaper");var hos=Fy((e=>{function s(q,U){var O=q.length;q.push(U);e:for(;0<O;){var K=O-1>>>1,H=q[K];if(0<i(H,U))q[K]=U,q[O]=H,O=K;else break e}}r(s,"push");function n(q){return q.length===0?null:q[0]}r(n,"peek");function a(q){if(q.length===0)return null;var U=q[0],O=q.pop();if(O!==U){q[0]=O;e:for(var K=0,H=q.length,Z=H>>>1;K<Z;){var se=2*(K+1)-1,ne=q[se],fe=se+1,X=q[fe];if(0>i(ne,O))fe<H&&0>i(X,ne)?(q[K]=X,q[fe]=O,K=fe):(q[K]=ne,q[se]=O,K=se);else if(fe<H&&0>i(X,O))q[K]=X,q[fe]=O,K=fe;else break e}}return U}r(a,"pop");function i(q,U){var O=q.sortIndex-U.sortIndex;return O!==0?O:q.id-U.id}if(r(i,"compare"),e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var l=Date,c=l.now();e.unstable_now=function(){return l.now()-c}}var d=[],u=[],h=1,p=null,f=3,x=!1,b=!1,v=!1,j=!1,N=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function S(q){for(var U=n(u);U!==null;){if(U.callback===null)a(u);else if(U.startTime<=q)a(u),U.sortIndex=U.expirationTime,s(d,U);else break;U=n(u)}}r(S,"advanceTimers");function C(q){if(v=!1,S(q),!b)if(n(d)!==null)b=!0,I||(I=!0,B());else{var U=n(u);U!==null&&$(C,U.startTime-q)}}r(C,"handleTimeout");var I=!1,R=-1,T=5,A=-1;function D(){return j?!0:!(e.unstable_now()-A<T)}r(D,"shouldYieldToHost");function M(){if(j=!1,I){var q=e.unstable_now();A=q;var U=!0;try{e:{b=!1,v&&(v=!1,w(R),R=-1),x=!0;var O=f;try{t:{for(S(q),p=n(d);p!==null&&!(p.expirationTime>q&&D());){var K=p.callback;if(typeof K=="function"){p.callback=null,f=p.priorityLevel;var H=K(p.expirationTime<=q);if(q=e.unstable_now(),typeof H=="function"){p.callback=H,S(q),U=!0;break t}p===n(d)&&a(d),S(q)}else a(d);p=n(d)}if(p!==null)U=!0;else{var Z=n(u);Z!==null&&$(C,Z.startTime-q),U=!1}}break e}finally{p=null,f=O,x=!1}U=void 0}}finally{U?B():I=!1}}}r(M,"performWorkUntilDeadline");var B;if(typeof k=="function")B=r(function(){k(M)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var E=new MessageChannel,z=E.port2;E.port1.onmessage=M,B=r(function(){z.postMessage(null)},"schedulePerformWorkUntilDeadline")}else B=r(function(){N(M,0)},"schedulePerformWorkUntilDeadline");function $(q,U){R=N(function(){q(e.unstable_now())},U)}r($,"requestHostTimeout"),e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125<q||(T=0<q?Math.floor(1e3/q):5)},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(q){switch(f){case 1:case 2:case 3:var U=3;break;default:U=f}var O=f;f=U;try{return q()}finally{f=O}},e.unstable_requestPaint=function(){j=!0},e.unstable_runWithPriority=function(q,U){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var O=f;f=q;try{return U()}finally{f=O}},e.unstable_scheduleCallback=function(q,U,O){var K=e.unstable_now();switch(typeof O=="object"&&O!==null?(O=O.delay,O=typeof O=="number"&&0<O?K+O:K):O=K,q){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=O+H,q={id:h++,callback:U,priorityLevel:q,startTime:O,expirationTime:H,sortIndex:-1},O>K?(q.sortIndex=O,s(u,q),n(d)===null&&q===n(u)&&(v?(w(R),R=-1):v=!0,$(C,O-K))):(q.sortIndex=H,s(d,q),b||x||(b=!0,I||(I=!0,B()))),q},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(q){var U=f;return function(){var O=f;f=U;try{return q.apply(this,arguments)}finally{f=O}}}})),pos=Fy(((e,s)=>{s.exports=hos()})),fos=Fy((e=>{var s=pos(),n=s7(),a=Wpe();function i(g){var y="https://react.dev/errors/"+g;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var _=2;_<arguments.length;_++)y+="&args[]="+encodeURIComponent(arguments[_])}return"Minified React error #"+g+"; visit "+y+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}r(i,"formatProdErrorMessage");function o(g){return!(!g||g.nodeType!==1&&g.nodeType!==9&&g.nodeType!==11)}r(o,"isValidContainer");function l(g){var y=g,_=g;if(g.alternate)for(;y.return;)y=y.return;else{g=y;do y=g,(y.flags&4098)!==0&&(_=y.return),g=y.return;while(g)}return y.tag===3?_:null}r(l,"getNearestMountedFiber");function c(g){if(g.tag===13){var y=g.memoizedState;if(y===null&&(g=g.alternate,g!==null&&(y=g.memoizedState)),y!==null)return y.dehydrated}return null}r(c,"getSuspenseInstanceFromFiber");function d(g){if(g.tag===31){var y=g.memoizedState;if(y===null&&(g=g.alternate,g!==null&&(y=g.memoizedState)),y!==null)return y.dehydrated}return null}r(d,"getActivityInstanceFromFiber");function u(g){if(l(g)!==g)throw Error(i(188))}r(u,"assertIsMounted");function h(g){var y=g.alternate;if(!y){if(y=l(g),y===null)throw Error(i(188));return y!==g?null:g}for(var _=g,F=y;;){var V=_.return;if(V===null)break;var J=V.alternate;if(J===null){if(F=V.return,F!==null){_=F;continue}break}if(V.child===J.child){for(J=V.child;J;){if(J===_)return u(V),g;if(J===F)return u(V),y;J=J.sibling}throw Error(i(188))}if(_.return!==F.return)_=V,F=J;else{for(var ve=!1,qe=V.child;qe;){if(qe===_){ve=!0,_=V,F=J;break}if(qe===F){ve=!0,F=V,_=J;break}qe=qe.sibling}if(!ve){for(qe=J.child;qe;){if(qe===_){ve=!0,_=J,F=V;break}if(qe===F){ve=!0,F=J,_=V;break}qe=qe.sibling}if(!ve)throw Error(i(189))}}if(_.alternate!==F)throw Error(i(190))}if(_.tag!==3)throw Error(i(188));return _.stateNode.current===_?g:y}r(h,"findCurrentFiberUsingSlowPath");function p(g){var y=g.tag;if(y===5||y===26||y===27||y===6)return g;for(g=g.child;g!==null;){if(y=p(g),y!==null)return y;g=g.sibling}return null}r(p,"findCurrentHostFiberImpl");var f=Object.assign,x=Symbol.for("react.element"),b=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),j=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),k=Symbol.for("react.consumer"),S=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),R=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),D=Symbol.for("react.activity"),M=Symbol.for("react.memo_cache_sentinel"),B=Symbol.iterator;function E(g){return g===null||typeof g!="object"?null:(g=B&&g[B]||g["@@iterator"],typeof g=="function"?g:null)}r(E,"getIteratorFn");var z=Symbol.for("react.client.reference");function $(g){if(g==null)return null;if(typeof g=="function")return g.$$typeof===z?null:g.displayName||g.name||null;if(typeof g=="string")return g;switch(g){case j:return"Fragment";case w:return"Profiler";case N:return"StrictMode";case I:return"Suspense";case R:return"SuspenseList";case D:return"Activity"}if(typeof g=="object")switch(g.$$typeof){case v:return"Portal";case S:return g.displayName||"Context";case k:return(g._context.displayName||"Context")+".Consumer";case C:var y=g.render;return g=g.displayName,g||(g=y.displayName||y.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case T:return y=g.displayName||null,y!==null?y:$(g.type)||"Memo";case A:y=g._payload,g=g._init;try{return $(g(y))}catch{}}return null}r($,"getComponentNameFromType");var q=Array.isArray,U=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},H=[],Z=-1;function se(g){return{current:g}}r(se,"createCursor");function ne(g){0>Z||(g.current=H[Z],H[Z]=null,Z--)}r(ne,"pop");function fe(g,y){Z++,H[Z]=g.current,g.current=y}r(fe,"push");var X=se(null),re=se(null),oe=se(null),G=se(null);function Y(g,y){switch(fe(oe,y),fe(re,g),fe(X,null),y.nodeType){case 9:case 11:g=(g=y.documentElement)&&(g=g.namespaceURI)?XY(g):0;break;default:if(g=y.tagName,y=y.namespaceURI)y=XY(y),g=ZY(y,g);else switch(g){case"svg":g=1;break;case"math":g=2;break;default:g=0}}ne(X),fe(X,g)}r(Y,"pushHostContainer");function Q(){ne(X),ne(re),ne(oe)}r(Q,"popHostContainer");function te(g){g.memoizedState!==null&&fe(G,g);var y=X.current,_=ZY(y,g.type);y!==_&&(fe(re,g),fe(X,_))}r(te,"pushHostContext");function ae(g){re.current===g&&(ne(X),ne(re)),G.current===g&&(ne(G),US._currentValue=K)}r(ae,"popHostContext");var le,he;function ce(g){if(le===void 0)try{throw Error()}catch(_){var y=_.stack.trim().match(/\n( *(at )?)/);le=y&&y[1]||"",he=-1<_.stack.indexOf(`
|
|
776
776
|
at`)?" (<anonymous>)":-1<_.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
777
777
|
`+le+g+he}r(ce,"describeBuiltInComponentFrame");var ge=!1;function me(g,y){if(!g||ge)return"";ge=!0;var _=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var F={DetermineComponentFrameRoot:r(function(){try{if(y){var Os=r(function(){throw Error()},"Fake");if(Object.defineProperty(Os.prototype,"props",{set:r(function(){throw Error()},"set")}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Os,[])}catch(ms){var ns=ms}Reflect.construct(g,[],Os)}else{try{Os.call()}catch(ms){ns=ms}g.call(Os.prototype)}}else{try{throw Error()}catch(ms){ns=ms}(Os=g())&&typeof Os.catch=="function"&&Os.catch(function(){})}}catch(ms){if(ms&&ns&&typeof ms.stack=="string")return[ms.stack,ns.stack]}return[null,null]},"DetermineComponentFrameRoot")};F.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var V=Object.getOwnPropertyDescriptor(F.DetermineComponentFrameRoot,"name");V&&V.configurable&&Object.defineProperty(F.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var J=F.DetermineComponentFrameRoot(),ve=J[0],qe=J[1];if(ve&&qe){var jt=ve.split(`
|
|
778
778
|
`),ts=qe.split(`
|