@tickernelz/paperclip-pro-ui 2026.1007.2 → 2026.1007.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-CQk3vdUE.js → Agents.production-DonAKR8K.js} +2 -2
- package/dist/assets/{CompanyActivity.production-CYOblDJ_.js → CompanyActivity.production-DSbPGLZv.js} +1 -1
- package/dist/assets/{CompanyExport-fZQCAxR3.js → CompanyExport-D6Hn27B_.js} +1 -1
- package/dist/assets/{CompanySkills.production-DZ9QO3Qb.js → CompanySkills.production-NS3jGhDW.js} +1 -1
- package/dist/assets/{Costs.production-DGzfBw_5.js → Costs.production-Dv0d-Z6H.js} +1 -1
- package/dist/assets/{OrgChart.production-DKLPpvm-.js → OrgChart.production-DieTRMth.js} +1 -1
- package/dist/assets/{RoutineDetail.production-Cgm2eWNX.js → RoutineDetail.production-Qq6ShQm5.js} +1 -1
- package/dist/assets/{Routines.production-BfGvfmpS.js → Routines.production-BxvC3L7v.js} +1 -1
- package/dist/assets/{definition-CZKX1H5T.js → definition-CK1a00WC.js} +1 -1
- package/dist/assets/{index-Cblntx1v.js → index-D6Rnj-qc.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-CK1a00WC.js","assets/character-CguPM7IG.js","assets/prod-COP_vZWu.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/CompanyExport-D6Hn27B_.js","assets/agent-avatar-url-BcyFoVtv.js","assets/router-DesWEj2C.js","assets/preload-helper-CceJXRIF.js","assets/boxes-tcjFwFpA.js","assets/agents-DQx-dvSi.js","assets/EmptyState-BZtI8X0G.js","assets/button-BY21O8GT.js","assets/mention-chips-D_n_qKFh.js","assets/StatusIcon-mIm27nQw.js","assets/clipboard-DHhOZMRn.js","assets/loader-circle-Bq0tfpSr.js","assets/octagon-alert-D4baqyHT.js","assets/MarkdownBody-C_h6YRQp.js","assets/check-CnODEUG9.js","assets/external-link-C19HtmzW.js","assets/rotate-ccw-LNlo9y5X.js","assets/PageSkeleton-Cy0AuFsD.js","assets/skeleton-CLIvalUo.js","assets/Agents.production-DonAKR8K.js","assets/AgentAvatar-CJxUMdmk.js","assets/tabs-De8GZtQI.js","assets/dist-BCtf-vM2.js","assets/bot-DKL-W8OH.js","assets/heartbeats-DF-m9cYQ.js","assets/triangle-alert-6xzP6adj.js","assets/SidebarContext-zupbpsOa.js","assets/environments-B7NZX_ky.js","assets/Routines.production-BxvC3L7v.js","assets/RoutineRunVariablesDialog-DCnWm09I.js","assets/MarkdownEditor-BOTosEGR.js","assets/dist-C42YHTVB.js","assets/dist-DCJXgQu0.js","assets/sheet-DaK7uiF0.js","assets/checkbox-I5XQmb-K.js","assets/chevron-right-B6d9r4Ro.js","assets/label-CZQ8NWbL.js","assets/select-CTeNTKSP.js","assets/chevron-down-DFUcku8q.js","assets/useHiddenSettings-Cx5eN_RQ.js","assets/health-CQndBw_N.js","assets/badge-BqqBOTVc.js","assets/input-B204XBDT.js","assets/company-members-Dzwzy-as.js","assets/AgentIdentity-D9ti_IEi.js","assets/card-De_lOmuE.js","assets/RoutineDetail.production-Qq6ShQm5.js","assets/save-DDenfr8W.js","assets/CompanySkills.production-NS3jGhDW.js","assets/use-adapter-capabilities-BoIn6U4T.js","assets/file-text-CeE8_Vjy.js","assets/CompanyActivity.production-DSbPGLZv.js","assets/Costs.production-Dv0d-Z6H.js","assets/OrgChart.production-DieTRMth.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var yDe=Object.defineProperty;var r=(e,s)=>yDe(e,"name",{value:s,configurable:!0});import{i as YP,n as jDe,t as Oy}from"./rolldown-runtime-ZpX3ckPj.js";import{$ as Cf,$n as wDe,$t as kDe,A as NDe,Ai as O8,An as SDe,Ar as CDe,At as _De,B as lpe,Bn as cpe,Br as IDe,Bt as ADe,C as TDe,Cn as F8,Cr as RDe,Ct as wN,D as Lr,Di as Mt,Dn as EDe,Dr as rJ,Dt as dpe,E as Id,Ei as PDe,En as upe,Er as l3,Et as MDe,F as Q1,Fn as DDe,Fr as mpe,Ft as LDe,G as $De,Gn as hpe,Gr as Dk,Gt as ODe,H as FDe,Hn as hI,Hr as Bb,Ht as BDe,I as d1,In as tp,Ir as Sl,It as zDe,J as Qf,Jn as aJ,Jr as je,Jt as qDe,K as UDe,Kn as vf,Kr as ob,Kt as KDe,L as jm,Ln as ppe,Lr as un,Lt as WDe,M as Ka,Mn as fpe,Mr as kL,Mt as kN,N as c3,Nn as VDe,Nr as Yw,Nt as HDe,O as iJ,Oi as GDe,On as QDe,Or as YDe,Ot as B8,P as og,Pn as Jw,Pr as oJ,Pt as JDe,Q as xpe,Qn as lJ,Qt as XDe,R as z8,Rn as d3,Rr as Te,Rt as ZDe,S as W,Sn as oz,Sr as pI,St as eLe,T as na,Ti as fI,Tn as gp,Tt as cJ,U as gs,Un as q8,Ur as tLe,Ut as sLe,Vn as gpe,Vt as nLe,W as rLe,Wn as aLe,Wr as iLe,Wt as bpe,X as P,Xn as oLe,Xr as lLe,Xt as cLe,Y as U8,Yn as vpe,Yr as X,Yt as dLe,Z as La,Zn as ype,Zt as uLe,_ as xm,_n as mLe,_r as dJ,_t as hLe,an as pLe,ar as JP,at as jpe,b as uJ,bn as Lk,br as XP,bt as mJ,c as fLe,ci as xLe,cn as gLe,cr as wpe,ct as kpe,d as bLe,dn as u1,dr as vLe,dt as Npe,en as yLe,er as jLe,et as xI,fn as LR,fr as wLe,ft as kLe,g as Wl,gn as hJ,gr as Spe,gt as pJ,h as Fy,hn as Cpe,hr as _pe,ht as lg,i as ZP,in as NLe,ir as SLe,it as fJ,j as rp,jn as CLe,jr as _Le,jt as $R,k as Di,ki as Ipe,kn as ILe,kr as u3,kt as ALe,l as gI,li as TLe,ln as xJ,lr as RLe,lt as ELe,m as NN,mn as gJ,mr as bI,mt as Ape,n as xv,nn as PLe,nr as MLe,o as DLe,oi as LLe,on as Tpe,or as $Le,ot as BS,pn as Rpe,pr as OLe,pt as FLe,q as BLe,qn as Epe,qr as zLe,qt as bJ,rn as Ppe,rr as qLe,rt as vJ,s as Fv,sn as ULe,sr as eM,st as Mpe,t as Bt,tn as Dpe,tr as NL,tt as _f,un as KLe,ur as WLe,ut as VLe,v as HLe,vn as GLe,vr as m3,vt as vI,w as Lpe,wn as $pe,wr as QLe,wt as K8,x as W8,xn as YLe,xr as JLe,xt as XLe,y as yJ,yn as V8,yr as lz,yt as Ope,z as or,zn as SN,zr as ZLe,zt as Fpe}from"./agent-avatar-url-BcyFoVtv.js";import{t as Wc}from"./preload-helper-CceJXRIF.js";import{$ as e$e,A as Qx,At as Bpe,B as Nl,Bt as zpe,C as bp,Ct as t$e,D as s$e,Dt as n$e,E as r$e,Et as a$e,F as Ad,Ft as lb,G as Yx,H as qpe,Ht as ga,I as tM,It as st,K as Y1,L as Ap,Lt as i$e,M as dd,Mt as Zi,N as yI,Nt as o$e,O as Jx,Ot as l$e,P as Tl,Pt as rd,Q as jJ,R as to,Rt as c$e,S as d$e,St as V0,T as jI,Tt as OR,U as h3,Ut as hi,V as wI,Vt as sM,W as Upe,X as p3,Y as u$e,Z as Kpe,_ as m$e,_t as wJ,a as CN,at as h$e,b as f3,bt as kJ,ct as Wpe,d as p$e,dt as yw,et as f$e,f as iy,ft as At,g as x$e,gt as _l,h as g$e,ht as _N,i as b$e,it as Vpe,j as H8,jt as v$e,k as Ih,kt as y$e,l as j$e,lt as w$e,m as Hpe,mt as x3,n as cb,nt as k$e,o as Ln,ot as g2,p as nM,pt as g3,q as N$e,r as Nn,rt as S$e,st as NJ,t as We,tt as SJ,u as G8,ut as C$e,v as wm,vt as _$e,w as vp,wt as I$e,x as Df,xt as oy,y as A$e,yt as SL,z as T$e,zt as ra}from"./router-DesWEj2C.js";import{$ as Q8,$n as Y8,$t as J1,A as $k,An as gm,At as Gpe,B as R$e,Bn as Qpe,Bt as Xw,Cn as Ype,Cr as IN,Ct as ly,D as E$e,Dn as Jpe,Dt as P$e,E as M$e,En as Xpe,Et as D$e,F as L$e,Fn as J8,Ft as Zpe,G as $$e,Gn as O$e,Gt as efe,H as F$e,Hn as B$e,Ht as tfe,I as sfe,In as nfe,It as Ok,J as cz,Jn as kI,Jt as b3,K as z$e,Kn as rfe,Kt as afe,L as q$e,Ln as v3,Lt as U$e,M as AN,Mn as Bv,Mt as TN,N as By,Nn as ife,Nt as K$e,O as yg,On as ph,Ot as Zw,P as W$e,Pn as Fk,Pt as fc,Q as V$e,Qn as X8,Qt as ofe,R as H$e,Rn as G$e,Rt as Q$e,Sn as y3,Sr as yp,St as cy,T as Y$e,Tn as lfe,Tt as J$e,U as X$e,Un as RN,Ut as cfe,V as Z$e,Vn as eOe,Vt as tOe,W as dfe,Wn as rM,Wt as sOe,X as CJ,Xn as nOe,Xt as Kx,Y as ufe,Yn as EN,Yt as mfe,Z as hfe,Zn as pfe,Zt as ek,_ as ffe,_n as j3,_r as jp,_t as rOe,a as aOe,an as _J,ar as PN,at as iOe,b as oOe,bn as lOe,br as w3,bt as NI,c as CL,cn as xfe,cr as Hl,ct as gfe,d as X1,dn as bfe,dr as jg,dt as Au,en as tk,er as vfe,et as yfe,f as jfe,fn as Z8,fr as cOe,ft as dOe,g as IJ,gn as k3,gr as wfe,gt as kfe,h as uOe,hn as Nfe,hr as mOe,ht as hOe,i as pOe,in as AJ,ir as MN,it as SI,j as dz,jn as uz,jt as dc,k as Sfe,kn as Cfe,kt as Px,l as fOe,ln as TJ,lr as RJ,lt as mz,m as N3,mn as S3,mr as xOe,mt as _fe,n as gOe,nn as C3,nr as bOe,nt as vOe,o as yOe,on as jOe,or as sl,ot as wOe,p as Ife,pn as Afe,pr as Tfe,pt as kOe,q as Rfe,qn as DN,qt as Efe,r as cg,rn as _3,rr as Lf,rt as wp,s as EJ,sn as Pfe,sr as nl,st as Mfe,t as e7,tn as Dfe,tr as CI,tt as zy,u as Lfe,un as PJ,ur as Tu,ut as hz,v as _L,vn as NOe,vr as aM,vt as dy,w as $fe,wn as MJ,wt as Z1,x as SOe,xn as Ofe,xr as iM,xt as pz,y as COe,yn as _Oe,yr as Ffe,yt as H0,z as IOe,zn as AOe}from"./RoutineRunVariablesDialog-DCnWm09I.js";import{$ as Bfe,Z as Vn,a as TOe,at as ROe,it as EOe,o as POe,s as MOe}from"./mention-chips-D_n_qKFh.js";import{g as DOe}from"./dist-C42YHTVB.js";import{i as LOe}from"./dist-BCtf-vM2.js";import{t as uc}from"./boxes-tcjFwFpA.js";import{D as $Oe,E as OOe,S as FOe,a as zfe,c as Xr,d as Uc,f as qfe,i as BOe,l as gi,m as G0,o as zOe,p as wg,r as qOe,s as Ufe,t as ud,u as Pu,w as UOe,x as KOe}from"./MarkdownEditor-BOTosEGR.js";import{_ as t7,a as Kfe,b as oM,c as Wfe,d as km,f as Nm,g as Sm,h as Cm,i as e_,l as _m,m as Im,n as WOe,o as kp,p as Am,r as Rh,s as Tm,t as Eh,u as Rm,v as Si,y as mc}from"./sheet-DaK7uiF0.js";import{a as So,c as VOe,i as lM,l as md,n as HOe,o as Co,r as Bl,s as Vfe,t as _r}from"./AgentAvatar-CJxUMdmk.js";import{A as Ed,C as Xa,D as s7,E as n7,O as ea,S as fh,T as r7,_ as a7,a as Qs,b as db,c as xn,d as qy,f as Un,g as ta,h as Kn,i as GOe,j as Ai,k as ua,l as QOe,m as Pd,n as Tn,o as yn,p as Wn,r as Vs,s as mr,t as mi,u as Js,v as sa,w as YOe,x as D0,y as cs}from"./checkbox-I5XQmb-K.js";import{_ as so,c as _I,d as ju,f as LN,g as JOe,h as Mx,i as XOe,l as ZOe,m as $N,n as Uy,o as cM,p as To,s as ui,t as Ws,u as ON,v as dM}from"./label-CZQ8NWbL.js";import{i as Oa,n as xa,r as ld,t as Ii}from"./tabs-De8GZtQI.js";import{a as RC,c as dm,d as yr,f as fz,g as Ir,h as eFe,i as Gr,l as Hfe,m as tFe,n as dg,o as Gfe,p as lr,r as Np,s as Kl,t as Lt,u as zv}from"./agents-DQx-dvSi.js";import{S as Su,a as Qfe,b as io,d as Yfe,f as I3,g as ma,l as Jfe,m as Ul,n as Xfe,o as Zfe,p as exe,t as Wi,u as sFe,v as txe,x as Cc,y as nFe}from"./StatusIcon-mIm27nQw.js";import{a as gl,i as $f,n as ch,r as da,t as Ky}from"./use-adapter-capabilities-BoIn6U4T.js";import{a as Wy,c as um,i as II,n as rFe,o as Cu,r as Fn,s as uM,t as On}from"./EmptyState-BZtI8X0G.js";import{t as Ji}from"./bot-DKL-W8OH.js";import{t as vs}from"./check-CnODEUG9.js";import{t as nn}from"./chevron-down-DFUcku8q.js";import{t as Pn}from"./chevron-right-B6d9r4Ro.js";import{a as aFe,c as Ea,i as Sn,l as FN,n as Pa,o as sxe,r as iFe,s as Ma,t as Da}from"./select-CTeNTKSP.js";import{n as Vc,r as Vi,t as If}from"./save-DDenfr8W.js";import{A as ug,C as xz,D as oFe,_ as nxe,c as lFe,h as cFe,i as dFe,j as la,k as bn,l as v0,n as uFe,o as mFe,p as gz,r as i7,t as L,u as hFe,y as pFe}from"./button-BY21O8GT.js";import{i as Ar,n as ki,r as Po,t as ha}from"./clipboard-DHhOZMRn.js";import{t as qn}from"./external-link-C19HtmzW.js";import{_ as fFe,a as xFe,b as Ph,c as rxe,d as axe,f as gFe,g as bFe,h as Af,i as vFe,l as yFe,m as jFe,n as ixe,o as wFe,p as DJ,r as oxe,s as kFe,t as Rn,u as lxe,v as NFe,y as SFe}from"./MarkdownBody-C_h6YRQp.js";import{t as Wa}from"./file-text-CeE8_Vjy.js";import{a as mM,i as Do,n as CFe,o as cxe,r as AI,t as Zr}from"./heartbeats-DF-m9cYQ.js";import{t as nt}from"./loader-circle-Bq0tfpSr.js";import{n as TI,t as tu}from"./useHiddenSettings-Cx5eN_RQ.js";import{t as Bk}from"./octagon-alert-D4baqyHT.js";import{t as Ni}from"./rotate-ccw-LNlo9y5X.js";import{t as Ds}from"./triangle-alert-6xzP6adj.js";import{n as Fa,t as _Fe}from"./SidebarContext-zupbpsOa.js";import{n as IFe,t as lt}from"./badge-BqqBOTVc.js";import{n as Or,t as Ri}from"./environments-B7NZX_ky.js";import{t as pt}from"./input-B204XBDT.js";import{a as Of,i as RI,n as EI,o as hr,r as kg,t as BN}from"./company-members-Dzwzy-as.js";import{t as su}from"./health-CQndBw_N.js";import{t as gn}from"./skeleton-CLIvalUo.js";import{t as Md}from"./AgentIdentity-D9ti_IEi.js";import{a as AFe,i as Il,n as TFe,o as Xi,r as Qa,s as go,t as sn}from"./card-De_lOmuE.js";import{t as Aa}from"./PageSkeleton-Cy0AuFsD.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 RFe=class extends LLe{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:xLe(s,n.data),hasPreviousPage:TLe(s,n.data),isFetchNextPageError:u,isFetchingNextPage:h,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!u&&!p,isRefetching:o&&!h&&!f}}};function ub(e,s){return lLe(e,RFe,s)}r(ub,"useInfiniteQuery");var EFe="adapter_auth_missing",PFe="document",MFe=80,DFe={markdown:"md",html:"html",json:"json",text:"txt"};function LFe(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,MFe).replace(/-+$/g,"")||PFe}r(LFe,"documentExportSlug");function $Fe(e){return DFe[(e??"").trim().toLowerCase()]??"md"}r($Fe,"documentExportExtension");function LJ(e,s){const n=s.replace(/^\.+/,"").toLowerCase()||"md";return`${LFe(e)}.${n}`}r(LJ,"documentExportFileName");function bz(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(bz,"decisionEffectTargetIssueIds");var OFe=new Set(["terminated","pending_approval","paused"]),FFe=new Set(["active","idle","running","error"]);function BFe(e){return FFe.has(e)&&!OFe.has(e)}r(BFe,"isAgentStatusInvokable");function zS(e){return e==="done"||e==="cancelled"}r(zS,"isPipelineTerminalStageKind");function dxe(e){const s={};for(const n of e)(s[n.stageId]??=[]).push(n);return s}r(dxe,"groupWarningsByStage");function uxe(e){return e==="RESPONSIBLE_USER_UNAUTHORIZED"||e==="RESPONSIBLE_USER_UNAVAILABLE"}r(uxe,"isResponsibleUserDenialCode");function PI(e){const s=e?.trim();return s&&s.length>0?s:"the responsible user"}r(PI,"responsibleUserLabel");function vz(e,s={}){const n=PI(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(vz,"describeResponsibleUserDenial");var zFe=["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 qFe(e){const s=e?.trim();return s&&s.length>0?s:"this task"}r(qFe,"issueLabel$2");function UFe(e){const s=e?.trim();return s&&s.length>0?s:"the current assignee"}r(UFe,"assigneeLabel");function KFe(e){const s=e?.trim();return s&&s.length>0?s:"this agent"}r(KFe,"actorLabel$1");var WFe="create a child issue with the request in its description (issue creation is a separate, open write path) and let its assignee act";function VFe(e,s={}){const n=qFe(s.issueIdentifier),a=KFe(s.actorLabel),i=UFe(s.assigneeLabel),o=PI(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 ${WFe}.`};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=vz("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=vz("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(VFe,"describeIssueWriteDenial");function mxe(e){return(typeof e=="string"?e:e?.name??"").trim()}r(mxe,"rawNameOf");function hxe(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(hxe,"looksLikeNetworkAddress");function yz(e){return e.split(/[\s._-]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}r(yz,"titleCaseIdentifier");function HFe(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,""),yz(n)||"Custom app"}r(HFe,"pluginPackageLabel");function Ff(e,s={}){const n=s.title?.trim();if(n)return n;const a=mxe(e);if(!a||hxe(a))return"Custom app";const i=HFe(a);if(i)return i;if(a.includes(":")&&!a.includes("://")){const o=a.slice(a.lastIndexOf(":")+1).trim();if(o)return yz(o)}return/\s/.test(a)||/[A-Z]/.test(a)?a:/[._-]/.test(a)?yz(a):a}r(Ff,"humanizeConnectionDisplayName");function $J(e){const s=mxe(e);return s&&hxe(s)?`hosted at ${s}`:null}r($J,"connectionDisplaySecondaryHint");var OJ=`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 bnt(){const e=new Blob([gnt],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(bnt,"createSandboxedWorker");var Oq=new Map,v5=new Map,rE=new Set,aE=new Map,BNe=null;function vnt(e){BNe=e}r(vnt,"setDynamicParserResultNotifier");function zNe(e,s){e.worker.postMessage(s)}r(zNe,"sendToWorker");function ynt(e){return e.nextId++}r(ynt,"nextRequestId");function jnt(e,s){return`${s}\0${e}`}r(jnt,"lineCacheKey");function wnt(){BNe?.()}r(wnt,"notifyResultReady");function knt(e,s,n){return new Promise(a=>{const i=ynt(e);e.pendingResolves.set(i,a),zNe(e,{type:"parse",id:i,line:s,ts:n})})}r(knt,"parseLineAsync");function FC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(FC,"drainPendingRequests");function Nnt(e){return new Promise((s,n)=>{const a=bnt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{FC(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"&&FC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),FC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),FC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},zNe(i,{type:"init",source:e})})}r(Nnt,"initSandboxedWorker");function Snt(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=jnt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),knt(e,i,o).then(d=>{n.delete(l),s.set(l,d),wnt()})),[])},"parseStdoutLine")}}r(Snt,"buildParserModule");async function Fq(e){const s=v5.get(e);if(s)return s;if(rE.has(e))return null;const n=aE.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 rE.add(e),null;const o=await Nnt(await i.text());Oq.set(e,o);const l=Snt(o);return v5.set(e,l),l}catch{return rE.add(e),null}finally{aE.delete(e)}})();return aE.set(e,a),a}r(Fq,"loadDynamicParser");function Bq(e){const s=v5.has(e);v5.delete(e),rE.delete(e),aE.delete(e);const n=Oq.get(e);return n&&(FC(n),n.worker.terminate(),Oq.delete(e)),s}r(Bq,"invalidateDynamicParser");var iE=[],JM=new Map,zq=new Set,qNe=new Map,T$=new Set,M2=new Map,qq=new Set;function UNe(e){return qq.add(e),()=>qq.delete(e)}r(UNe,"onAdapterChange");function KNe(){for(const e of qq)e()}r(KNe,"notifyAdapterChange");vnt(KNe);function Cnt(){for(const e of[det,ket,Uet,Qet,btt,Rtt,Utt,Xtt,cst,vst,Ust,Lst,ltt,ant,b5,xnt])zq.add(e.type),qNe.set(e.type,e),vv(e)}r(Cnt,"registerBuiltInUIAdapters");function vv(e){const s=iE.findIndex(n=>n.type===e.type);s>=0?iE.splice(s,1,e):iE.push(e),JM.set(e.type,e),KNe()}r(vv,"registerUIAdapter");function WNe(e){return JM.get(e)??null}r(WNe,"findUIAdapter");Cnt();function tS(e){const s=JM.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Fq(e).then(o=>{o&&vv({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:vy,buildAdapterConfig:Xk})})),b5.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:vy,buildAdapterConfig:Xk}}return s}r(tS,"getUIAdapter");function _nt(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=qNe.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=T$.has(a);if(o&&l&&!c){T$.add(a);const d=(M2.get(a)??0)+1;M2.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;vv({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Fq(a).then(b=>{b&&M2.get(a)===d&&vv({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&&(T$.delete(a),M2.delete(a),Bq(a),vv(i))}for(const{type:a,label:i}of e){if(zq.has(a))continue;const o=JM.get(a);if(o&&o!==b5)continue;let l=!1;const c=o?.parseStdoutLine??b5.parseStdoutLine;vv({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Fq(a).then(h=>{h&&vv({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??vy,buildAdapterConfig:o?.buildAdapterConfig??Xk})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??vy,buildAdapterConfig:o?.buildAdapterConfig??Xk})}}r(_nt,"syncExternalAdapters");function hW(){return[...iE]}r(hW,"listUIAdapters");function Uq(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(Uq,"resolveStdoutParser");function VNe(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(VNe,"appendTranscriptEntry");function Int(e,s){for(const n of s)VNe(e,n)}r(Int,"appendTranscriptEntries");function Ant(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(Ant,"truncateTranscriptLine");function Tnt(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(Tnt,"formatTranscriptParserError");function Rnt(e,s,n,a){const i=Tnt(n)||"unknown parser error",o=Ant(e);return{kind:"result",ts:s,text:lm(`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(Rnt,"createTranscriptParseErrorEntry");function pW(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{Int(s,i(n,a).map(c=>TXe(c,l)))}catch(c){o?.(),VNe(s,Rnt(n,a,c,l))}}r(pW,"appendParsedTranscriptLine");function HNe(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:lm(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:lm(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&&pW({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(HNe,"foldTranscriptChunks");function GNe(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=Uq(s),c=HNe({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&pW({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(GNe,"buildTranscript");var xte=[];function Ent(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=Uq(e),o=[],l="",c=xte,d=[];const u=r(()=>{i=Uq(e),o=[],l="",c=xte},"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 GNe(f,e,s);const b=o.slice(),v=b.length-1;return v>=0&&(b[v]={...b[v]}),x&&pW({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=HNe({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(Ent,"createIncrementalTranscript");function Pnt({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)(yr,{open:c,onOpenChange:d,children:[(0,t.jsx)(Ir,{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)(Uc,{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)(_r,{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)(Uc,{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)(lr,{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)(_r,{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)(_r,{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:lW[b.role]??b.role})]},b.id))]})]})}r(Pnt,"ReportsToPicker");var Mnt="__secret_folder__:";function Dnt(e){return!e||e==="active"?null:(0,t.jsx)(lt,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(Dnt,"statusBadge");function QNe(e){return e.split("/").filter(s=>s.length>0)}r(QNe,"splitSecretPath$1");function oE(e){return e.join("/")}r(oE,"pathKey$1");function GS(e){return e.length>0?`/${e.join("/")}`:"/"}r(GS,"pathLabel");function Lnt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(Lnt,"pathStartsWith");function gte(e){return`${Mnt}${oE(e)}`}r(gte,"folderValue");function $nt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=QNe(c.name);if(Lnt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=oE(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=GS(u);i.set(h,{key:`folder-${h||"root"}`,value:gte(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-${oE(s)}`,value:gte(c),label:"Up one folder",title:GS(c),searchText:GS(c),kind:"back",folderPath:oE(c),pathHint:GS(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?GS(s):"Browse secrets",options:l}}r($nt,"buildFolderGroup");function fW({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=>QNe(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||XOe(j))return N;const w=$nt(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)(Uy,{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)(ki,{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)(ki,{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"?dze:Kl;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)(ki,{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]}),Dnt(j.status)]})},"renderOption"),createItem:o?{render:r(j=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(bn,{className:"size-3.5 shrink-0"}),j.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",j.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(j=>o(j),"onSelect")}:void 0})}r(fW,"SecretPicker");var Ont=/^[a-z][a-z0-9_]*$/,bte="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 YNe({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?Ont.test(w)?a?.some(R=>R.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(R){v(R instanceof Error?R.message:"Failed to create secret"),x(!1)}}}r(I,"handleSubmit");const T=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)(eFe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(tFe,{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(bte,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(R=>c(R.target.value),"onChange"),onBlur:r(()=>N(!0),"onBlur"),onKeyDown:r(R=>{R.key==="Enter"&&(R.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(bte,"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"?R=>u(R.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(R=>!R),"onClick"),children:h?(0,t.jsx)(Em,{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)(nt,{className:"h-3.5 w-3.5 animate-spin"}):null,T]})]})]})}r(YNe,"SecretPopoverForm");function JNe(e){return(0,t.jsx)(YNe,{mode:"create",...e})}r(JNe,"CreateSecretPopover");function Fnt(e){return(0,t.jsx)(YNe,{mode:"store",...e})}r(Fnt,"ConvertToSecretPopover");var Bnt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,znt=[/^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 qnt(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(qnt,"looksHighEntropy");function Unt(e,s){return s?Bnt.test(e)||znt.some(n=>n.test(s))?!0:qnt(s):!1}r(Unt,"isSensitiveEnv");var vte=0;function Knt(){return vte+=1,`env-row-${vte}`}r(Knt,"nextRowId");function Ox(e="text"){return{id:Knt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Ox,"emptyRow");function Wnt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(Wnt,"isSecretRef");function Vnt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(Vnt,"isPlainObj");function Hnt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(Hnt,"isUserSecretRef");function R$(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Ox(),name:s,textValue:n};if(Wnt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Ox(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(Hnt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Ox(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return Vnt(n)?{...Ox(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Ox(),name:s}})}r(R$,"rowsFromValue");function lE(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(lE,"valueFromRows");var yte="CLAUDE_CODE_OAUTH_TOKEN";function Bw(){return lE([{...Ox("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(Bw,"buildFixedClaudeOAuthBinding");var Gnt=/^[A-Za-z_][A-Za-z0-9_]*$/;function Qnt(e,s,n){const a=e.trim();if(!a)return null;if(!Gnt.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(Qnt,"validateName");function Ynt(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(Ynt,"computeDuplicateNames");function Jnt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:y5(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(Jnt,"planSourceSwitch");function XNe(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(XNe,"computeRowHealth");function ZNe(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(ZNe,"computeUserSecretRowHealth");function y5(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(y5,"secretNameFromKey");function N1(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(N1,"envKeyFromSecretName");var Xnt="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",jte="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function Znt({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),[T,R]=(0,m.useState)(!1),[A,D]=(0,m.useState)(null),M=XNe(e,n)??ZNe(e,a),$=e.source==="secret"?n.find(Z=>Z.id===e.secretId)??null:null,E=(a?.length??0)>0,B=e.source==="text"&&!e.sensitiveDismissed&&Unt(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 Z=window.setTimeout(()=>D(null),5e3);return()=>window.clearTimeout(Z)},[A]);function z(Z){if(Z==="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=Jnt(e,Z);switch(re.kind){case"noop":return;case"open-store":{const{name:ce,value:H}=re;window.setTimeout(()=>I({mode:"store",name:ce,value:H}),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(z,"switchSource");async function q(Z,re){const ce=await b(Z,re);u({source:"secret",secretId:ce.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${ce.name} created`),I(null)}r(q,"submitSecretPopover");function U(){const Z=y5(e.name)||"secret",{textValue:re}=e;window.setTimeout(()=>I({mode:"store",name:Z,value:re}),0)}r(U,"openStoreAsSecret");const F=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",K=`${e.id}-name-error`,G=`${e.id}-health`,se=d.name||d.value,ee=$?Math.max(0,$.latestVersion):0,ne=e.version==="latest"?"latest":`v${e.version}`,he=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",se&&"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(Xnt,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(Z=>u({name:Z.target.value}),"onChange"),onBlur:p,onPaste:r(Z=>{e.name||f(Z.clipboardData.getData("text"))&&Z.preventDefault()},"onPaste"),onKeyDown:r(Z=>{Z.key==="Enter"&&(Z.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)(yr,{open:C!==null,onOpenChange:r(Z=>{Z||I(null)},"onOpenChange"),children:[(0,t.jsx)(fz,{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)(ta,{children:[(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)(ea,{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)(Wze,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(ki,{className:"size-3.5"}):(0,t.jsx)(Th,{className:"size-3.5"}),(0,t.jsx)(nn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(Wn,{side:"top",children:F})]}),(0,t.jsxs)(sa,{align:"start",className:"w-56",children:[(0,t.jsxs)(cs,{className:"flex-col items-start gap-0.5",onSelect:r(()=>z("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)(cs,{className:"flex-col items-start gap-0.5",onSelect:r(()=>z("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)(cs,{className:"flex-col items-start gap-0.5",onSelect:r(()=>z("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:jte,placeholder:"value",value:e.textValue,type:B?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(Z=>u({textValue:Z.target.value}),"onChange"),onKeyDown:r(Z=>{Z.key==="Enter"&&s&&(Z.preventDefault(),x())},"onKeyDown")}),B?(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)(hc,{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)(Vn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(fW,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(Z=>u({secretId:Z,version:"latest"}),"onSelect"),onCreateNew:r(Z=>I({mode:"create",name:y5(Z)||Z.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",$&&$.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),$&&$.status==="active"?(0,t.jsxs)(yr,{open:T,onOpenChange:R,children:[(0,t.jsx)(fz,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(Z=>{Z.preventDefault(),Z.stopPropagation(),R(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",he?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:ne})}),(0,t.jsxs)(lr,{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"}),R(!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:ee},(Z,re)=>ee-re).filter(Z=>Z>0).map(Z=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===Z,onClick:r(()=>{u({version:Z}),R(!1)},"onClick"),className:W("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===Z&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",Z]},Z))]})]}):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(Z=>{const re=Z.target.value,ce=a?.find(H=>H.key===re);u({userSecretKey:re,...ce&&!e.name.trim()?{name:ce.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(Z=>Z.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(Z=>(0,t.jsxs)("option",{value:Z.key,children:[Z.name,Z.status!=="active"?` (${Z.status})`:""]},Z.id))]}):(0,t.jsx)("input",{className:jte,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(Z=>u({userSecretKey:Z.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(Z=>u({required:Z.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)(lr,{align:"start",className:"w-auto p-3",onInteractOutside:r(Z=>{const re=Z.detail.originalEvent.target;re&&S.current?.contains(re)&&Z.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(Fnt,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(Z=>Z.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):C?.mode==="create"?(0,t.jsx)(JNe,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(Z=>Z.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):null})]}),M?(0,t.jsx)("p",{id:G,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"&&!B&&(e.name.trim()||e.textValue)?(0,t.jsxs)(ta,{children:[(0,t.jsx)(ea,{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)(Ai,{className:"size-4"})})}),(0,t.jsx)(sa,{align:"end",children:(0,t.jsx)(cs,{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)(Vn,{className:"size-4"})})]})]})}r(Znt,"EnvironmentVariableRow");var ert=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function trt(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(trt,"stripInlineComment");function srt(e){const s=e.trim();if(s.length>=2){const n=s[0],a=s[s.length-1];if(n==='"'&&a==='"'||n==="'"&&a==="'")return s.slice(1,-1)}return trt(s).trim()}r(srt,"unquote");function nrt(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=ert.exec(a);if(!i)continue;const o=i[1],l=srt(i[2]);s.push({key:o,value:l})}return s}r(nrt,"parseDotenv");var rrt=["PAPERCLIP_"],art="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 Kq(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(Kq,"normalizedEnvEntries");function QS(e){return JSON.stringify(Kq(e))}r(QS,"normalizedEnvKey");var E$=3;function P$(e){const s=e.slice(0,E$).join(", ");return e.length>E$?`${s} +${e.length-E$} more`:s}r(P$,"formatChangedNames");function wte(e){return e.map(s=>({...s}))}r(wte,"cloneRows");function irt(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(irt,"rowDirtyFields");var yy=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=rrt,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=Gc(),b=(0,m.useRef)(null),[v,j]=(0,m.useState)(()=>R$(s)),N=(0,m.useRef)(v),[w,k]=(0,m.useState)(()=>wte(v)),S=(0,m.useMemo)(()=>QS(s),[]),C=(0,m.useRef)(S),I=(0,m.useRef)(S),T=(0,m.useRef)(null),[R,A]=(0,m.useState)(S),[D,M]=(0,m.useState)(()=>new Set(R$(s).map(le=>le.name.trim()).filter(Boolean))),[$,E]=(0,m.useState)(null);(0,m.useEffect)(()=>{N.current=v},[v]);function B(le,ue=N.current){C.current=le,A(le),k(wte(ue))}r(B,"markCommitted");function z(le){M(ue=>{const Se=new Set(ue);for(const ye of le){const Ie=ye.name.trim();Ie&&Se.add(Ie)}return Se})}r(z,"touchCommittedNames");function q(le){const ue=R$(le);return j(ue),z(ue),ue}r(q,"adoptExternalValue"),(0,m.useEffect)(()=>{const le=QS(s);if(le===I.current)return;I.current=le;const ue=QS(lE(N.current)),Se=ue!==C.current,ye=T.current===le;if(ye&&(T.current=null),!Se){B(le,q(s));return}(ye||ue===le)&&(z(N.current),B(le))},[s]);const U=(0,m.useMemo)(()=>lE(v),[v]),F=(0,m.useMemo)(()=>QS(U),[U]),K=F!==R;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const G=(0,m.useMemo)(()=>{const le=new Map(Kq(lE(w)).map(([Ie,Ke])=>[Ie,JSON.stringify(Ke)])),ue=new Map(Kq(U).map(([Ie,Ke])=>[Ie,JSON.stringify(Ke)])),Se=[],ye=[];for(const[Ie,Ke]of ue)le.has(Ie)?le.get(Ie)!==Ke&&ye.push(Ie):Se.push(Ie);return{added:Se,changed:ye,removed:[...le.keys()].filter(Ie=>!ue.has(Ie))}},[w,U]),se=(0,m.useMemo)(()=>{const le=[];return G.added.length>0&&le.push(`New: ${P$(G.added)}`),G.changed.length>0&&le.push(`Edited: ${P$(G.changed)}`),G.removed.length>0&&le.push(`Removed: ${P$(G.removed)}`),le.join(" · ")},[G]);(0,m.useEffect)(()=>{if(c||!K)return;function le(ue){ue.preventDefault(),ue.returnValue=""}return r(le,"handleBeforeUnload"),window.addEventListener("beforeunload",le),()=>window.removeEventListener("beforeunload",le)},[c,K]);const ee=(0,m.useCallback)(()=>c||!K?null:(T.current=F,(0,up.flushSync)(()=>{n(U)}),U??{}),[c,U,F,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:ee}),[ee]),(0,m.useEffect)(()=>{const le=b.current?.closest("form");if(!le)return;function ue(){ee()}return r(ue,"handleSubmit"),le.addEventListener("submit",ue,!0),()=>le.removeEventListener("submit",ue,!0)},[ee]),(0,m.useEffect)(()=>{const le=b.current;if(!le)return;const ue=le;function Se(ye){const Ie=ye.target;if(!(Ie instanceof Element)||ue.contains(Ie))return;const Ke=Ie.closest("button");if(!Ke||Ke.disabled)return;const rt=`${Ke.getAttribute("aria-label")??""} ${Ke.textContent??""}`;(Ke.type==="submit"||/\b(save|create|update|test|import)\b/i.test(rt))&&ee()}return r(Se,"handleDocumentClick"),document.addEventListener("click",Se,!0),()=>document.removeEventListener("click",Se,!0)},[ee]);function ne(le){j(le)}r(ne,"updateDraft");function he(le,ue){ne(v.map(Se=>Se.id===le?{...Se,...ue}:Se))}r(he,"patchRow");function Z(le){ne(v.filter(ue=>ue.id!==le))}r(Z,"removeRow");function re(){const le=Ox();j([...v,le]),E({rowId:le.id,field:"name"})}r(re,"addRow");function ce(le){const ue=v.find(Se=>Se.id===le)?.name.trim();ue&&M(Se=>{if(Se.has(ue))return Se;const ye=new Set(Se);return ye.add(ue),ye})}r(ce,"markTouched");function H(le,ue){const Se=nrt(le);if(Se.length===0)return!1;const ye=v.filter(Ie=>Ie.id!==ue).map(Ie=>({...Ie}));for(const{key:Ie,value:Ke}of Se){const rt=ye.find(dt=>dt.name.trim()===Ie);rt?(rt.name=Ie,rt.source="text",rt.textValue=Ke,rt.secretId="",rt.sensitiveDismissed=!1,rt.userSecretKey="",rt.required=!0):ye.push({...Ox(),name:Ie,textValue:Ke})}return ne(ye),x?.pushToast({title:`Imported ${Se.length} variable${Se.length===1?"":"s"}`,tone:"success"}),!0}r(H,"bulkImport");function Q(le){const ue=v.map(Ie=>({...Ie})),Se=ue[ue.length-1];let ye;Se&&!Se.name&&!Se.textValue&&!Se.secretId&&!Se.userSecretKey?ye=Se:(ye=Ox(),ue.push(ye)),ye.source="secret",ye.secretId=le.id,ye.version="latest",ye.name||(ye.name=N1(le.name)),ne(ue)}r(Q,"bindRecentSecret");function Y(){K&&(T.current=F,n(U))}r(Y,"saveDraft");function te(){T.current=null,I.current=QS(s);const le=q(s);B(I.current,le)}r(te,"revertDraft");const ae=(0,m.useMemo)(()=>Ynt(v),[v]),me=(0,m.useMemo)(()=>v.reduce((le,ue)=>XNe(ue,a)||ZNe(ue,i)?le+1:le,0),[v,a,i]),oe=(0,m.useMemo)(()=>{const le=new Set(v.filter(ue=>ue.source==="secret"&&ue.secretId).map(ue=>ue.secretId));return(l??[]).filter(ue=>ue.status==="active"&&!le.has(ue.id)).slice(0,8)},[l,v]),ie=v.length>0,ge=u===void 0?art:u,be=(0,m.useMemo)(()=>new Map(w.map(le=>[le.id,le])),[w]);return(0,t.jsx)(Pd,{children:(0,t.jsxs)("div",{ref:b,className:"@container/env space-y-2",children:[me>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)(Vi,{className:"size-3.5"}),me," bindings need attention"]}):null,ie?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-(--gtc-14)",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Value"}),(0,t.jsx)("span",{})]}),v.map((le,ue)=>{const Se=Qnt(le.name,ae,d),ye=D.has(le.name.trim());return(0,t.jsx)(Znt,{row:le,isLast:ue===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:Se,showNameIssue:ye,dirtyFields:irt(le,be.get(le.id)),onPatch:r(Ie=>he(le.id,Ie),"onPatch"),onRemove:r(()=>Z(le.id),"onRemove"),onNameBlur:r(()=>ce(le.id),"onNameBlur"),onNamePaste:r(Ie=>H(Ie,le.id),"onNamePaste"),onEnterInValueLast:re,onCreateSecret:o,onToast:r(Ie=>x?.pushToast({title:Ie,tone:"success"}),"onToast"),focusRequest:$?.rowId===le.id?$.field:null,onFocusConsumed:r(()=>E(null),"onFocusConsumed")},le.id)})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No environment variables"}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[(0,t.jsxs)("button",{type:"button",onClick: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)(bn,{className:"size-3.5"}),"Add variable"]}),oe.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)(ki,{className:"size-3"}),"Recently used:"]}),oe.map(le=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>Q(le),"onClick"),className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",title:`Bind ${le.name}`,children:["+ ",le.name]},le.id))]}):null]}),K&&!c&&!p?(0,t.jsxs)("div",{role:"status",className:"mt-3 flex w-full flex-col gap-3 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-3 text-amber-950 shadow-sm dark:bg-amber-500/15 dark:text-amber-100 @[34rem]/env:flex-row @[34rem]/env:items-center @[34rem]/env:justify-between",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)("span",{className:"size-2 rounded-full bg-amber-500 shadow-(--shadow-extract-13)"}),(0,t.jsx)("span",{children:"Unsaved changes"})]}),se?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:se,children:se}):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)(Ni,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Y,className:"inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90",children:[(0,t.jsx)(If,{className:"size-4"}),"Save"]})]})]}):null,ge?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ge}):null,v.some(le=>le.source==="user_secret"&&le.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Th,{className:"mt-0.5 size-3 shrink-0"}),(0,t.jsx)("span",{children:"User secrets resolve from the user responsible for the run. Required bindings fail until that user sets their value under Secrets → My secrets."})]}):null]})})},"EnvironmentVariablesEditor")),ort="env.",sA="access.",Wq=/^[A-Za-z_][A-Za-z0-9_]*$/;function eSe(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(eSe,"deliveryModeForConfigPath");function tSe(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(tSe,"deliveryModeLabel");function lrt(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(lrt,"deliveryModeDescription");function sSe(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(sSe,"aliasFromConfigPath");function crt(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(crt,"consumerTypeLabel");var drt={numeric:!0,sensitivity:"base"};function BC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(BC,"getSecretPathRowName");function sN(e){return e.split("/").filter(s=>s.length>0)}r(sN,"splitSecretPath");function M$(e){return sN(e).join("/")}r(M$,"normalizeSecretPath");function kte(e,s){return s.every((n,a)=>e[a]===n)}r(kte,"startsWithSegments");function Nte(e,s){return e.localeCompare(s,void 0,drt)}r(Nte,"compareNames");function urt(e,s){const n=sN(s),a=e.map(c=>({row:c,name:BC(c),segments:sN(BC(c))})),i=new Set,o=[];for(const c of a){if(!kte(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(!kte(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)=>Nte(c.name,d.name)),o.sort((c,d)=>Nte(BC(c),BC(d))),{folders:l,secrets:o}}r(urt,"buildSecretPathListing");function mrt(e){const s=sN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(mrt,"buildSecretPathBreadcrumbs");function hrt(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(hrt,"validateSecretFolderSegment");function I_({name:e,basePath:s="",className:n,leafClassName:a}){const i=sN(e),o=sN(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(I_,"SecretPathName");function prt(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(prt,"fingerprintLabel");function nSe({fingerprint:e,length:s,className:n}){const{pushToast:a}=pa(),i=prt(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(Cz,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{ha(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)(Cz,{className:"size-3 shrink-0"}),i,(0,t.jsx)(Ar,{className:"size-3 shrink-0 opacity-60"})]})}r(nSe,"FingerprintChip");function xW({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(xW,"ProposalJustification");function A_({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)(_r,{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(A_,"AgentRefChip");function gW({configPath:e}){const s=eSe(e),n=s==="env",a=s==="api";return(0,t.jsxs)(lt,{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)(gve,{className:"size-3"}):a?(0,t.jsx)(bM,{className:"size-3"}):null,tSe(s)]})}r(gW,"DeliveryBadge$1");function bW({className:e}){return(0,t.jsxs)(lt,{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)(hc,{className:"size-3"})," Proposed"]})}r(bW,"ProposedBadge");function XM(e){return sSe(e.configPath)}r(XM,"bindingEnvKey");function vW(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(vW,"bindingSecretLabel");function Ste(e){return e instanceof un?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Ste,"readableError");function rSe(e,s=[]){const n=Mt(),{pushToast:a}=pa(),[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 Sr.approveProposal(e,k.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return Sr.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"} · ${XM(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Ste(w)),"onError")}),b=je({mutationFn:r(({proposal:w,reason:k})=>Sr.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(Ste(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)(frt,{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)(grt,{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(rSe,"useProposalReview");function frt({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)(Vs,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Qs,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(yn,{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)(A_,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(xW,{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)(Ws,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(pt,{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)(Ws,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(pt,{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)(I_,{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)(Ws,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(pt,{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)(Ws,{htmlFor:"approve-provider-config",children:"Provider vault"}),(0,t.jsxs)("select",{id:"approve-provider-config",value:e.providerConfigId,onChange:r(p=>i({...e,providerConfigId:p.target.value}),"onChange"),className:"h-9 w-full rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",children:[(0,t.jsx)("option",{value:"",children:"Deployment default"}),u.map(p=>(0,t.jsx)("option",{value:p.id,children:p.displayName},p.id))]})]}):null,(0,t.jsx)("div",{className:"rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-muted-foreground",children:(0,t.jsx)(nSe,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(xrt,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(mr,{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(frt,"ApproveDialog");function xrt({draft:e,onChange:s}){const{proposal:n}=e,a=vW(n),i=XM(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)(A_,{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)(gW,{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)(ki,{className:"size-3.5 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:a.name}),a.pending?(0,t.jsx)(bW,{}):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)(mi,{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(xrt,"BindingApproveBody");function grt({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(Vs,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Qs,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Reject proposal"}),(0,t.jsxs)(yn,{children:["The reason is sent back to"," ",(0,t.jsx)(A_,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Ws,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Tn,{id:"reject-reason",value:s,onChange:r(d=>i(d.target.value),"onChange"),rows:3,autoFocus:!0,placeholder:"Why is this being rejected?"})]}),n?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:n}):null,(0,t.jsxs)(mr,{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(grt,"RejectDialog");function aSe({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)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)(Wn,{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(aSe,"ProposalActions");function iSe(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(iSe,"asRecord$16");function oSe(e){const s=iSe(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(oSe,"readSecretRef");function brt(e){const s=iSe(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=oSe(i);o&&n.push({name:a,...o})}return n}r(brt,"parseEnvSecretRefs");function vrt(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=oSe(a);i&&s.push({name:n.slice(sA.length),...i})}return s}r(vrt,"parseAccessGrants");function yrt(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(yrt,"summarizeAgentBindings");var Cte=0;function lSe(){return Cte+=1,`access-row-${Cte}`}r(lSe,"nextAccessRowId");function D$(e){return e.map(s=>({id:lSe(),alias:s.name,secretId:s.secretId,version:s.version}))}r(D$,"entriesToRows");function _te(e){const s={};for(const n of e){const a=n.alias.trim();!a||!Wq.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(_te,"rowsToAccessMap");function Ite(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(Ite,"normalizeAccessMapKey");function Ate({mode:e}){return e==="env"?(0,t.jsxs)(lt,{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)(gve,{className:"size-3"})," Env var"]}):(0,t.jsxs)(lt,{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)(bM,{className:"size-3"})," API access"]})}r(Ate,"DeliveryBadge");function jrt({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter($=>$.kind==="binding"),[o]),u=(0,m.useMemo)(()=>brt(e),[e]),h=(0,m.useMemo)(()=>vrt(e),[e]),p=(0,m.useMemo)(()=>yrt(u,h),[u,h]),f=(0,m.useMemo)(()=>_te(D$(h)),[h]),x=(0,m.useMemo)(()=>Ite(f),[f]),[b,v]=(0,m.useState)(()=>D$(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(D$(h)))},[x,h]);const C=r($=>s.find(E=>E.id===$)?.name??`${$.slice(0,8)}…`,"secretName");function I($){v($);const E=_te($);k.current=Ite(E),n(E)}r(I,"emit");function T($,E){I(b.map(B=>B.id===$?{...B,...E}:B))}r(T,"patchRow");function R($){I(b.filter(E=>E.id!==$))}r(R,"removeRow");function A(){v($=>[...$,{id:lSe(),alias:"",secretId:"",version:"latest"}])}r(A,"addRow");const D=(0,m.useMemo)(()=>{const $=new Map;for(const E of b){const B=E.alias.trim();B&&$.set(B,($.get(B)??0)+1)}return $},[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($=>(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)(ki,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:C($.secretId)}),$.envKeys.length>0?(0,t.jsx)(Ate,{mode:"env"}):null,$.apiAliases.length>0?(0,t.jsx)(Ate,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...$.envKeys.map(E=>`${ort}${E}`),...$.apiAliases.map(E=>`${sA}${E}`)].join(" · ")})]},$.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($=>{const E=vW($),B=XM($);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)(gW,{configPath:$.configPath}),(0,t.jsx)("code",{className:"font-mono",children:B||$.configPath}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"→"}),(0,t.jsx)(ki,{className:"size-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:E.name}),E.pending?(0,t.jsx)(bW,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",$.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",$.justification,"”"]})]})]}),(0,t.jsx)(aSe,{proposal:$,onApprove:l,onReject:c,disabled:i,size:"xs"})]},$.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($=>{const E=$.alias.trim(),B=!!E&&!Wq.test(E),z=!!E&&(D.get(E)??0)>1,q=s.find(U=>U.id===$.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)(pt,{value:$.alias,onChange:r(U=>T($.id,{alias:U.target.value}),"onChange"),onBlur:r(U=>{const F=U.target.value.trim();if(F&&!Wq.test(F)){const K=N1(F);K&&K!==F&&T($.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(B||z)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(yr,{open:j?.rowId===$.id,onOpenChange:r(U=>{!U&&j?.rowId===$.id&&N(null)},"onOpenChange"),children:[(0,t.jsx)(fz,{asChild:!0,children:(0,t.jsx)("div",{ref:r(U=>{U?w.current.set($.id,U):w.current.delete($.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(fW,{secretId:$.secretId,secrets:s,onSelect:r(U=>T($.id,{secretId:U,version:"latest",alias:!$.alias.trim()&&U?N1(C(U)):$.alias}),"onSelect"),onCreateNew:a?U=>{window.setTimeout(()=>{N({rowId:$.id,name:y5(U)||U.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(lr,{align:"start",className:"w-auto p-3",onInteractOutside:r(U=>{const F=U.detail.originalEvent.target;F&&w.current.get($.id)?.contains(F)&&U.preventDefault()},"onInteractOutside"),children:j?.rowId===$.id&&a?(0,t.jsx)(JNe,{initialName:j.name,initialValue:"",existingSecretNames:s.map(U=>U.name),onCancel:r(()=>N(null),"onCancel"),onSubmit:r(async(U,F)=>{const K=await a(U,F);T($.id,{secretId:K.id,version:"latest",alias:$.alias.trim()||N1(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:$.version===void 0?"latest":String($.version),onChange:r(U=>{const F=U.target.value;T($.id,{version:F==="latest"?"latest":Number.parseInt(F,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,F)=>{const K=q.latestVersion-F;return K<=0?null:(0,t.jsxs)("option",{value:K,children:["v",K]},K)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>R($.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)(ua,{className:"size-3.5"})})]}),B?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):z?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},$.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)(bn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[lrt("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(jrt,"AgentSecretAccessEditor");function wrt(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(wrt,"asNonEmptyString$3");function krt(e){return wrt(e)!==null}r(krt,"hasLegacyWorkingDirectory");function Nrt(e){return e.isCreate?!1:krt(e.adapterConfig?.cwd)}r(Nrt,"shouldShowLegacyWorkingDirectoryField");var cSe=new Set;function Srt(e){return cSe.has(e)}r(Srt,"isAdapterTypeHidden");function Crt(e){cSe=new Set(e)}r(Crt,"setDisabledAdapterTypes");function _rt(e){return!Nh(e).hideFromVisualSelection}r(_rt,"isVisualAdapterChoice");function dSe(e,s=hW()){const n=e??qf;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Nh(a.type).comingSoon,hidden:Srt(a.type),experimental:!!Nh(a.type).experimental}))}r(dSe,"listAdapterOptions");function uSe(e={}){const s=e.enabled??!0,{data:n}=X({queryKey:P.adapters.all,queryFn:r(()=>ch.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&_nt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&Crt(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(uSe,"useDisabledAdaptersSync");function Irt(e={}){const s=e.enabled??!0,{data:n}=X({queryKey:P.adapters.all,queryFn:r(()=>ch.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(Irt,"useAdapterRegistryLoaded");function j5(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(j5,"omitUndefinedEntries");function D2(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=j5(s.adapterType!==void 0?{...Object.fromEntries(vLe.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=j5({...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(D2,"buildAgentUpdatePatch");var Art="kubernetes";function Trt(e){return e.driver!=="sandbox"?!1:e.config?.provider===Art}r(Trt,"isKubernetesSandboxEnvironment");function yW(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>Trt(n))??null}}r(yW,"resolveForcedKubernetesEnvironment");var L$={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},YS={};function Rrt(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(Rrt,"supportsAdapterModelRefresh");function Ert(e,s){return aNe(e,s).model}r(Ert,"resolvePaperclipRunnerTransitionModel");function Tte(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(Tte,"isOverlayDirty");function Vq(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)=>Vq(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&&Vq(o,a[i]))}return!1}r(Vq,"overlayValuesEqual");function Prt(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!Vq(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(Prt,"subtractPersistedOverlay");var Jm="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 Mrt(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(Mrt,"parseCommaArgs");function Drt(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(Drt,"formatArgList");var Lrt=[{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"}],$rt=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],Ort=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],Frt=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],Brt=2,Rte=10,zrt=1,mSe=300;function cE(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(cE,"clampInteger");function qrt(e){return cE(e,0,mSe)*1e3}r(qrt,"clampDelayMsFromSeconds");function Urt({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(Urt,"ConfigSections");function hSe(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}=gs(),x=Mt(),b=(0,m.useRef)(null),v=uSe(),{data:j=[]}=X({queryKey:f?P.secrets.list(f):["secrets","none"],queryFn:r(()=>Sr.list(f),"queryFn"),enabled:!!f}),{data:N=[]}=X({queryKey:f?P.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>Sr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:k=[]}=X({queryKey:f?P.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>Sr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>k.filter(tt=>tt.kind==="binding"&&tt.target?.id===w),[k,w]),C=rSe(f,[]),{data:I}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn"),retry:!1}),T=(0,m.useMemo)(()=>{const tt=new Set(v);return I?.enableNativeRunner!==!0&&tt.add("paperclip_runner"),tt},[v,I?.enableNativeRunner]),R=I?.enableEnvironments===!0,A=I?.enableManagedSandboxOnly===!0,D=I===void 0||A,{data:M}=X({queryKey:P.instance.generalSettings,queryFn:r(()=>Or.getGeneral(),"queryFn"),retry:!1}),{data:$}=X({queryKey:P.instance.settings,queryFn:r(()=>Or.get(),"queryFn"),retry:!1}),{data:E=[]}=X({queryKey:f?P.environments.list(f):["environments","none"],queryFn:r(()=>Ri.list(f),"queryFn"),enabled:!!f&&(R||M?.executionMode==="kubernetes")}),{forced:B,kubernetesEnvironment:z}=(0,m.useMemo)(()=>yW(M?.executionMode,E),[M?.executionMode,E]),q=je({mutationFn:r(tt=>{if(!f)throw new Error("Select an organization to create secrets");return Sr.create(f,tt)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.list(f)})},"onSuccess")}),U=je({mutationFn:r(async({file:tt,namespace:Dt})=>{if(!f)throw new Error("Select an organization to upload images");return fb.uploadImage(f,tt,Dt)},"mutationFn")}),[F,K]=(0,m.useState)(L$),[G,se]=(0,m.useState)(!1),[ee,ne]=(0,m.useState)(0),he=(0,m.useRef)(null),Z=(0,m.useRef)(null),re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(he.current!==null&&e.agent!==he.current&&!re.current){const tt=Z.current;Z.current=null,K(Dt=>tt?Prt(Dt,tt):{...L$})}he.current=e.agent}},[a,a?void 0:e.agent]);const ce=!a&&(Tte(F)||G);function H(tt,Dt,xs){const Gs=F[tt];return Dt in Gs?Gs[Dt]:xs}r(H,"eff");function Q(tt,Dt,xs){K(Gs=>({...Gs,[tt]:{...Gs[tt],[Dt]:xs}}))}r(Q,"mark");function Y(){return b.current?.flushPendingDraft()??null}r(Y,"flushEnvironmentDraft");const te=(0,m.useCallback)(tt=>{a||K(Dt=>{const xs={...e.agent.adapterConfig??{},...Dt.adapterConfig},Gs={...Dt.adapterConfig};for(const[Bn,Cr]of Object.entries(tt))Gs[`${sA}${Bn}`]=Cr;for(const Bn of Object.keys(xs))Bn.startsWith("access.")&&(Bn.slice(7)in tt||(Gs[Bn]=void 0));return{...Dt,adapterConfig:Gs}})},[a,a?void 0:e.agent]),ae=(0,m.useCallback)(()=>{K({...L$}),se(!1),ne(tt=>tt+1)},[]),me=(0,m.useCallback)(async()=>{if(a)return;const tt=Y(),Dt=tt?{...F,adapterConfig:{...F.adapterConfig,env:tt}}:F;Tte(Dt)&&await e.onSave(D2(e.agent,Dt))},[a,ce,F,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(ce),e.onSaveActionChange?.(me),e.onCancelActionChange?.(ae))},[a,ce,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,me,ae]),(0,m.useEffect)(()=>{if(!a)return()=>{e.onSaveActionChange?.(null),e.onCancelActionChange?.(null),e.onDirtyChange?.(!1)}},[a,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const oe=a?{}:e.agent.adapterConfig??{},ie=a?{}:e.agent.runtimeConfig??{},ge=a?{}:ie.heartbeat??{},be=a?{}:ie.debug??{},le=a?e.values.adapterType:F.adapterType??e.agent.adapterType,ue=Ky(),Se=ue(le),ye=Se.supportsInstructionsBundle||Se.supportsSkills||Se.supportsLocalAgentJwt,Ie=ye&&!D&&Nrt({isCreate:a,adapterConfig:oe}),Ke=(0,m.useMemo)(()=>tS(le),[le]),rt=(0,m.useMemo)(()=>new Set(kBe(le)),[le]),dt=a?e.values:null,de=a?tt=>e.onChange(tt):null;a&&dt.claudeStoredSessionId;const ze=r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),gt=r(tt=>{if(!a||!de)return;const Dt=dt.envBindings??{};de({envBindings:{...Dt,...Bw()},claudeStoredSessionId:tt}),ze()},"handleClaudeLoginStored"),bt=r(async()=>{if(a)return;const tt={...Y()??H("adapterConfig","env",oe.env??YS),...Bw()},Dt={...F,adapterConfig:{...F.adapterConfig,env:tt}};K(Dt),await e.onSave({...D2(e.agent,Dt),applyStoredClaudeLogin:!0}),ze()},"handleClaudeLoginStoredEdit"),De=r(async tt=>{if(a||!tt.companyIdentityDiffers)return;const Dt={...Y()??H("adapterConfig","env",oe.env??YS),CODEX_HOME:{type:"secret_ref",secretId:tt.secretId,version:"latest"}},xs={...F,adapterConfig:{...F.adapterConfig,env:Dt}};K(xs),Z.current=xs,re.current=!0;try{await e.onSave(D2(e.agent,xs))}catch(Gs){throw Z.current=null,Gs}finally{re.current=!1}ze()},"handleCodexAccountBindingEdit"),Qe=r(()=>{if(!a||!de)return;const tt=dt.envBindings??{};de({envBindings:{...tt,...Bw()},claudeApplyStoredLogin:!0}),ze()},"handleApplyStoredClaudeLogin"),mt=r(async()=>{if(a)return;const tt={...Y()??H("adapterConfig","env",oe.env??YS),...Bw()},Dt={...F,adapterConfig:{...F.adapterConfig,env:tt}};K(Dt),await e.onSave({...D2(e.agent,Dt),applyStoredClaudeLogin:!0}),ze()},"handleApplyStoredClaudeLoginEdit"),Ye=a?dt.defaultEnvironmentId??"":H("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),it=(0,m.useMemo)(()=>Ye?(E.find(tt=>tt.id===Ye)??null)?.driver==="local"?"":Ye:"",[E,Ye]),Nt=(0,m.useMemo)(()=>E.find(tt=>tt.id===it)??null,[it,E]),Ze=(0,m.useMemo)(()=>{const tt=$?.defaultEnvironmentId??null;return tt?(E.find(Dt=>Dt.id===tt)??null)?.driver==="local"?"":tt:""},[E,$?.defaultEnvironmentId]),Pe=(0,m.useMemo)(()=>E.find(tt=>tt.id===Ze)??null,[E,Ze]),Ce=(0,m.useMemo)(()=>{try{return Zk({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:$?.defaultEnvironmentId??null,localDefaultEnvironmentId:tN(E),managedSandboxOnly:I?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:eN(E),visibleEnvironmentIds:E.map(tt=>tt.id)})}catch{return null}},[Ye,$?.defaultEnvironmentId,E,I?.enableManagedSandboxOnly]),Ve=(0,m.useMemo)(()=>E.find(tt=>tt.id===Ce)??null,[E,Ce]),{data:Ge}=X({queryKey:f?P.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>Ri.capabilities(f),"queryFn"),enabled:!!f&&Se.login!=null});(0,m.useEffect)(()=>{!a||!de||!B||!z||it!==z.id&&de({defaultEnvironmentId:z.id})},[a,de,B,z,it]);const ot=(0,m.useMemo)(()=>E.filter(tt=>{if(!rt.has(tt.driver)||tt.driver==="local")return!1;if(tt.driver!=="sandbox")return!0;const Dt=typeof tt.config?.provider=="string"?tt.config.provider:null;return Dt!==null&&Dt!=="fake"}),[E,rt]),Ee=(0,m.useMemo)(()=>!Nt||ot.some(tt=>tt.id===Nt.id)?ot:[...ot,Nt],[Nt,ot]),Je=R&&(B||it.length>0||ot.length>=1),_e=Pe?Hv(Pe):A?"Paperclip Computer":"Local",He=le==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":H("adapterConfig","provider",oe.provider==="acpx"&&oe.acpxAgent==="codex"?"codex":oe.provider??"codex")):void 0,ns=le==="opencode_local"&&Rpe.safeParse(F.runtime.runtimeConfig?.aiConnection??ie.aiConnection).data?.provider==="openrouter"?"openrouter":He,fe=f?P.agents.adapterModels(f,le,it||null,ns):["agents","none","adapter-models",le],{data:ct,error:Ue}=X({queryKey:fe,queryFn:r(()=>Lt.adapterModels(f,le,{environmentId:it||null,provider:ns}),"queryFn"),enabled:!!f}),[Et,$t]=(0,m.useState)(null),[js,Fe]=(0,m.useState)(!1),xt=ct??n??[],Wt="command",{data:Cs,refetch:Ts}=X({queryKey:f?P.agents.detectModel(f,le):["agents","none","detect-model",le],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return Lt.detectModel(f,le)},"queryFn"),enabled:!!(f&&ye&&le!=="opencode_local"&&le!=="paperclip_runner")}),Ct=Cs?.model??null;Cs?.candidates;const{data:ds=[]}=X({queryKey:f?P.agents.list(f):["agents","none","list"],queryFn:r(()=>Lt.list(f),"queryFn"),enabled:!!(!a&&f)}),Oe={mode:s,isCreate:a,adapterType:le,values:a?e.values:null,set:a?tt=>e.onChange(tt):null,config:oe,eff:H,mark:Q,models:xt,hideInstructionsFile:h||D,managedSandboxOnly:D},[xe,Gt]=(0,m.useState)(!1),[Pt,os]=(0,m.useState)(!1),ws=gNe(le),Hs=r(tt=>(0,t.jsxs)(t.Fragment,{children:[le==="claude_local"&&(0,t.jsx)(cet,{...Oe,section:tt}),(0,t.jsx)(Ke.ConfigFields,{...Oe,section:tt,hideModel:ye})]}),"renderAdapterFields"),[tr,Le]=(0,m.useState)(!1),[et,vt]=(0,m.useState)(!1);function $e(tt){if(a){const xs=Ke.buildAdapterConfig(dt);return tt&&Object.assign(xs,tt),j5(xs)}const Dt={...oe,...F.adapterConfig};return tt&&Object.assign(Dt,tt),j5(Dt)}r($e,"buildAdapterConfigForTest");const Ft=je({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const tt=Y(),Dt=tt?{env:tt}:void 0;let xs=$,Gs=E,Bn=I?.enableManagedSandboxOnly===!0;if(!Ye)try{const[cr,rr,sr]=await Promise.all([x.ensureQueryData({queryKey:P.instance.settings,queryFn:r(()=>Or.get(),"queryFn")}),x.ensureQueryData({queryKey:P.environments.list(f),queryFn:r(()=>Ri.list(f),"queryFn")}),x.ensureQueryData({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn")})]);xs=cr,Gs=rr,Bn=sr?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Cr=Zk({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:xs?.defaultEnvironmentId??null,localDefaultEnvironmentId:tN(Gs),managedSandboxOnly:Bn,managedSandboxEnvironmentId:eN(Gs),visibleEnvironmentIds:Gs.map(cr=>cr.id)}),Qr=$e(Dt),Nr=a?void 0:e.agent.id,Rr=a?void 0:cJ.safeParse(F.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const cr=le==="paperclip_runner"?Qr.provider==="codex"?"codex_local":Qr.provider==="acpx"&&Qr.acpxAgent==="grok"?"grok_local":Qr.provider==="acpx"&&Qr.acpxAgent==="claude"?"claude_local":le:le;return eNe({companyId:f,adapterType:le,providerAdapter:cr,adapterConfig:Qr,agentId:Nr,aiConnection:Rr,environmentId:Cr})}return Lt.testEnvironment(f,le,{adapterConfig:Qr,agentId:Nr,aiConnection:Rr,environmentId:Cr})},"mutationFn")}),[wt,Yt]=(0,m.useState)(!1),[Zt,us]=(0,m.useState)(null),ht="Test",kt=!a&&!!e.isSaving,Rs=wt||kt||!f,hs=(0,m.useRef)(Ft.reset);hs.current=Ft.reset;const jn=(0,m.useRef)(()=>{});jn.current=()=>{if(!a||!de)return;const tt=dt.envBindings??{},Dt=dt.claudeStoredSessionId!=null||dt.claudeApplyStoredLogin===!0,xs=yte in tt;if(!Dt&&!xs)return;const Gs={...tt};delete Gs[yte],de({envBindings:Gs,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{hs.current(),us(null),jn.current()},[le,Ce]);const Es=Se.login!=null,an=Ft.data,Jt=an!=null&&ue(an.adapterType).login!=null,Xs=an&&Jt?an.checks.find(tt=>tt.code==="adapter_auth_missing")??null:null,Zs=typeof Ve?.config?.provider=="string"?Ve.config.provider:null,qr=Zs!=null&&Ge?.sandboxProviders?.[Zs]?.supportsLoginPty===!0,pr=Se.login!=null,jr=(a||!(F.runtime.runtimeConfig?.aiConnection??ie.aiConnection))&&Es&&Ve?.driver==="sandbox"&&!!Ce&&!!f&&!!Xs&&(!pr||qr),mn=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");Yt(!0),us(null),Ft.reset();try{return await Ft.mutateAsync()}catch(tt){throw us(tt instanceof Error?tt.message:"Environment test failed"),tt}finally{Yt(!1)}},[f,Ft]),Zn=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{Zn.current=()=>{Rs||mn().catch(()=>{})}},[mn,Rs]);const Tr=(0,m.useCallback)(()=>{Zn.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Tr),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Tr]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Rs,pending:wt}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Rs,wt]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Zt??(Ft.error instanceof Error?Ft.error.message:Ft.error?"Environment test failed":null),result:Ft.data??null,login:jr&&f&&Ce?{companyId:f,adapterType:le,environmentId:Ce}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Zt,Ft.data,Ft.error,jr,f,le,Ce]);const Wr=a?dt.model??"":H("adapterConfig","model",String(oe.model??"")),ut=typeof Wr=="string"?Wr:"";async function rs(){if(f){Fe(!0),$t(null);try{const tt=await Lt.adapterModels(f,le,{refresh:!0,environmentId:it||null,provider:ns});x.setQueryData(fe,tt)}catch(tt){$t(tt instanceof Error?tt.message:"Failed to refresh adapter models.")}finally{Fe(!1)}}}r(rs,"handleRefreshModels");const Ls=le==="codex_local"?"modelReasoningEffort":le==="cursor"?"mode":le==="opencode_local"?"variant":le==="grok_local"?"reasoningEffort":le==="pi_local"?"thinking":"effort",Os=le==="codex_local"?iW(ut,"Auto").map(tt=>({id:tt.value,label:tt.label})):le==="cursor"?$rt:le==="opencode_local"?Lrt:le==="kimi_local"?Frt:le==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(tt=>({id:tt,label:tt}))]:le==="claude_local"||le==="grok_local"?[{id:"",label:"Auto"},...p5(le,ut).map(tt=>({id:tt,label:tt==="xhigh"?"X-High":tt[0].toUpperCase()+tt.slice(1)}))]:Ort,Us=a?dt.thinkingEffort:le==="codex_local"?H("adapterConfig","modelReasoningEffort",String(oe.modelReasoningEffort??oe.reasoningEffort??"")):le==="cursor"?H("adapterConfig","mode",String(oe.mode??"")):le==="opencode_local"?H("adapterConfig","variant",String(oe.variant??"")):H("adapterConfig",Ls,String(oe[Ls]??"")),Ps=le!=="gemini_local"&&le!=="cursor_cloud"&&le!=="paperclip_runner",fr=le==="codex_local"?a?!!dt.search:H("adapterConfig","search",!!oe.search):!1,xr=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:dt.heartbeatEnabled,intervalSec:dt.intervalSec}};const tt={...ie.heartbeat&&typeof ie.heartbeat=="object"?ie.heartbeat:{},...F.heartbeat};return{...ie,heartbeat:tt}},[a,F.heartbeat,ie,dt]),wr=uJ(xr.heartbeat),nr=uJ(wr.maxTurnContinuation),Fr=HLe(nr.enabled,!0),kr=cE(yJ(nr.maxAttempts,Brt),0,Rte),_t=cE(yJ(nr.delayMs,zrt*1e3)/1e3,0,mSe);function qs(tt){Q("heartbeat","maxTurnContinuation",{...nr,...tt})}r(qs,"updateMaxTurnContinuation");const hn=(0,t.jsx)(yy,{ref:b,onDirtyChange:se,hideDraftActions:!a&&e.hideInlineSave,value:a?dt.envBindings??YS:H("adapterConfig","env",oe.env??YS),secrets:j,userSecretDefinitions:N,onCreateSecret:r(async(tt,Dt)=>await q.mutateAsync({name:tt,value:Dt}),"onCreateSecret"),onChange:r(tt=>a?de({envBindings:tt??{},envVars:""}):Q("adapterConfig","env",tt),"onChange")},ee);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:W("relative",i&&"space-y-6"),children:[ce&&!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:me,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:hn})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Secret access"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Secret access"}),(0,t.jsxs)("div",{className:W(i?"space-y-3 rounded-lg border border-border p-4":"space-y-3 px-4 pb-3"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:wi.secretAccess}),(0,t.jsx)(jrt,{config:{...oe,...F.adapterConfig},secrets:j,onChange:te,onCreateSecret:r((tt,Dt)=>q.mutateAsync({name:tt,value:Dt}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(Urt,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[ce&&!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:me,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(Ss,{label:"Name",hint:wi.name,children:(0,t.jsx)(za,{value:H("identity","name",e.agent.name),onCommit:r(tt=>Q("identity","name",tt),"onCommit"),immediate:!0,className:Jm,placeholder:"Agent name"})}),(0,t.jsx)(Ss,{label:"Title",hint:wi.title,children:(0,t.jsx)(za,{value:H("identity","title",e.agent.title??""),onCommit:r(tt=>Q("identity","title",tt||null),"onCommit"),immediate:!0,className:Jm,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(Ss,{label:"Reports to",hint:wi.reportsTo,children:(0,t.jsx)(Pnt,{agents:ds,value:H("identity","reportsTo",e.agent.reportsTo??null),onChange:r(tt=>Q("identity","reportsTo",tt),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),ye&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Prompt Template",hint:wi.promptTemplate,children:(0,t.jsx)(ud,{value:H("adapterConfig","promptTemplate",String(oe.promptTemplate??"")),onChange:r(tt=>Q("adapterConfig","promptTemplate",tt??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async tt=>{const Dt=`agents/${e.agent.id}/prompt-template`;return(await U.mutateAsync({file:tt,namespace:Dt})).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."})]})]})]}),B?(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:z?(0,t.jsxs)("div",{className:W(Jm,"flex items-center text-muted-foreground"),children:[z.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."})})})]}):Je?(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:Jm,value:it,onChange:r(tt=>{const Dt=tt.target.value;if(a){de({defaultEnvironmentId:Dt});return}Q("identity","defaultEnvironmentId",Dt||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",_e]}),Ee.map(tt=>(0,t.jsx)("option",{value:tt.id,children:Hv(tt)},tt.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:Tr,disabled:Rs,children:wt?`${ht}...`:ht})]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(Ss,{label:"Adapter type",hint:wi.adapterType,children:(0,t.jsx)(fSe,{value:le,disabledTypes:T,onChange:r(tt=>{if(a){const{adapterType:Dt,...xs}=tb,Gs={...xs,adapterType:tt};tt==="codex_local"?Gs.dangerouslyBypassSandbox=!0:tt==="gemini_local"?Gs.model="auto":tt==="kimi_local"?Gs.model="kimi-code/kimi-for-coding":tt==="cursor"?Gs.model="auto":tt==="opencode_local"?Gs.model="openai/gpt-5.2-codex":tt==="paperclip_runner"&&(Gs.model=Yk),de(Gs)}else K(Dt=>({...Dt,adapterType:tt,adapterConfig:{model:tt==="gemini_local"?"auto":tt==="kimi_local"?"kimi-code/kimi-for-coding":tt==="opencode_local"?"openai/gpt-5.2-codex":tt==="cursor"?"auto":tt==="paperclip_runner"?Ert(le,oe.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...tt==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:tt==="paperclip_runner"?{...aNe(le,H("adapterConfig","model",oe.model))}:{}}}))},"onChange")})}),!a&&f&&(0,t.jsx)(Zke,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:le==="paperclip_runner"?H("adapterConfig","provider",oe.provider)==="codex"?"codex_local":H("adapterConfig","provider",oe.provider)==="opencode"?"opencode_local":H("adapterConfig","provider",oe.provider)==="acpx"&&H("adapterConfig","acpxAgent",oe.acpxAgent)==="grok"?"grok_local":H("adapterConfig","provider",oe.provider)==="acpx"&&H("adapterConfig","acpxAgent",oe.acpxAgent)==="claude"?"claude_local":le:le,routerAdapterType:le,value:cJ.safeParse(F.runtime.runtimeConfig?.aiConnection??ie.aiConnection).data,model:String(H("adapterConfig","model",oe.model)??""),environmentId:it||void 0,legacy:!0,onChange:r(tt=>Q("runtime","runtimeConfig",{...ie,aiConnection:tt}),"onChange")}),d&&!e.compactTestFeedback&&(Zt||Ft.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Zt??(Ft.error instanceof Error?Ft.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&Ft.data&&(0,t.jsx)(Yrt,{result:Ft.data}),d&&jr&&(0,t.jsx)(jW,{companyId:f,adapterType:le,environmentId:Ce,onStored:a?gt:bt,onApplyStored:a?Qe:mt,onAccountBinding:a?void 0:De},`${le}:${Ce}`),Ie&&(0,t.jsx)(Ss,{label:"Working directory (deprecated)",hint:wi.cwd,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[(0,t.jsx)(Po,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(za,{value:a?dt.cwd:H("adapterConfig","cwd",String(oe.cwd??"")),onCommit:r(tt=>a?de({cwd:tt}):Q("adapterConfig","cwd",tt||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,{})]})}),Hs("adapter"),ye&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(wW,{models:xt,value:ut,onChange:r(tt=>{const Dt=p5(le,tt),xs=["codex_local","claude_local","grok_local"].includes(le)&&!!Us&&!Dt.includes(String(Us));if(a){de({model:tt,...xs?{thinkingEffort:""}:{}});return}Q("adapterConfig","model",tt||void 0),xs&&(Q("adapterConfig",Ls,void 0),Q("adapterConfig","reasoningEffort",void 0))},"onChange"),open:tr,onOpenChange:Le,defaultLabel:le==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:le!=="opencode_local"&&le!=="pi_local"&&le!=="paperclip_runner",required:le==="opencode_local"||le==="pi_local",groupByProvider:le==="opencode_local"||le==="pi_local",preserveOrder:mW(le),creatable:!0,detectedModel:Ct,detectedModelCandidates:[],onDetectModel:le==="opencode_local"||le==="paperclip_runner"?void 0:async()=>(await Ts()).data?.model??null,onRefreshModels:Rrt(le)?rs:void 0,refreshingModels:js,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Et||Ue)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Et??(Ue instanceof Error?Ue.message:"Failed to load adapter models.")}),le==="opencode_local"&&Nt&&Nt.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 ",Nt.name,"."]}),Ps&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Jrt,{value:Us,options:Os,onChange:r(tt=>a?de({thinkingEffort:tt}):Q("adapterConfig",Ls,tt||void 0),"onChange"),open:et,onOpenChange:vt}),le==="codex_local"&&fr&&Us==="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 oe.bootstrapPromptTemplate=="string"&&oe.bootstrapPromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Bootstrap prompt (legacy)",hint:wi.bootstrapPrompt,children:(0,t.jsx)(ud,{value:H("adapterConfig","bootstrapPromptTemplate",String(oe.bootstrapPromptTemplate??"")),onChange:r(tt=>Q("adapterConfig","bootstrapPromptTemplate",tt||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async tt=>{const Dt=`agents/${e.agent.id}/bootstrap-prompt`;return(await U.mutateAsync({file:tt,namespace:Dt})).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."})]}),Hs("configuration"),(ye||le==="process"||ws?.fields.some(tt=>Aq(tt.key)==="advanced"))&&(0,t.jsx)(sE,{title:"Advanced",open:Pt,onToggle:r(()=>os(!Pt),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[ye&&(0,t.jsxs)(t.Fragment,{children:[" ",!D&&(0,t.jsx)(Ss,{label:"Command",hint:wi.localCommand,children:(0,t.jsx)(za,{value:a?dt.command:H("adapterConfig",Wt,String(oe.command??"")),onCommit:r(tt=>a?de({command:tt}):Q("adapterConfig",Wt,tt||null),"onCommit"),immediate:!0,className:Jm,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[le]??le.replace(/_local$/,"")})}),(0,t.jsx)(Ss,{label:"Extra args (comma-separated)",hint:wi.extraArgs,children:(0,t.jsx)(za,{value:a?dt.extraArgs:H("adapterConfig","extraArgs",Drt(oe.extraArgs)),onCommit:r(tt=>a?de({extraArgs:tt}):Q("adapterConfig","extraArgs",tt?.trim()?Mrt(tt):null),"onCommit"),className:Jm,placeholder:"e.g. --verbose, --foo=bar"})})]}),Hs("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(ye||ws?.fields.some(tt=>Aq(tt.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:ye?hn:Hs("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)(RC,{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)(RC,{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)(Hee,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:dt.heartbeatEnabled,onCheckedChange:r(tt=>de({heartbeatEnabled:tt}),"onCheckedChange"),number:dt.intervalSec,onNumberChange:r(tt=>de({intervalSec:tt}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:dt.heartbeatEnabled}),(0,t.jsx)(sE,{title:"Advanced Run Policy",open:xe,onToggle:r(()=>Gt(!xe),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Hs("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)(RC,{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)(RC,{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)(Hee,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:H("heartbeat","enabled",ge.enabled===!0),onCheckedChange:r(tt=>Q("heartbeat","enabled",tt),"onCheckedChange"),number:H("heartbeat","intervalSec",Number(ge.intervalSec??300)),onNumberChange:r(tt=>Q("heartbeat","intervalSec",tt),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:H("heartbeat","enabled",ge.enabled===!0)})}),(0,t.jsx)(sE,{title:"Advanced Run Policy",bordered:i,open:xe,onToggle:r(()=>Gt(!xe),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Hs("runPolicy"),ye&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!ws?.fields.some(tt=>tt.key==="timeoutSec")&&(0,t.jsx)(Ss,{label:"Timeout (sec)",hint:wi.timeoutSec,children:(0,t.jsx)(Sc,{value:H("adapterConfig","timeoutSec",Number(oe.timeoutSec??0)),onCommit:r(tt=>Q("adapterConfig","timeoutSec",tt),"onCommit"),immediate:!0,className:Jm})}),!ws?.fields.some(tt=>tt.key==="graceSec")&&(0,t.jsx)(Ss,{label:"Interrupt grace period (sec)",hint:wi.graceSec,children:(0,t.jsx)(Sc,{value:H("adapterConfig","graceSec",Number(oe.graceSec??15)),onCommit:r(tt=>Q("adapterConfig","graceSec",tt),"onCommit"),immediate:!0,className:Jm})})]})}),(0,t.jsx)(Cd,{label:"Wake on demand",hint:wi.wakeOnDemand,checked:H("heartbeat","wakeOnDemand",ge.wakeOnDemand!==!1),onChange:r(tt=>Q("heartbeat","wakeOnDemand",tt),"onChange")}),(0,t.jsx)(Ss,{label:"Cooldown (sec)",hint:wi.cooldownSec,children:(0,t.jsx)(Sc,{value:H("heartbeat","cooldownSec",Number(ge.cooldownSec??10)),onCommit:r(tt=>Q("heartbeat","cooldownSec",tt),"onCommit"),immediate:!0,className:Jm})}),(0,t.jsx)(Ss,{label:"Max concurrent runs",hint:wi.maxConcurrentRuns,children:(0,t.jsx)(Sc,{value:H("heartbeat","maxConcurrentRuns",Number(ge.maxConcurrentRuns??20)),onCommit:r(tt=>Q("heartbeat","maxConcurrentRuns",tt),"onCommit"),immediate:!0,className:Jm})}),(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:wi.maxTurnContinuationEnabled,checked:Fr,onChange:r(tt=>qs({enabled:tt}),"onChange")}),Fr?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Continuation attempts",hint:wi.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Sc,{value:kr,onCommit:r(tt=>qs({maxAttempts:cE(tt,0,Rte)}),"onCommit"),immediate:!0,className:Jm})}),(0,t.jsx)(Ss,{label:"Continuation delay (sec)",hint:wi.maxTurnContinuationDelaySec,children:(0,t.jsx)(Sc,{value:_t,onCommit:r(tt=>qs({delayMs:qrt(tt)}),"onCommit"),immediate:!0,className:Jm})})]}):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)(zv,{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)(zv,{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:H("debug","providerTrace",be.providerTrace)==="raw",onChange:r(tt=>Q("debug","providerTrace",tt?"raw":void 0),"onChange")}),H("debug","providerTrace",be.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)(zv,{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)(mNe,{state:wt?"running":Zt||Ft.error?"fail":an?.status??"idle",result:an??null,error:Zt??(Ft.error instanceof Error?Ft.error.message:null),onTest:Tr,disabled:Rs})]})}r(hSe,"AgentConfigForm");var Hq=new Set(["authenticated","failed","timed_out","cancelled"]),Gq=2e3;function Qq({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 ha(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(vs,{className:"size-3"}):(0,t.jsx)(Ar,{className:"size-3"})})}r(Qq,"AdapterLoginCopyButton");function Krt({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)(vs,{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)(Ds,{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(Krt,"AdapterLoginTerminalState");var Wrt={claude_local:"Anthropic",codex_local:"OpenAI"};function pSe(e){const s=Wrt[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(pSe,"adapterLoginTitle");function jW(e){return Ky()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(Qrt,{...e}):(0,t.jsx)(Vrt,{...e})}r(jW,"AdapterLoginPanel");var $$=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 Vrt({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(()=>Lt.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(()=>Lt.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:k,onError:r(re=>{f(re instanceof Error?re.message:"Could not cancel the login.")},"onError")}),C=X({queryKey:["adapter-login-active-session",e,s],queryFn:r(async()=>{try{const re=await Lt.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 $$(re.sessionId);return re}catch(re){if(re instanceof un&&re.status===404)return null;throw re}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[I,T]=(0,m.useState)(!1),R=X({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>Lt.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!I,retry:r((re,ce)=>ce instanceof un&&ce.status===404?!1:re<3,"retry"),refetchInterval:r(re=>{const ce=re.state.data?.status;return ce&&Hq.has(ce)?!1:Gq},"refetchInterval")});(0,m.useEffect)(()=>{const re=R.data?.prompt??null;re&&b(re)},[R.data]);const A=R.data??w.data??null,D=A?.status??null,M=x,$=D?Hq.has(D):!1,E=!!u&&!$,B=w.isPending||E||v==="saving",z=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(z.current||!C.isFetched)return;z.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=R.error;if(!(re instanceof un&&re.status===404)||!N.current||I)return;T(!0);const ce=u;(async()=>(ce&&await Lt.cancelAdapterAuthLogin(e,s,ce).catch(()=>{}),T(!1),k()))()},[R.error,I,u,e,s,k]);const q=(0,m.useRef)(!1),U=je({mutationFn:r(async()=>{const re=C.error;re instanceof $$&&await Lt.cancelAdapterAuthLogin(e,s,re.sessionId)},"mutationFn"),onSuccess:r(async()=>{q.current=!1,z.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")}),F=(0,m.useRef)(w.mutate);F.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&&F.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),G=(0,m.useRef)(i);G.current=i,(0,m.useEffect)(()=>{D!=="authenticated"||K.current||(K.current=!0,G.current?.(u??void 0))},[D]);const se=(0,m.useRef)(null),ee=(0,m.useRef)(o);ee.current=o;const ne=R.data?.codexAccountBinding??null,he=(0,m.useCallback)(async re=>{const ce=ee.current;if(ce){j("saving");try{await ce(re),j("bound")}catch{j("failed")}}},[]);(0,m.useEffect)(()=>{D!=="authenticated"||!u||se.current!==u&&(!ne||!ne.companyIdentityDiffers||!ee.current||(se.current=u,he(ne)))},[D,u,ne,he]);const Z=(0,m.useRef)(d);if(Z.current=d,(0,m.useEffect)(()=>{Z.current?.(M?.url??null)},[M]),l==="onboarding"){const re=$&&D&&D!=="authenticated";return(0,t.jsx)(wNe,{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 $$&&(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)(zZe,{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:pSe(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:B,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)(nt,{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)(Qq,{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)(Qq,{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)(qn,{className:"size-3"})})})]})]})]}),$&&D&&(0,t.jsx)(Krt,{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)(nt,{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)(vs,{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)(Ds,{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&&he(ne)},"onClick"),children:"Retry"})]})]})]})}r(Vrt,"DisplayedCodeLoginPanel");var Hrt=new Set(["failed","timed_out","cancelled"]),Ete="The login did not finish. Start the login again.",Grt=9e5,Pte="The login timed out. Start the login again.";function Qrt({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,T]=(0,m.useState)(null),[R,A]=(0,m.useState)(!1),[D,M]=(0,m.useState)(!1),[$,E]=(0,m.useState)(!1),[B,z]=(0,m.useState)(!1),q=(0,m.useRef)(!1),[U,F]=(0,m.useState)(!1),K=(0,m.useRef)(!1),G=r(()=>{v(null),N(null),k(!1),C(""),T(null),A(!1),M(!1),z(!1),E(!1),q.current=!1},"resetLocalState"),se=X({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await Lt.getClaudeOAuthTokenStatus(e)}catch(Ze){if(Ze instanceof un&&Ze.status===404)return null;throw Ze}},"queryFn"),retry:r((Ze,Pe)=>Pe instanceof un&&Pe.status===404?!1:Ze<2,"retry")}).data??null,ee=je({mutationFn:r(()=>Lt.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...se&&!h?{overwrite:{expectedSecretId:se.secretId,expectedLatestVersion:se.latestVersion}}:{}}),"mutationFn"),onSuccess:r(Ze=>{K.current=!1,G(),x(Ze.sessionId)},"onSuccess"),onError:r(Ze=>{v(Ze instanceof Error?Ze.message:"Could not start the login.")},"onError")}),ne=r(()=>{K.current=!1,x(null),G()},"clearActiveSession"),he=je({mutationFn:r(()=>Lt.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{ne()},"onSuccess"),onError:r(Ze=>{if(Ze instanceof un&&Ze.status===404){ne();return}v(Ze instanceof Error?Ze.message:"Could not cancel the login.")},"onError")}),Z=(0,m.useCallback)(Ze=>{Lt.cancelClaudeSetupTokenLogin(e,Ze).catch(()=>{})},[e]),re=X({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const Ze=await Lt.getActiveClaudeSetupTokenLoginSession(e);if(!Ze)return null;if(h&&Ze.environmentId!==n||!!Ze.aiConnection!=!!h||h&&(Ze.aiConnection?.provider!==h.provider||Ze.aiConnection?.method!==h.method||Ze.aiConnection?.connectionId!==h.connectionId||Ze.aiConnection?.ownership!==h.ownership||Ze.aiConnection?.allAgents!==h.allAgents||JSON.stringify(Ze.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 Ze}catch(Ze){if(Ze instanceof un&&Ze.status===404)return null;throw Ze}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[ce,H]=(0,m.useState)(!1),Q=!!f&&!D&&!B&&!ce,Y=X({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>Lt.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:Q,retry:r((Ze,Pe)=>Pe instanceof un&&Pe.status===404?!1:Ze<3,"retry"),refetchInterval:r(Ze=>{if(D||B)return!1;const Pe=Ze.state.data?.status;return Pe&&Hq.has(Pe)?!1:Gq},"refetchInterval")});(0,m.useEffect)(()=>{const Ze=Y.error;if(Ze instanceof un&&Ze.status===404){if(K.current){if(ce)return;H(!0);const Pe=f;(async()=>(Pe&&await Lt.cancelClaudeSetupTokenLogin(e,Pe).catch(()=>{}),H(!1),ne()))();return}z(!0)}},[Y.error,ce,f,e]);const te=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(te.current||!re.isFetched)return;te.current=!0;const Ze=re.data;Ze&&(K.current=!0,G(),x(Ze.sessionId),Ze.prompt&&(N(Ze.prompt.authorizationUrl),Ze.prompt.transportAdvisory&&k(!0)))},[re.isFetched,re.data]);const ae=X({queryKey:["claude-setup-token-prompt",e,f],enabled:Q&&!j,queryFn:r(async()=>{try{return await Lt.getClaudeSetupTokenLoginPrompt(e,f)}catch(Ze){if(Ze instanceof un&&Ze.status===404)return null;throw Ze}},"queryFn"),refetchInterval:r(Ze=>D||Ze.state.data?.authorizationUrl?!1:Gq,"refetchInterval")});(0,m.useEffect)(()=>{const Ze=ae.data?.authorizationUrl??null;Ze&&N(Ze),ae.data?.transportAdvisory&&k(!0)},[ae.data]);const me=je({mutationFn:r(Ze=>Lt.submitClaudeSetupTokenBrowserCode(e,f,Ze),"mutationFn"),onError:r(Ze=>{v(Ze instanceof Error?Ze.message:"Could not submit the browser code.")},"onError")}),oe=je({mutationFn:r(()=>Lt.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(Ze=>{T(Ze.storedSessionId),a?.(Ze.storedSessionId)},"onSuccess"),onError:r(()=>{A(!0)},"onError")}),ie=Y.data?.status??ee.data?.status??null,ge=Y.data?.expiresAt??ee.data?.expiresAt??null,be=(0,m.useRef)(oe.mutate);be.current=oe.mutate,(0,m.useEffect)(()=>{ie==="authenticated"&&!q.current&&(q.current=!0,be.current())},[ie]);const le=I!==null,ue=R||B||!!(ie&&Hrt.has(ie)),Se=ie==="authenticated"&&!le&&!R,ye=!!f&&!le&&!ue&&!D,Ie=ee.isPending||ye;(0,m.useEffect)(()=>{if(!ye)return;const Ze=ge!==null?new Date(ge).getTime():NaN,Pe=Number.isFinite(Ze)?Math.max(0,Ze-Date.now()):Grt,Ce=setTimeout(()=>{f&&Z(f),M(!0)},Pe);return()=>clearTimeout(Ce)},[ye,ge,f,Z]);const Ke=S.trim(),rt=ye&&!!j&&!Se&&HDe(Ke)&&!me.isPending&&!$,dt=(0,m.useRef)(c);dt.current=c;const de=(0,m.useRef)(d);de.current=d;const ze=r(()=>{rt&&(v(null),me.mutate(Ke),E(!0),dt.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),gt=(0,m.useRef)(!1),bt=(0,m.useRef)(ee.mutate);bt.current=ee.mutate,(0,m.useEffect)(()=>{if(!(!o||gt.current)){if(re.isError){gt.current=!0,v(re.error instanceof Error?re.error.message:"Could not check for an active login.");return}re.isSuccess&&(gt.current=!0,!re.data&&bt.current())}},[o,re.isSuccess,re.isError,re.data,re.error]);const De=(0,m.useRef)(ze);De.current=ze;const Qe=u==="onboarding",mt=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Qe||!mt.current||(mt.current=!1,rt&&De.current())},[Qe,rt,S]);const Ye=(0,m.useRef)(!1),it=(0,m.useRef)(l);it.current=l,(0,m.useEffect)(()=>{!le||Ye.current||(Ye.current=!0,it.current?.(f??void 0))},[le]),(0,m.useEffect)(()=>{$&&(!b&&!ue&&!D||(E(!1),de.current?.()))},[$,b,ue,D]);const Nt=(0,m.useRef)(p);if(Nt.current=p,(0,m.useEffect)(()=>{Nt.current?.(j)},[j]),u==="onboarding"){const Ze=ue||D;return(0,t.jsxs)(wNe,{loading:!j&&!b&&!Ze,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)(Ds,{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}):Ze?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D&&!ue?Pte:Ete}):(0,t.jsx)(GM,{value:S,onChange:C,onSubmit:ze,onPaste:r(()=>{mt.current=!0},"onPaste"),masked:!0,disabled:me.isPending||Se||$})]})}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:pSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[ye&&(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:he.isPending,onClick:r(()=>he.mutate(),"onClick"),children:"Cancel"}),i&&se&&!ye&&!le&&!U&&(0,t.jsx)(L,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),F(!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(()=>ee.mutate(),"onClick"),children:se&&!ye&&!le?"Sign in to replace":"Sign in"})]})]}),se&&!ye&&!le&&!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)(vs,{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:[ye&&!j&&!Se&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(nt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),ye&&j&&!Se&&(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)(Ds,{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)(Qq,{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)(qn,{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(Ze=>C(Ze.target.value),"onChange"),onKeyDown:r(Ze=>{Ze.key==="Enter"&&(Ze.preventDefault(),ze())},"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:!rt,onClick:ze,children:"Submit"})]})]})]}),Se&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(nt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(vs,{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)(Ds,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Ete})]}),D&&!ue&&!le&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Ds,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Pte})]})]})]})}r(Qrt,"SubmittedBrowserCodeLoginPanel");function Yrt({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(Yrt,"AdapterEnvironmentResult$1");function fSe({value:e,onChange:s,disabledTypes:n}){const[a,i]=(0,m.useState)(!1),o=Nh(e),l=(0,m.useMemo)(()=>dSe(c=>Jk[c]??qf(c)).filter(c=>!n.has(c.value)),[n]);return(0,t.jsxs)(yr,{open:a,onOpenChange:i,children:[(0,t.jsx)(Ir,{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)(Tq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{className:"truncate",children:Jk[e]??qf(e)}),o.experimental&&(0,t.jsx)(Mte,{})]}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(lr,{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)(Tq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{children:c.label}),c.experimental&&(0,t.jsx)(Mte,{})]}),c.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},c.value))})]})}r(fSe,"AdapterTypeDropdown");function Mte(){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(Mte,"ExperimentalBadge$1");function wW({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),T=w.trim(),R=!!(u&&T&&!e.some(E=>E.id.toLowerCase()===T.toLowerCase())),A=(0,m.useMemo)(()=>{const E=new Set;h&&E.add(h);for(const B of p??[])B&&E.add(B);return E},[h,p]),D=(0,m.useMemo)(()=>e.filter(E=>{if(A.has(E.id))return!1;if(!w.trim())return!0;const B=w.toLowerCase(),z=Eq(E.id)??"";return E.id.toLowerCase().includes(B)||E.label.toLowerCase().includes(B)||z.toLowerCase().includes(B)}),[e,w,A]),M=(0,m.useMemo)(()=>{if(!c)return[{provider:"models",entries:d?D:[...D].sort((B,z)=>B.id.localeCompare(z.id))}];const E=new Map;for(const B of D){const z=Eq(B.id)??"other",q=E.get(z)??[];q.push(B),E.set(z,q)}return Array.from(E.entries()).sort(([B],[z])=>B.localeCompare(z)).map(([B,z])=>({provider:B,entries:[...z].sort((q,U)=>q.id.localeCompare(U.id))}))},[D,c,d]);async function $(){if(f){C(!0);try{const E=await f();E&&(n(E),i(!1),k(""))}finally{C(!1)}}}return r($,"handleDetectModel"),(0,t.jsx)(Ss,{label:"Model",hint:wi.model,children:(0,t.jsxs)(yr,{open:a,onOpenChange:r(E=>{i(E),E||k("")},"onOpenChange"),children:[(0,t.jsx)(Ir,{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)(lr,{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(()=>{$()},"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)(lt,{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)(lt,{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 B=e.find(z=>z.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:B?.label??E}),(0,t.jsx)(lt,{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"}),R&&(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(T),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:T})]}),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(B=>(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",B.id===s&&"bg-accent"),onClick:r(()=>{n(B.id),i(!1)},"onClick"),children:(0,t.jsx)("span",{className:"block w-full text-left truncate",title:B.id,children:c?WZe(B.id):B.label})},B.id))]},E.provider)),D.length===0&&!R&&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(wW,"ModelDropdown");function Jrt({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(Ss,{label:"Thinking effort",hint:wi.thinkingEffort,children:(0,t.jsxs)(yr,{open:a,onOpenChange:i,children:[(0,t.jsx)(Ir,{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)(lr,{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(Jrt,"ThinkingEffortDropdown");function xSe(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=dpe.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=$R();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(xSe,"useAgentAppearanceDraft");var JS=null,L2=new Set,XS={subscribe(e){return L2.add(e),()=>{L2.delete(e)}},getSnapshot(){return JS},acquire(e){if(JS)return!1;JS=e;for(const s of L2)s();return!0},release(e){if(JS===e){JS=null;for(const s of L2)s()}}};function T_({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)(()=>kN(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)(XS.subscribe,XS.getSnapshot,()=>null),[k,S]=(0,m.useState)(!1),[C,I]=(0,m.useState)(!0),[T,R]=(0,m.useState)(!1),[A,D]=(0,m.useState)(!1),M=k&&!C&&!T&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const $=matchMedia("(prefers-reduced-motion: reduce)"),E=r(()=>I($.matches),"change");E(),$.addEventListener("change",E);const B=new IntersectionObserver(z=>S(z[0]?.isIntersecting??!1));return b.current&&B.observe(b.current),()=>{B.disconnect(),$.removeEventListener("change",E)}},[]),(0,m.useEffect)(()=>{M&&w===null&&XS.acquire(N.current),M||XS.release(N.current)},[M,w]),(0,m.useEffect)(()=>()=>XS.release(N.current),[]),(0,m.useEffect)(()=>{if(!M||w!==N.current)return;let $=!1;return D(!1),Promise.all([Wc(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),Wc(()=>import("./definition-CZKX1H5T.js"),__vite__mapDeps([2,3,1]))]).then(([E,B])=>{$||!v.current||(j.current=E.createCharacter(v.current,B.characterDefinition(x,i),{animation:B.animationId(a),trackingRegion:l?.current??b.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>R(!0),"onError")}),D(!0))}).catch(()=>{$||R(!0)}),()=>{$=!0,j.current?.destroy(),j.current=null,D(!1)}},[M,w,l,c,n,d,u]),(0,m.useEffect)(()=>{j.current&&Wc(()=>import("./definition-CZKX1H5T.js").then($=>{j.current?.setDefinition($.characterDefinition(x,i)),j.current?.setAnimation($.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",HOe[n],h),children:[(0,t.jsx)(_r,{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(T_,"AgentCharacter");var Xrt=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function gSe(e,{cloud:s,nativeRunnerEnabled:n}){return e==="paperclip_runner"?n:s?Xrt.has(e):!0}r(gSe,"isNewAgentAdapterAllowed");var Zrt={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=Nh(e).icon,a=Zrt[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 eat(){const{selectedCompanyId:e}=gs(),{appearance:s}=xSe(`${e}:new-agent`);return(0,t.jsx)(T_,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(eat,"AgentBasicsCharacter");function bSe({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!Ac(),c=X({queryKey:P.instance.experimentalSettings,queryFn:Or.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}=X({queryKey:P.adapters.all,queryFn:ch.list,enabled:e}),k=(j??[]).filter(C=>C.loaded&&!C.disabled&&gSe(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Nh(C.type).comingSoon),S=k.some(C=>C.type===h);return(0,t.jsx)(Vs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Qs,{className:W("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",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)(Pn,{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)(eat,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Js,{className:"text-3xl font-semibold tracking-tight",children:b==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(yn,{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)(pt,{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=Nh(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)(vs,{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)(gl,{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)(el,{className:"size-4"})]})]})]})]})})}r(bSe,"AgentBasicsDialog");var tat={subscription:"Subscription",api:"API"};function sat({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)(eS,{initial:!1,mode:"sync",children:(0,t.jsx)(fl.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:Yee},animate:{opacity:1,y:0,transition:NZe},exit:{opacity:0,y:Yee,transition:SZe},children:tat[e]},e)})})}r(sat,"CredentialTag");function nat({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)(sat,{mode:s})]})}r(nat,"ModelSourceTile");function vSe({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)(eS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(fl.div,{layout:!0,transition:vNe,exit:{opacity:0,transition:DZe},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(nat,{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(vSe,"ModelSourceTiles");var O$={subscription:"Use API key instead",api:"Use subscription instead"},rat={subscription:"api",api:"subscription"};function ySe({mode:e,onChange:s}){return(0,t.jsxs)("button",{type:"button",onClick:r(()=>s(rat[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(O$).map(n=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:O$[n]},n)),(0,t.jsx)(eS,{initial:!1,mode:"sync",children:(0,t.jsx)(fl.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:dW},exit:{opacity:0,transition:CZe},children:O$[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)(gl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(fl.div,{layout:!0,transition:AZe,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)(fl.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:TZe,children:[d==="spinner"?(0,t.jsx)(nt,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(el,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(jSe,"FooterNav");function wSe({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onBack:l,testConnection:c,testError:d,managedAccount:u}){const h=X({queryKey:P.health,queryFn:su.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"),[T,R]=(0,m.useState)(""),[A,D]=(0,m.useState)(!1),[M,$]=(0,m.useState)(null),[E,B]=(0,m.useState)(null),z=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",F=Yke(e,q),K=u?{...F,options:[],subscriptions:[],loading:!1}:F,[G,se]=(0,m.useState)(null),ee=K.subscriptions.length?K.subscriptions.find(ge=>ge.id===(G??K.subscriptions[0]?.id)):void 0,[ne,he]=(0,m.useState)(null),Z=K.options.find(ge=>ge.id===(ne??K.options[0]?.id)),re=u?{...K.storedLogin,data:void 0,isPending:!1,isError:!1}:K.storedLogin,ce=(0,m.useRef)(null),H=b??(K.subscriptions.length>0||s==="claude_local"&&!ee&&re.data?"subscription":K.options.length?"api":"subscription"),Q=H==="api"?"api_key":"subscription",Y=u?.intent.connectionId&&(u.fixedMethod!==!1||u.initialMethod===Q),te=u?{...u.intent,connectionId:Y?u.intent.connectionId:void 0,name:Y?u.intent.name:u.nameForMethod?.(Q)??u.intent.name}:void 0,ae=pwe(e,te??{provider:U,method:"subscription",name:`My ${z} subscription`,ownership:"personal",agentIds:[],allAgents:!0},p&&H==="subscription"&&!ee&&!re.data,{allowHostClaude:h.data?.deploymentMode==="local_trusted"}),me=X({queryKey:P.agents.authSignal(e,s,n),queryFn:r(()=>Lt.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!u});async function oe(){if(A||u?.disabled)return;const ge=++f.current;D(!0),$(null);try{if(u&&te){if(H==="subscription"&&!p)return;const ue=ce.current??await(H==="api"?Kc.create(e,{...te,method:"api_key",apiKey:T.trim()}):ae.connect(te));ce.current=ue,R(""),ge===f.current&&u.onComplete({...ue,method:H==="api"?"api_key":"subscription"});return}let be=H==="api"?Z?Z.aiConnection?{env:{},aiConnection:Z.aiConnection}:{env:{[q]:Z.binding}}:E??{env:{},credentials:{[q]:T.trim()}}:{...ee?.aiConnection?{aiConnection:ee.aiConnection}:{},env:ee?.binding?{CODEX_HOME:ee.binding}:{},...s==="claude_local"&&!ee&&re.data?{env:Bw(),applyStoredClaudeLogin:!0}:{}};if(H==="subscription"&&p&&!ee&&!re.data&&(ce.current??=await ae.connect(),be={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}}),be.credentials&&(await Kc.create(e,{provider:U,method:"api_key",name:`My ${z} API`,ownership:"personal",apiKey:be.credentials[q],agentIds:[],allAgents:!0}),be={env:{},aiConnection:{provider:U,method:"api_key",mode:"responsible_user"}}),ge!==f.current)return;H==="api"&&(R(""),Z||B(be));const le=await c(be);if(ge!==f.current)return;le?o(be):$("The provider did not respond. Check the connection and try again.")}catch(be){if(ge!==f.current)return;u&&R(""),$(be instanceof Error?be.message:"Could not connect to the provider.")}finally{ge===f.current&&D(!1)}}r(oe,"connect");const ie=H==="subscription"&&a&&n&&!ee&&!K.loading&&!re.data&&(!!u||me.data?.status!=="present"||G==="");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(vSe,{label:"Connect your model provider",sources:[{id:s,label:z,icon:(0,t.jsx)(kW,{type:s})}],mode:H,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:H,onChange:r(ge=>{x(),N(j),ce.current=null,v(ge),R(""),B(null),$(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","."]}),H==="subscription"&&K.subscriptions.length>0&&(0,t.jsx)(dk,{options:K.subscriptions,value:ee?.id??"",onChange:se,loading:!1,error:!1,kind:"subscription",disabled:A}),(0,t.jsx)(fl.div,{initial:!1,animate:{height:j?"auto":0,opacity:j?1:0},transition:{height:_d,opacity:VM},className:"overflow-hidden",children:j&&(0,t.jsx)("div",{className:"pt-5",children:H==="api"?(0,t.jsxs)(HM,{instruction:K.options.length?"Choose a saved API key or enter a new one":`Provide your ${z} API key to connect`,children:[(0,t.jsx)(dk,{...K,value:Z?.id??"",disabled:A,onChange:r(ge=>{he(ge),R(""),B(null),$(null)},"onChange")}),!Z&&(0,t.jsx)(GM,{label:"API key",masked:!0,autoFocus:!0,value:T,placeholder:E?"Key entered. Retry the connection.":"Enter API key here",onChange:r(ge=>{he(""),R(ge),B(null)},"onChange"),onSubmit:r(()=>{oe()},"onSubmit"),disabled:A})]}):ie?(0,t.jsx)(jW,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:te??{provider:U,method:"subscription",name:`My ${z} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(ge=>{k(ge),C(be=>ge?be==="preparing"?"ready":be:"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){$("The login did not return a saved connection. Try again.");return}const le=f.current;C("connecting"),Kc.loginResult(e,ge).then(ue=>{le===f.current&&u.onComplete({...ue,method:"subscription"})}).catch(()=>{le===f.current&&(C("ready"),$("Could not retrieve the saved connection. Go back and retry."))});return}const be={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}};B(be),o(be)},"onConnected")}):ee?null:p&&!re.data?(0,t.jsx)(uW,{adapterType:s,login:{...ae,retry:r(()=>{$(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."})})}),H==="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&&ie?S==="waiting"?"Waiting for code":S==="connecting"?"Connecting":`Sign in to ${z}`:A?"Connecting":H==="subscription"&&(re.data||ee)?"Use saved subscription":H==="api"&&Z?"Use saved API key":"Connect",primaryDisabled:u?.disabled||!!u&&H==="subscription"&&!a&&!p||i&&h.isPending||ae.preparing||!!ae.error||!u&&me.isPending||K.loading||s==="claude_local"&&re.isPending||!j&&!(H==="subscription"&&ee)||!!ie&&(!w||S!=="ready")||H==="api"&&!T.trim()&&!E&&!Z,loading:A,primaryIcon:j&&ie?S==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(ie){if(!w||S!=="ready")return;window.open(w,"_blank","noreferrer,noopener"),C("waiting")}else oe()},"onPrimary")})]})}r(wSe,"AgentProviderConnection");function w5(e){return e.provider==="openrouter"?(0,t.jsx)(iat,{...e}):(0,t.jsx)(aat,{...e})}r(w5,"AiConnectionCredentialStep");function aat({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=Mt(),k=X({queryKey:P.environments.list(e),queryFn:r(()=>Ri.list(e),"queryFn")}),S=X({queryKey:P.environments.capabilities(e),queryFn:r(()=>Ri.capabilities(e),"queryFn")}),C=X({queryKey:P.instance.settings,queryFn:Or.get}),I=X({queryKey:P.instance.experimentalSettings,queryFn:Or.getExperimental}),T=X({queryKey:P.instance.generalSettings,queryFn:Or.getGeneral}),R=yW(T.data?.executionMode,k.data??[]);let A=null,D;try{A=R.forced?R.kubernetesEnvironment?.id??null:Zk({agentDefaultEnvironmentId:p??j,instanceDefaultEnvironmentId:C.data?.defaultEnvironmentId,localDefaultEnvironmentId:tN(k.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:eN(k.data),visibleEnvironmentIds:k.data?.map(F=>F.id)})}catch(F){D=F instanceof Error?F.message:"Could not resolve the sign-in environment."}const M=(k.data??[]).filter(F=>F.status==="active"&&(F.driver==="local"||F.driver==="sandbox"&&typeof F.config.provider=="string"&&S.data?.sandboxProviders?.[F.config.provider]?.supportsLoginPty===!0));!R.forced&&!p&&!j&&!M.some(F=>F.id===A)&&(A=M[0]?.id??null);const $=k.data?.find(F=>F.id===A),E=typeof $?.config.provider=="string"?$.config.provider:"",B=$?.driver==="sandbox"&&S.data?.sandboxProviders?.[E]?.supportsLoginPty===!0,z=[k,S,C,I,T].some(F=>F.isPending),q=D??[k,S,C,I,T].find(F=>F.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)(pt,{value:b,onChange:r(F=>v(F.target.value),"onChange"),disabled:!!i})]}),!p&&!R.forced&&M.length>1&&(0,t.jsxs)(Da,{value:A??"",onValueChange:N,children:[(0,t.jsx)(Ma,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Ea,{placeholder:"Sign-in environment"})}),(0,t.jsx)(Pa,{children:M.map(F=>(0,t.jsx)(Sn,{value:F.id,children:F.name},F.id))})]}),q&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:q}),z?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(wSe,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:A,canLogin:B,localEnvironment:$?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:U,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:z||!!q||!b.trim(),onComplete:r(F=>{w.invalidateQueries({queryKey:["ai-connections",e]}),f(F)},"onComplete")}},A??"local")]})}r(aat,"SubscriptionConnectionStep");function iat({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=Mt(),j=je({mutationFn:r(()=>Kc.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)(pt,{value:p,onChange:r(N=>f(N.target.value),"onChange"),disabled:!!n})]}),j.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error.message}),(0,t.jsx)(kNe,{providerName:"OpenRouter",value:x,onChange:b,onSubmit:r(()=>j.mutate(),"onSubmit"),disabled:j.isPending,placeholder:"Enter API key here",autoFocus:!0}),(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)(L,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)(L,{disabled:!p.trim()||!x.trim()||j.isPending,onClick:r(()=>j.mutate(),"onClick"),children:j.isPending?"Connecting…":"Connect"})]})]})}r(iat,"ApiKeyConnectionStep");var oat=null;function sS(){const e=(0,m.useContext)(fI),{data:s,isFetched:n,isError:a}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn"),enabled:e!=null},e??(oat??=new IN));return e?{enabled:!a&&s?.enableChatConnectors===!0,loaded:n}:{enabled:!1,loaded:!0}}r(sS,"useChatConnectorsEnabled");var lat=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function kSe(e){return e.replace(lat,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(kSe,"sanitizeProsumerCopy");var cat={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."}},dat={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function NSe(e,s){const n=cat[e];if(n)return n;if(s){const a=kSe(s);if(a)return{tagline:a,short:a}}return dat}r(NSe,"appCopyFor");function Dte(e,s,n){return n<=1?`Your ${e} key`:kSe(s)||`Your ${e} key`}r(Dte,"credentialFieldLabel");var uat=1500;function Cp(e=uat){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 ha(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 NW(){const e=Gc()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await ha(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(NW,"useCopyToast");var mat="/cloud/connections/handoff",hat="/cloud/connections/reauth",k5="paperclip.cloud-oauth-handoff.v1",tg=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function SW(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new tg("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 tg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(SW,"parseHandoff");function pat(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new tg("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new tg("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new tg("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(pat,"handoffFailure");async function fat(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(mat,{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 tg(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(fat,"postCloudHandoff");function xat(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!==hat||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(xat,"exactReauthenticationTarget");async function nN(e,s={}){const n=SW(e.handoff);if(!n){const l=Y3(e.authorizationUrl);if(!l.ok)throw new tg(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await fat(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=xat(i.reauthenticationUrl,n.session);if(l)return l}throw pat(a.status,i?.error)}const o=Y3(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new tg("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(nN,"prepareOAuthNavigation");function R_(e,s=window.sessionStorage){const n=SW({kind:"paperclip_cloud",session:e});if(!n)throw new tg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(k5,JSON.stringify(a))}r(R_,"savePendingCloudHandoff");function gat(e=window.sessionStorage){const s=e.getItem(k5);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 SW({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(k5),null}}r(gat,"readPendingCloudHandoff");function Lte(e=window.sessionStorage){e.removeItem(k5)}r(Lte,"clearPendingCloudHandoff");function ZM(e){return!!(e&&fpe({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(ZM,"appSupportsToolCatalogSetup");var bat=SDe.filter(e=>gpe(e).some(s=>tp(s))).map(e=>e.slug);function vat(e){return bat.some(s=>s===e)}r(vat,"isMcpDirectOAuthConnectSlug");function E_(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(E_,"appSourceConnectHref");function yat(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(yat,"appSourceResumeHref");function F$(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(F$,"vercelConnectSourceHref");function jat(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(jat,"resolveAppsConnectRouteKey");function wat(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=SN(n);return!s&&a?.methods.some(i=>i.transport==="chat_sdk")&&!a.methods.some(i=>(i.purpose??"tool")!=="channel"&&i.transport!=="chat_sdk")?!1:hI(n)&&e.get("reconnect")?.trim()?!0:n==="agentmail"||s?fpe(a):ZM(a)}r(wat,"canEnterAppsConnect");var B$=" for the organization",kat=" for the company";function $te(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(B$)?n:a.endsWith(kat)?`${n.slice(0,n.length-16).trimEnd()}${B$}`:`${n}${B$}`}r($te,"connectionNameForGrantKind");function Nat(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(Nat,"grantStatusLabel");function Sat(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(Sat,"grantStatusTone");function Cat(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(Cat,"grantAccountLabel");function _at(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(_at,"audienceUserIds");function Iat(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(Iat,"organizationGrant");function Aat(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(Aat,"personalGrantFor");function Tat(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(Tat,"memberLabel");var Ote=0;function Yq(){return Ote+=1,{id:`header-${Ote}`,name:"",value:""}}r(Yq,"newCustomHeaderRow");function S1(e){try{return new URL(e).host||null}catch{return null}}r(S1,"endpointHost");function SSe(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(SSe,"oauthCallbackUrlForBrowser");function z$(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(z$,"defaultGenericMcpName");function Fte(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(Fte,"genericConnectGuidance");function CSe(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=ULe(a);if(!i.ok)return xJ(a,i.reason);const o=gLe(n.value);if(!o.ok)return xJ(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(CSe,"customHeaderError");function Rat(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(Rat,"genericConnectPayload");function Eat(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&&CSe(e.headers)===null:!0:!1}r(Eat,"canSubmitGenericConnect");function rN(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(rN,"installStateFrom");function _Se(e,s){return e.onAll||e.agentIds.has(s)}r(_Se,"isAgentInstalled");function ISe(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(ISe,"installPayload");var Pat="Has access — tick to load its tools into this agent's context.";function ASe(e){return`paperclip.connector-enrollment-access:${e}`}r(ASe,"enrollmentAccessStorageKey");function Mat(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(Mat,"validEnrollmentAccessState");function Dat(e,s,n){try{window.sessionStorage.setItem(ASe(s),JSON.stringify({...n,companyId:e}))}catch{}}r(Dat,"saveEnrollmentAccessState");function Lat(e){const s=ASe(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Mat(a)?a:null}catch{return null}}r(Lat,"consumeEnrollmentAccessState");function Bte(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(Bte,"githubRecoveryUrl");function zte(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(zte,"oauthCallbackErrorMessage");var $at={key:"setup",success:"complete"};function qte(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(qte,"requestedConnectionInitialStep");function Oat(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 hg(n)!==e.requestedAppKey?null:hI(e.requestedAppKey)}r(Oat,"requestedConnectionEntry");function Fat(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?hg(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(Fat,"retainedReconnectMatches");function Bat(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(Bat,"isVercelConnectUnavailable");function zat(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(zat,"isConnectionDefinitionUnavailable");function qat(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(qat,"requestedConnectionSetupResolution");function Ute(e,s,n,a){const i=$at[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(Ute,"appConnectHref");function $2(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($2,"withConnectionIntent");var Kte=["Pick app","Add your key"],Wte={gallery:0,key:1},Uat={key:0},Kat=["Add MCP URL"],Wat=["Sign in"];function q$(e,s=!1){return s&&e?.auth!=="none"&&(!e?.grantKinds||e.grantKinds.includes("user"))?"user":e?.grantKinds?.length===1||e?.grantKinds&&!e.grantKinds.includes("organization")?e.grantKinds[0]:"organization"}r(q$,"defaultGrantKindFor");function Vat(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(Vat,"configuredAgentIdentity");function zC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(zC,"isGoogleSheetsRobotMethod");function ZS(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(ZS,"defaultMethodConfig");function kw(e,s){if(!e)return[];const n=nA(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(kw,"connectionMethodsForCredentialSource");function nA(e){return gpe(e).filter(s=>(s.purpose??"tool")!=="channel")}r(nA,"availableToolConnectionMethods");function O2(e,s){const n=nA(e);return s?n.find(a=>a.key===s)??null:q8(n)}r(O2,"availableToolConnectionMethod");function mk(e){return q8(e)}r(mk,"recommendedSetupConnectionMethod");function Vte(e){return mk(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(Vte,"recommendedManagedConnectorMethod");function Hte(e){if(!e)return!1;const s=nA(e),n=s.length===1?s[0]:null;return!!(n&&tp(n)&&!DDe(n))}r(Hte,"canUseAutomaticOAuthFastPath");function Gte(e){if(!e)return null;const s=nA(e),n=s.length===1?s[0]:null;return n&&tp(n)?n:null}r(Gte,"automaticOAuthMethod");function Hat(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(Hat,"appSourceSlug");function Gat(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(Gat,"connectionSourceSlug");function Qte(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&Hat(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)||Gat(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(Qte,"reusableOAuthConnection");function TSe(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(TSe,"readConnectionIntentOAuthOutcome");function e4(e={}){const[s]=hi(),n=ga(),{selectedCompanyId:a}=gs(),i=_9(),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&&u1(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||u1(l)||A3(l))),h=X({queryKey:["tools","connection",d],queryFn:r(()=>es.getConnection(d),"queryFn"),enabled:u}),p=l||h.data?.config?.sourceTemplateKey,f=s.get("method")||h.data?.config?.connectionMethodKey;if(u&&h.isPending)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection…"});if(u&&h.isError)return(0,t.jsxs)("div",{role:"alert",className:"space-y-3 p-6",children:[(0,t.jsx)("p",{children:"Could not load this connection. Your saved access and credentials have not changed."}),(0,t.jsx)(L,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(A3(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"&&u1(p)&&(!f||LR(p,f))){const x=Mpe(p,s.get("targetToolkit"));return(0,t.jsx)(kHe,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(Qat,{...e})}r(e4,"ConnectionSetupFlow");function Qat({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=Mt(),S=Ln(),C=(0,m.useCallback)((yt,Ne)=>{o==="page"&&(Ne?S(yt,Ne):S(yt))},[o,S]),I=ga(),{selectedCompany:T,selectedCompanyId:R}=gs(),{enabled:A}=sS(),{enabled:D}=_9(),{setBreadcrumbs:M}=Fn(),{pushToast:$}=pi(),[E]=hi(),B=d?.trim()||E.get("intent")?.trim()||null,z=I.appKey??E.get("appKey")??void 0,q=E.get("source")?.trim()||null,U=u||E.get("new")==="1",F=E.get("stage")?.trim()||null,K=E.get("method")?.trim()||null,G=E.get("resume")?.trim()||null,se=E.get("oauth"),ee=E.get("code"),ne=Bte(E.get("installation_url")),he=Bte(E.get("management_url")),Z=p?.id??(E.get("reconnect")?.trim()||null),re=E.get("identity")==="user"?"user":E.get("identity")==="organization"?"organization":null,ce=i==="vercel_connect",H=l??q,Q=i==="paperclip_vault"&&vat(H)?H:null,Y=jat({serviceSlug:l,appKey:z,sourceSlug:q}),te=(l??q??z)==="zapier",ae=te?void 0:Y,me=!!p||o==="page"&&(a||E.get("byo")==="1"),[oe]=(0,m.useState)(()=>o==="page"&&E.get("cloud_connector")==="enrolled"&&ae?Lat(ae):null),[ie]=(0,m.useState)(()=>{const yt=E.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(yt)?yt:"",name:p?.name??E.get("name")?.trim()??"",applicationId:p?.applicationId??(E.get("applicationId")?.trim()||void 0)}}),[ge,be]=(0,m.useState)(()=>qte({requestedAppKey:ae,routeStage:F,resumeConnectionId:G,hasPrefilledLink:!!ie.link,zapierSource:te})),[le,ue]=(0,m.useState)(null),[Se,ye]=(0,m.useState)(""),[Ie,Ke]=(0,m.useState)(ie.link),[rt,dt]=(0,m.useState)(ie.name||(te?"Zapier":"")),[de,ze]=(0,m.useState)(!1),[gt,bt]=(0,m.useState)(""),[De,Qe]=(0,m.useState)("auto"),[mt,Ye]=(0,m.useState)(()=>[Yq()]),[it,Nt]=(0,m.useState)(""),[Ze,Pe]=(0,m.useState)(""),[Ce,Ve]=(0,m.useState)(!1),[Ge,ot]=(0,m.useState)(null),[Ee,Je]=(0,m.useState)(!1),[_e,He]=(0,m.useState)({}),[ns,fe]=(0,m.useState)(""),[ct,Ue]=(0,m.useState)(""),[Et,$t]=(0,m.useState)(""),[js,Fe]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[xt,Wt]=(0,m.useState)(null),[Cs,Ts]=(0,m.useState)({}),[Ct,ds]=(0,m.useState)(""),[Oe,xe]=(0,m.useState)(null),[Gt,Pt]=(0,m.useState)(null),[os,ws]=(0,m.useState)({}),[Hs,tr]=(0,m.useState)("all"),[Le,et]=(0,m.useState)(new Set),[vt,$e]=(0,m.useState)(()=>new Set(oe?.agentIds??(c?[c]:[]))),[Ft,wt]=(0,m.useState)(oe?.grantKind??re??(c?"user":"organization")),[Yt,Zt]=(0,m.useState)(oe?.installChoice??(c?"specific":"all")),us=!!(G&&(se==="failed"||se==="denied")),[ht,kt]=(0,m.useState)(us?"error":"entry"),[Rs,hs]=(0,m.useState)(()=>us?zte(se,ee):null),[jn,Es]=(0,m.useState)(null),an=(0,m.useRef)(!1),Jt=(0,m.useRef)(!1),Xs=(0,m.useRef)(null),Zs=(0,m.useRef)(null),[qr,pr]=(0,m.useState)(null),jr=(0,m.useRef)(null),[mn,Zn]=(0,m.useState)(null),[Tr,Wr]=(0,m.useState)(null),ut=(0,m.useRef)(null),[rs,Ls]=(0,m.useState)(h.length>0&&!!f),[Os,Us]=(0,m.useState)(null),[Ps,fr]=(0,m.useState)(null),[xr,wr]=(0,m.useState)(null),nr=(0,m.useCallback)(()=>{o!=="dialog"||jr.current?.closed===!1||(jr.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),Fr=(0,m.useCallback)(yt=>{if(o!=="dialog"){Mm(yt);return}Wr(yt);const Ne=jr.current;if(!Ne||Ne.closed){kt("error"),hs("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),j?.("needs_retry");return}Ne.location.assign(yt),Ne.focus()},[o,j]),kr=(0,m.useCallback)(()=>{jr.current=null,hs(null),kt("redirecting"),j?.("authorizing")},[j]);(0,m.useEffect)(()=>{if(o!=="dialog"||ht!=="redirecting")return;const yt=window.setInterval(()=>{jr.current?.closed&&(kt("error"),hs("The sign-in window closed. If authorization did not finish, try again."),Wr(null),j?.("needs_retry"))},1e3);return()=>window.clearInterval(yt)},[o,ht,j]);const _t=(0,m.useCallback)(async yt=>{ut.current?.abort();const Ne=new AbortController;ut.current=Ne;try{const at=await nN(yt,{signal:Ne.signal});if(at.kind==="reauthentication"){const It=o==="dialog"?jr.current:window;if(!It||It.closed||!yt.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");R_(yt.handoff.session,It.sessionStorage),kt("starting")}else Es(at.host),kt("redirecting");Fr(at.url)}catch(at){if(Ne.signal.aborted)return;kt("error"),hs(at instanceof Error?at.message:"Paperclip couldn’t start secure sign-in. Try again."),j?.("needs_retry")}finally{ut.current===Ne&&(ut.current=null)}},[o,j,Fr]);(0,m.useEffect)(()=>()=>ut.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!B)return;const yt=r(Ne=>{const at=TSe(Ne,window.location.origin,B);if(at==="connected"){kt("entry"),Wr(null),x?.({resolvedByCallback:!0});return}if(at==="declined"){kt("error"),hs("Authorization was cancelled. You can try again."),j?.("needs_retry");return}at==="failed"&&(kt("error"),hs("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",yt),()=>window.removeEventListener("message",yt)},[B,o,x,b]),(0,m.useEffect)(()=>{if(o!=="dialog"||B||!mn)return;let yt=!1,Ne=!1;const at=window.setInterval(async()=>{if(Ne||yt)return;const It=jr.current;if(!It||It.closed){Zn(null),kt("error"),hs("The sign-in window closed. Try again to finish connecting GitHub.");return}let ps;try{ps=new URL(It.location.href)}catch{return}if(!(ps.origin!==window.location.origin||!ps.pathname.includes(mn))){if(ps.searchParams.has("oauth")){Zn(null),kt("error"),hs("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(ps.searchParams.get("success")==="1"){Ne=!0;try{const Bs=await es.getConnection(mn);!yt&&Bs.status==="active"&&(Zn(null),It.close(),x?.({connectionId:Bs.id}))}catch{yt||(Zn(null),kt("error"),hs("Could not confirm the connection. Try again."))}finally{Ne=!1}}}},1e3);return()=>{yt=!0,window.clearInterval(at)}},[B,mn,o,x]);const qs=r(()=>{Qe("auto"),Ye([Yq()]),Nt(""),Pe(""),Ve(!1),ot(null),Je(!1)},"resetGenericAuthState"),hn=r(yt=>{if(o==="page"&&!B&&i==="paperclip_vault"&&u1(yt.slug)){C(`/apps/connect?source=${yt.slug}`);return}if(yt.slug==="zapier"){ue(null),ye(""),Ke(""),dt("Zapier"),ze(!1),bt(""),qs(),He({}),Pt(null),be("key"),C($2("/apps/connect?source=zapier",B));return}if(i==="paperclip_vault"&&Hte(yt)){C(E_(yt.slug,B));return}ue(yt),ye(yt.name),Ke(""),dt(""),ze(!1),bt(""),qs(),He({}),fe(""),Ue(""),$t("");const Ne=mk(kw(yt,i));Fe(Ne?.key??""),Ts(ZS(Ne)),ds(""),xe(null),Pt(null),$e(new Set(c?[c]:[])),Zt(c?"specific":"all"),wt(Br??q$(Ne,!!c)),be("key"),C(i==="vercel_connect"?$2(F$(yt.slug),B):E_(yt.slug,B))},"useMatchedGalleryEntry"),tt=r(()=>{be("gallery"),C($2(i==="vercel_connect"?F$():a?"/apps/byo":"/apps",B))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return M([{label:"Connectors",href:"/apps"},{label:ce?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>M([])},[a,o,M,ce]);const Dt=X({queryKey:P.apps.gallery(R??"__none__"),queryFn:r(()=>es.listGallery(R),"queryFn"),select:(0,m.useCallback)(yt=>B?{...yt,apps:yt.apps.map(Ne=>({...Ne,methods:Ne.methods.filter(at=>v?at.ai?.provider===v.provider&&(v.mode==="responsible_user"||at.ai.method===v.method):at.transport!=="runtime_auth")})).filter(Ne=>Ne.methods.length>0)}:yt,[B,v?.provider,v?.method,v?.mode]),enabled:!!R}),xs=(0,m.useMemo)(()=>(Dt.data?.apps??[]).filter(yt=>D||!A3(yt.slug)).filter(yt=>yt.slug==="agentmail"||A||!yt.methods.some(Ne=>Ne.transport==="chat_sdk")||ZM(yt)),[Dt.data,A,D]),Gs=ae?hI(ae):null,Bn=Gs?.methods.find(yt=>Jw(yt)&&!tp(yt)),Cr=!(Bn&&js===Bn.key)&&!!Gs?.methods.some(yt=>yt.oauthStrategy==="paperclip_cloud_connector"||yt.oauthStrategy==="paperclip_id_connector"),Qr=!!le?.methods.some(yt=>yt.oauthStrategy==="paperclip_cloud_connector"||yt.oauthStrategy==="paperclip_id_connector"),Nr=le&&Cr&&!Qr?Vte(Gs):null,[Rr,cr]=(0,m.useState)(null),rr=X({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>es.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Rr?2e3:!1,enabled:!!(R&&Cr&&!Qr)}),[sr,Va]=(0,m.useState)(null),Ta=(0,m.useCallback)(()=>{jr.current?.close(),jr.current=null,cr(null)},[]),$s=(0,m.useCallback)(()=>{!R||!ae||Dat(R,ae,{grantKind:Ft,installChoice:Yt,agentIds:Yt==="specific"?[...vt]:[]})},[Ft,vt,Yt,ae,R]),pn=(0,m.useCallback)(yt=>{const Ne=Y3(yt);if(!Ne.ok){Ta(),Va(Ne.message);return}if(o==="dialog"){cr(Ne.url);const at=jr.current;at&&!at.closed?(at.location.assign(Ne.url),at.focus()):Va("Open authorization in a new tab to continue.");return}Mm(Ne.url)},[o,Ta]);(0,m.useEffect)(()=>{!Rr||rr.data?.status!=="active"||(Ta(),Va(null),Dt.refetch())},[Rr,rr.data?.status,Dt.refetch,Ta]);const dr=je({mutationFn:r(()=>es.startCloudConnectorEnrollment(R,T?.name,ae?Ute(ae,"key",i,{resumeConnectionId:G,reconnectConnectionId:Z,interactionId:B})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(yt=>{if(!yt.verificationUrl){Ta(),Va("Paperclip Cloud did not return an enrollment link. Try again.");return}pn(yt.verificationUrl)},"onSuccess"),onError:r(yt=>{Ta(),Va(yt instanceof Error?yt.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),Yn=X({queryKey:P.tools.applications(R??"__none__"),queryFn:r(()=>es.listApplications(R),"queryFn"),enabled:!!R&&(!!Q||!!G||!!Z),refetchOnMount:"always"}),wn=X({queryKey:P.tools.connections(R??"__none__"),queryFn:r(()=>es.listConnections(R),"queryFn"),enabled:!!R&&(!!Q||!!G||!!Z),refetchOnMount:"always"}),Vr=(0,m.useMemo)(()=>u?null:Qte(Q,Yn.data?.applications??[],wn.data?.connections??[],U?{applicationId:ie.applicationId,draftOnly:!0}:{}),[Yn.data,wn.data,U,Q,ie.applicationId,u]),as=(0,m.useMemo)(()=>Z?(wn.data?.connections??[]).find(yt=>yt.id===Z)??null:null,[wn.data,Z]),Mn=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!wn.isFetchedAfterMount||!as||Mn.current===as.id)return;const yt=as.config?.url??as.transportConfig?.url??as.transportConfig?.serverUrl??as.config?.serverUrl;typeof yt!="string"||!/^https?:\/\//i.test(yt)||(Mn.current=as.id,Ke(Ne=>Ne||yt))},[p,wn.isFetchedAfterMount,as]);const $n=(0,m.useMemo)(()=>as?(Yn.data?.applications??[]).find(yt=>yt.id===as.applicationId)??null:null,[Yn.data,as]),zn=Fat({requestedAppKey:ae,byo:me,applicationId:ie.applicationId,reconnectConnection:as,reconnectApplication:$n}),Cn=(0,m.useMemo)(()=>G?(wn.data?.connections??[]).find(yt=>yt.id===G)??null:null,[wn.data,G]),Er=Cn??as,Br=Er?Er.credentialPolicy==="per_user"?"user":Er.credentialPolicy==="per_agent"?"agent":"organization":re,we=Cn?.authKind==="oauth"?Cn:Vr,Xt=Vr?Vr.credentialPolicy==="per_user"?"user":Vr.credentialPolicy==="per_agent"?"agent":"organization":null,fn=Br??Xt;(0,m.useEffect)(()=>{fn&&wt(fn)},[fn]);const br=(0,m.useMemo)(()=>Ie&&!le?d3(Ie,xs):null,[le,xs,Ie]),aa=le?O2(le,js||null):null,ei=aa&&tp(aa)?aa:Gte(le),ms=i==="paperclip_vault"&&ei?le:null,Ae=i==="paperclip_vault"&&Hte(le)?le:null,Ut=!!Q&&(!Yn.isFetchedAfterMount||!wn.isFetchedAfterMount),Ht=r(yt=>{be(yt),le&&C(Ute(le.slug,yt,i,{connectionMethodKey:le.methods.find(Ne=>Ne.key===js)?.ai?js:void 0,resumeConnectionId:G,reconnectConnectionId:Z,interactionId:B}))},"setAppStep"),cn=Cn??as??we,rn=le?.agentInstructions,er=le&&rn?xt?.slug===le.slug?xt.value:cn?cn.agentInstructions??{...Lk(rn),enabled:!1}:Lk(rn):null,Dr=!er||!!er.text.trim(),zt=je({mutationFn:r(async yt=>(er&&JSON.stringify(er)!==JSON.stringify(yt.agentInstructions)&&await es.updateConnection(yt.id,{agentInstructions:er}),es.startOAuth(yt.id,{asCurrentUser:yt.credentialPolicy==="per_user",...yt.credentialPolicy==="per_agent"?{asAgentId:Vat(yt)??[...vt][0]}:{},...B?{interactionId:B}:{}})),"mutationFn"),onSuccess:r(yt=>{_t(yt)},"onSuccess"),onError:r(yt=>{const Ne=yt instanceof un&&yt.body&&typeof yt.body=="object"?yt.body.details:null;kt("error"),j?.("needs_retry"),hs(Ne?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":yt instanceof Error?yt.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),ls=zt.mutate,_n=(0,m.useCallback)(yt=>{j?.("authorizing"),nr(),o==="dialog"&&!B&&Zn(yt.id),ls(yt)},[ls,j,nr,o,B]),ar=r(async yt=>{if(c)return;const Ne=ISe(R,(fn??Ft)!=="agent"&&Yt==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:vt});await es.putConnectionInstalls(yt,Ne)},"applyAccessInstalls"),dn=fn??Ft,ca=je({mutationFn:r(async yt=>{const Ne=yt??le;let at;if(Ne){const It=fn??Ft,ps=O2(Ne,js||null),Bs=zC(Ne,ps)?eq(Ct).ids:[],ja=Se.trim(),ia=$te(ja||Ne.name,It);at=await es.connectApp(R,{galleryKey:Ne.slug,...er?{agentInstructions:er}:{},...js?{connectionMethodKey:js}:{},name:ia,credentialSource:i,...i==="paperclip_vault"?{credentialValues:_e}:{},...i==="vercel_connect"?{vercelConnect:{connector:Et.trim()}}:{},...ns.trim()?{oauthClient:{clientId:ns.trim(),...ct?{clientSecret:ct}:{}}}:{},configValues:zC(Ne,ps)?{allowedSpreadsheetIds:Bs}:Object.keys(Cs).length>0?Cs:void 0,applicationId:ie.applicationId,...G??Xs.current?{resumeConnectionId:G??Xs.current}:Z?{reconnectConnectionId:Z}:{},...It!=="organization"?{grantKind:It}:{},...It==="agent"?{subjectAgentId:[...vt][0]}:{}}),Xs.current=null}else{const It=Rat({link:Ie,name:rt,authMode:De,needsKey:de,keyValue:gt,headers:mt,oauthClientId:it,oauthClientSecret:Ze}),ps=$te(It.name??z$(Ie)??"Custom app",dn);at=await es.connectApp(R,{...It,...Z?{reconnectConnectionId:Z}:{},...te||br?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:ps,applicationId:ie.applicationId,...dn!=="organization"?{grantKind:dn}:{},...dn==="agent"?{subjectAgentId:[...vt][0]}:{}})}return at.auth?.kind==="oauth"&&!G&&!Z&&await ar(at.connectionId),at},"mutationFn"),onSuccess:r(yt=>{if(yt.auth?.kind==="oauth"){if(Pt(yt),yt.auth.manualClientRequired){ot(Fte("oauth_manual_client_required",null)),Qe("oauth"),Ve(!0),Je(!1);return}if(o==="dialog"||B){kt("starting"),Je(!le),_n(yt.connection);return}const at=yt.auth.startUrl?.trim();if(!at){kt("starting"),Je(!0),_n(yt.connection);return}Je(!0),_t({authorizationUrl:at,handoff:yt.auth.handoff});return}ot(null),Pt(yt);const Ne={};for(const at of yt.actions.readOnly)Ne[at.catalogEntryId]=!0;for(const at of yt.actions.canMakeChanges)Ne[at.catalogEntryId]=!0;ws(Ne),zi.mutate({result:yt,enabled:Ne})},"onSuccess"),onError:r(yt=>{const Ne=yt instanceof un&&yt.body&&typeof yt.body=="object"?yt.body.details:null;if(ms){kt("error"),j?.("needs_retry"),hs(Ne?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":yt instanceof Error?yt.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!le&&Ie){const at=typeof Ne?.code=="string"?Ne.code:null,It=Fte(at,yt instanceof Error?yt.message:null);ot(It),Je(!1),It.focus==="credentials"&&(ze(!0),Ve(!0));return}$({title:"Couldn’t connect",body:yt instanceof Error?yt.message:"Please check your key and try again.",tone:"error"})},"onError")}),ur=ca.mutate,Ei=(0,m.useCallback)(yt=>{const Ne=yt??le;(Ne?O2(Ne,js||null):null)?.auth==="oauth"&&nr(),ur(yt)},[js,le,ur,nr]);(0,m.useEffect)(()=>{if(!ae||Dt.isLoading||!Dt.data||Z&&(!wn.isFetchedAfterMount||!Yn.isFetchedAfterMount))return;const yt=Oat({requestedAppKey:ae,galleryApps:Dt.data.apps,reconnectConnection:as,applications:Yn.data?.applications??[]}),Ne=!!yt?.methods.some(Re=>Re.oauthStrategy==="paperclip_cloud_connector"||Re.oauthStrategy==="paperclip_id_connector");if(Cr&&!Ne&&rr.isLoading)return;const at=kw(yt,i),It=v??(as?.connectionPurpose==="ai"?gJ.safeParse(as.config?.ai).data:void 0),ps=at.find(Re=>It?Re.ai?.provider===It.provider&&(!("mode"in It)||It.mode!=="responsible_user")&&Re.ai.method===It.method:Re.key===K)??(Cr&&!Ne?Vte(Gs):null)??mk(at),Bs=at.length===1?at[0]:null,ja=i==="paperclip_vault"&&!!Gte(yt),ia=Bat({credentialSource:i,available:Dt.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(Z&&zn)}),Ur=at.length===1&&Bs?.auth==="oauth"&&!tp(Bs)&&!Jw(Bs),_a=zat({available:yt?.availability?.available,reconnectConnectionId:Z,reconnectSourceMatches:zn}),Ti=qat({reconnectConnectionId:Z,hasRequestedEntry:!!yt,supportedMethodCount:at.length,unsupportedOAuth:Ur,vercelUnavailable:ia,definitionUnavailable:_a});if(Ti!=="ready"){if(ue(null),be("gallery"),Ti==="reconnect_unavailable"&&Z){wr(Z);return}C($2(i==="vercel_connect"?F$():"/apps/connect",B),{replace:!0});return}if(wr(null),!!yt){if(le?.slug!==yt.slug){ue(yt),ye(yt.name),Ke(""),dt(""),ze(!1),bt(""),He({}),fe(""),Ue(""),$t(""),Fe(ps?.key??""),Ts(ZS(ps)),ds(""),xe(null),Pt(null);const Re=oe?.companyId===R?oe:null;wt(Br??Re?.grantKind??q$(ps,!!c)),$e(new Set(Re?.agentIds??(c?[c]:[]))),Zt(Re?.installChoice??(c?"specific":"all")),be(qte({requestedAppKey:ae,routeStage:F,resumeConnectionId:G,hasPrefilledLink:!!ie.link,zapierSource:te}))}else Qr!==Ne&&(ue(yt),Fe(ps?.key??""),Ts(ZS(ps)));if(!(ja&&(!Yn.isFetchedAfterMount||!wn.isFetchedAfterMount))&&!(ja&&Jt.current)&&ja&&(Yn.isError||wn.isError)){kt("error"),hs("Paperclip couldn’t check for an existing connection. Try again."),be("key");return}}},[v,K,Yn.isError,Yn.isFetchedAfterMount,Yn.data,wn.isError,wn.isFetchedAfterMount,rr.data?.configured,rr.isLoading,js,i,le?.slug,Qr,Dt.data,Dt.isLoading,C,Br,as,Z,zn,G,Gs,ae,c,oe,F,te]),(0,m.useEffect)(()=>{Zs.current=null,pr(null)},[G]),(0,m.useEffect)(()=>{const yt=Cn??as;if(!yt||!le||Zs.current===yt.id)return;const Ne=V8(yt),at=typeof Ne.sourceTemplateKey=="string"?Ne.sourceTemplateKey:null;if(at&&at!==le.slug)return;const It=typeof Ne.connectionMethodKey=="string"?Ne.connectionMethodKey:null,ps=It?kw(le,i).find(ja=>ja.key===It)??null:null;if(ye(yt.name||le.name),ps){Fe(ps.key);const ja=Ne.methodConfig&&typeof Ne.methodConfig=="object"?Ne.methodConfig:{};Ts({...ZS(ps),...Object.fromEntries(Object.entries(ja).filter(ia=>typeof ia[1]=="string"||typeof ia[1]=="boolean"))})}const Bs=Ne.oauth&&typeof Ne.oauth=="object"?Ne.oauth:null;Bs?.clientRegistrationSource==="manual"&&typeof Bs.clientId=="string"&&fe(Bs.clientId),se==="failed"||se==="denied"?(kt("error"),hs(zte(se,ee))):(kt("entry"),hs(null)),be("key"),Zs.current=yt.id,pr(yt.id)},[i,le,ee,se,Cn,as]);const zi=je({mutationFn:r(async yt=>{const{result:Ne,enabled:at}=yt,It=Object.entries(at).filter(([,ia])=>ia).map(([ia])=>ia),ps=Wje(Ne,ia=>!!at[ia]),Bs=Yt==="all"?"all_agents":{agentIds:Array.from(vt)},ja=await es.finishApp(R,Ne.connectionId,{enabledCatalogEntryIds:It,askFirstCatalogEntryIds:ps,...er?{agentInstructions:er}:{},access:Bs,...c?{preserveExistingAccess:!0}:{}});return await ar(Ne.connectionId),ja},"mutationFn"),onSuccess:r(async(yt,Ne)=>{await k.invalidateQueries({queryKey:["tools"]}),await k.invalidateQueries({queryKey:P.apps.attention(R)}),Ht("success"),x?.({connectionId:Ne.result.connectionId})},"onSuccess"),onError:r(yt=>{Ht("key"),$({title:"Couldn’t finish setup",body:yt instanceof Error?yt.message:"Please try again.",tone:"error"})},"onError")});if(!R)return(0,t.jsx)("div",{className:"p-6 text-sm text-muted-foreground",children:"Select an organization to connect apps."});if((G||Z)&&(wn.isError||Yn.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[yt,Ne]=await Promise.all([wn.refetch(),Yn.refetch()]);!yt.isError&&!Ne.isError&&(hs(null),kt("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(G&&wn.isFetchedAfterMount&&!Cn)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(Z&&wn.isFetchedAfterMount&&Yn.isFetchedAfterMount&&(!as||!zn))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:as?"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((G||Z)&&Dt.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(()=>{Dt.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(Z&&xr===Z)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(G&&(!wn.isFetchedAfterMount||Dt.isLoading||!le||qr!==Cn?.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)(gn,{className:"h-8 w-48"}),(0,t.jsx)(gn,{className:"h-40 w-full rounded-xl"})]});if(Z&&(!wn.isFetchedAfterMount||!Yn.isFetchedAfterMount||Dt.isLoading||ae&&!le))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(gn,{className:"h-8 w-48"}),(0,t.jsx)(gn,{className:"h-40 w-full rounded-xl"})]});if(rs&&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)(N9,{choices:h.map(yt=>({id:yt.id,name:yt.name,description:yt.status==="active"&&yt.enabled?"Ready to use":"Setup needs attention"})),pendingId:Os,onSelect:r(async yt=>{Us(yt),fr(null);try{await f(yt)}catch(Ne){fr(Ne instanceof Error?Ne.message:"Couldn’t use this connection."),Us(null)}},"onSelect")}),Ps?(0,t.jsx)(da,{tone:"danger",className:"mt-4",children:Ps}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>Ls(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),N?(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:N,children:"Cancel"}):null]})]});const Lo=kw(le,i),Pi=Nr?[Nr]:Lo,Me=le?js?Pi.find(yt=>yt.key===js)??null:Pi[0]??null:null,Ns=le?Me?.auth??"none":De==="none"?"none":De==="oauth"?"oauth":"api_key",on=ge==="key"?((yt,Ne)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ESe,{extra:yt,forceOpen:Ne,companyId:R,sentence:e6({grantKind:dn,authKind:Ns,installChoice:Yt,installCount:vt.size,lockedAgentId:c??null,preserveAgentAccess:!!(ms&&(we||as))}),notice:[Dt.data?.capabilities?.canCreateOrganizationGrant===!1?Dt.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,Dt.data?.capabilities?.canSetCompanyInstall===!1?Dt.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(at=>!!at),authKind:Ns,grantKinds:fn?[fn]:Me?.grantKinds,grantKind:dn,setGrantKind:wt,installChoice:Yt,setInstallChoice:Zt,installAgentIds:vt,setInstallAgentIds:$e,lockedAgentId:c,capabilities:Dt.data?.capabilities,githubIdentity:le?.slug==="github",identityLoading:!!ms&&Ut,preserveAgentAccess:!!(ms&&(we||as)),disabled:ca.isPending||zt.isPending},"connection-defaults"),le&&rn&&er&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(k9,{provider:le.name,template:rn,value:er,onChange:r(at=>Wt({slug:le.slug,value:at}),"onChange"),disabled:ca.isPending||zt.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,ya=ms&&ei&&Jw(ei)?ei:null,Ha=ya&&ms?(0,t.jsx)(Zq,{entry:ms,method:ya,callbackUrl:SSe(),clientId:ns,onClientIdChange:fe,clientSecret:ct,onClientSecretChange:Ue,required:!1}):null,qa=on?.()??null,li=Ha?on?.(Ha,ht==="error"||ns.trim().length>0)??null:qa,Ba=!!(ms&&ge==="key"&&(Ae||ht!=="entry")),yl=!!(ge==="key"&&le&&Cr&&!Qr&&rr.data?.configured===!0),ba=!!(ge==="key"&&le&&Cr&&!Qr&&(rr.isLoading||rr.isError||rr.data?.configured!==!0));if(Ba&&ms)return(0,t.jsx)(Jq,{entry:ms,resuming:!!G,phase:ht,error:Rs,recoveryActions:ee==="github_installation_required"?{installationUrl:ne,managementUrl:he}:void 0,authorizationHost:jn,authorizationUrl:Tr,guidance:le?.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(yt=>(0,t.jsx)("li",{children:yt},yt))})]}):null,defaults:li,settingsValid:n&&Dr,onOpenAuthorization:kr,onRetry:r(async()=>{const yt=!an.current;an.current=!0,hs(null),kt("starting");const Ne=Gt?.connection??we;if(Ne&&Ha&&ns.trim()){Xs.current=Ne.id,Ei(ms);return}if(Ne){_n(Ne);return}if(yt&&!G&&!Yn.isError&&!wn.isError){Ei(ms);return}Jt.current=!0;try{const[at,It]=await Promise.all([Yn.refetch(),wn.refetch()]);if(at.isError||It.isError){kt("error"),hs("Paperclip couldn’t check for an existing connection. Try again.");return}const ps=(G?(It.data?.connections??[]).find(Bs=>Bs.id===G&&Bs.authKind==="oauth")??null:null)??Qte(Q,at.data?.applications??[],It.data?.connections??[],U?{applicationId:ie.applicationId,draftOnly:!0}:{});ps&&!G&&wt(ps.credentialPolicy==="per_user"?"user":ps.credentialPolicy==="per_agent"?"agent":"organization"),ps?_n(ps):ca.mutate(ms)}finally{Jt.current=!1}},"onRetry"),onBack:r(()=>{ut.current?.abort(),kt("entry"),hs(null),tt()},"onBack"),onCancel:r(()=>{ut.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});if(Ee&&!le&&Ie&&ge==="key")return(0,t.jsx)(Jq,{identity:{name:rt.trim()||S1(Ie)||"this server",unverifiedHost:S1(Ie)},steps:{labels:Kte,activeIndex:Wte.key},phase:ht,error:Rs,authorizationHost:jn,authorizationUrl:Tr,defaults:qa,onOpenAuthorization:kr,onRetry:r(()=>{hs(null);const yt=Gt?.connection;if(yt){kt("starting"),_n(yt);return}Je(!1),kt("entry")},"onRetry"),onBack:r(()=>{ut.current?.abort(),Je(!1),kt("entry"),hs(null)},"onBack"),onCancel:r(()=>{ut.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});const Hi=Gt?.application.name??le?.name??(rt.trim()||z$(Ie)||"this app"),Go=ce?xs.filter(yt=>kw(yt,i).length>0):xs,$o=te?Dt.data?.apps.find(yt=>yt.slug==="zapier")??null:null,rl=(as?.connectionPurpose==="ai"?gJ.safeParse(as.config?.ai).data:void 0)??le?.methods.find(yt=>yt.key===js)?.ai??(!js&&le?.methods.every(yt=>yt.ai)?le.methods[0]?.ai:void 0),Oo=le?w?.({app:le,name:Se||le.name,grantKind:dn,agentIds:[...vt],allAgents:Yt==="all",onBack:r(()=>tt(),"onBack")})??(rl&&R?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(w5,{companyId:R,provider:rl.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:as?.connectionPurpose==="ai"?(as.config?.ai).method:rl.method,connectionId:as?.connectionPurpose==="ai"?as.id:void 0,name:as?.connectionPurpose==="ai"?as.name:Se||`My ${le.name} ${rl.method==="subscription"?"subscription":"API"}`,ownership:(as?.connectionPurpose==="ai"?as.credentialPolicy==="shared":dn==="organization")?"shared":"personal",agentIds:[...vt],allAgents:Yt==="all",onCancel:r(()=>N?N():C("/apps"),"onCancel"),onComplete:r(yt=>{x?.({connectionId:yt.connectionId}),x||C(`/apps/${yt.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,Qo=as?.connectionPurpose==="ai"?["Reconnect account"]:Oo!==void 0?["Connect account"]:te?Kat:le&&Pi.length>1?["Choose connection"]:le&&Pi[0]?.auth==="oauth"?["Sign in"]:zC(le,js)?["Share sheet"]:le?["Add your key"]:Kte,Rc=as?.connectionPurpose==="ai"?0:(te||le)&&ge!=="gallery"&&ge!=="success"?Uat[ge]:ge==="success"?Qo.length:Wte[ge];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[ge!=="success"&&!(a&&ge==="gallery")&&(0,t.jsx)(LM,{subtitle:ge==="gallery"?ce?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":Qo.length<=1?void 0:`Step ${Rc+1} of ${Qo.length}`,step:ge,activeIndex:Rc,labels:Qo,appIdentity:te?{name:"Zapier",logoUrl:$o?.branding.logoUrl??null,darkLogoUrl:$o?.branding.darkLogoUrl??null}:le&&ge!=="gallery"?{name:le.name,logoUrl:le.branding.logoUrl,darkLogoUrl:le.branding.darkLogoUrl??null}:void 0,unverifiedHost:!le&&!te&&ge!=="gallery"?S1(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)(Jat,{loading:Dt.isLoading,initialLink:Ie,apps:Go,vercelConnect:ce,vercelConnectAvailability:Dt.data?.credentialSources?.vercelConnect??null,byo:me,byoOnly:a,source:E.get("source"),onPick:hn,onUseLink:r(yt=>{const Ne=d3(yt,xs);ue(null),ye(""),Ke(yt),dt(Ne?.name??z$(yt)??""),ze(!1),bt(""),He({}),ds(""),xe(null),$e(new Set(c?[c]:[])),Zt(c?"specific":"all"),wt(Br??(c?"user":"organization")),be("key")},"onUseLink")}),yl&&le?(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("h2",{className:"text-lg font-semibold text-foreground",children:[le.name," sign-in is unavailable"]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This instance is connected to Paperclip, but ",le.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),Bn?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Fe(Bn.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:tt,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:Dt.isFetching,onClick:r(()=>{Dt.refetch()},"onClick"),children:[Dt.isFetching?(0,t.jsx)(nt,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):ge==="key"&&le&&ba?(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)(Q0,{className:"h-5 w-5"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Connect with Paperclip"}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["You must connect this instance to Paperclip to connect to ",le.name," (you only need to do this once)."]})]})]}),Bn?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Fe(Bn.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,rr.isError||sr?(0,t.jsx)(da,{tone:"danger",className:"mt-4",children:sr??"Paperclip couldn’t check Cloud registration. Try again."}):null,Rr?(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:Rr,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,qa,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:tt,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:rr.isLoading||dr.isPending,onClick:r(()=>{Va(null),nr(),$s(),dr.mutate()},"onClick"),children:[dr.isPending?(0,t.jsx)(nt,{className:"h-4 w-4 animate-spin"}):null,rr.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):ge==="key"&&le&&Oo!==void 0?Oo:ge==="key"&&le?(0,t.jsx)(eit,{settingsValid:n&&Dr,entry:le,error:ca.isError?ca.error instanceof Error?ca.error.message:"Please check your key and try again.":null,values:_e,onChange:He,oauthClientId:ns,onOAuthClientIdChange:fe,oauthClientSecret:ct,canReuseOAuthClientSecret:!!(Er?.config?.oauth&&Er.config.oauth.clientId===ns.trim()&&Er.hasSavedOAuthClientSecret),onOAuthClientSecretChange:Ue,credentialSource:i,vercelConnector:Et,onVercelConnectorChange:$t,vercelConnectAvailability:Dt.data?.credentialSources?.vercelConnect??null,methodKey:js,onMethodChange:r(yt=>{Fe(yt?.key??""),!Br&&yt?.grantKinds&&!yt.grantKinds.includes(Ft)&&wt(q$(yt,!!c)),He({}),fe(""),Ue(""),$t(""),Ts(ZS(yt))},"onMethodChange"),configValues:Cs,onConfigChange:Ts,googleSheetsLinks:Ct,googleSheetsError:Oe,onGoogleSheetsLinksChange:r(yt=>{ds(yt),xe(null)},"onGoogleSheetsLinksChange"),submitting:ca.isPending,renderDefaults:on??void 0,onBack:tt,onConnect:r(()=>{if(zC(le,js)){const at=eq(Ct);if(at.invalidCount>0){xe("That doesn't look like a Google Sheets link.");return}if(at.ids.length===0){xe("Paste at least one Google Sheets link.");return}}const yt=O2(le,js||null),Ne=!!(yt?.credentialFields?.length||yt?.tenantFields?.some(at=>!at.hidden)||yt?.extensionFields?.some(at=>!at.hidden));if(yt&&tp(yt)&&we&&!Ne&&!ns.trim()){an.current=!0,hs(null),kt("starting"),_n(we);return}yt&&tp(yt)&&(an.current=!0,hs(null),kt("starting")),Ei()},"onConnect")}):null,ge==="key"&&!le&&!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)(gn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(gn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(gn,{className:"mt-8 h-11 w-40 rounded-md"})]}),ge==="key"&&!le&&Ie&&!te&&(0,t.jsx)(Xat,{link:Ie,name:rt,needsKey:de,keyValue:gt,onKeyChange:bt,authMode:De,onAuthModeChange:r(yt=>{Qe(yt),ot(null),yt!=="auto"&&ze(!1),yt!=="bearer"&&yt!=="auto"&&bt("")},"onAuthModeChange"),headers:mt,onHeadersChange:r(yt=>{Ye(yt),ot(null)},"onHeadersChange"),oauthClientId:it,onOAuthClientIdChange:Nt,oauthClientSecret:Ze,onOAuthClientSecretChange:Pe,advancedOpen:Ce,onAdvancedOpenChange:Ve,guidance:Ge,matchedEntry:br,onUseMatchedEntry:br?()=>hn(br):void 0,submitting:ca.isPending||Ee,defaults:qa,onBack:tt,onConnect:r(()=>{ot(null),ca.mutate(void 0)},"onConnect")}),ge==="key"&&!le&&te&&(0,t.jsx)(Yat,{link:Ie,onLinkChange:Ke,submitting:ca.isPending,defaults:qa,onBack:tt,onConnect:r(()=>ca.mutate(void 0),"onConnect")}),ge==="success"&&(0,t.jsx)(rit,{appName:Hi,logoUrl:le?.branding.logoUrl,darkLogoUrl:le?.branding.darkLogoUrl,summary:nit({grantKind:dn,authKind:Ns,installChoice:Yt,installCount:vt.size,enabledCount:Object.values(os).filter(Boolean).length}),statedDefault:e6({grantKind:dn,authKind:Ns,installChoice:Yt,installCount:vt.size,lockedAgentId:c??null}),onDone:N??(()=>C("/apps"))})]})}r(Qat,"StandardConnectionSetupFlow");function Jq({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:Wat,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)(LM,{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)(pc,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(dd,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(nt,{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)(DM,{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(Jq,"OAuthConnectStateScreen");function Yat({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=Xq(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)(pt,{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)(nt,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(Yat,"ZapierConnectStep");function Jat({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=Xq(f),I=C?d3(C,n):null,T=c==="zapier",R=r(()=>{const A=Xq(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)(gn,{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)(da,{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)(Gr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(pt,{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=NSe(A.slug,A.description),M=nA(A),$=M.length===0||M.every(B=>B.auth==="oauth"&&!tp(B)&&!Jw(B)),E=A.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:$||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",$||E?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(Vo,{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."}):$?(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)(pc,{className:"h-4 w-4 text-muted-foreground"}),T?"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:T?"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."}),!T&&(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)(Vo,{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"){R();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)(pt,{ref:w,type:T||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"&&R()},"onKeyDown"),placeholder:T?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:R,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(Jat,"GalleryStep");function Xq(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(Xq,"normalizeAppLink");function Xat({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=S1(e),T=o==="custom_headers"?CSe(c):null,R=Eat({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"?xpe(e):e,M=r(($,E)=>{d(c.map(B=>B.id===$?{...B,...E}:B))},"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)(DM,{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)(Vo,{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)(da,{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)(pt,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r($=>i($.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)(sl,{open:x,onOpenChange:b,children:[(0,t.jsxs)(Hl,{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)(nl,{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:Yte.map($=>(0,t.jsx)(Zat,{label:$.label,selected:o===$.mode,onClick:r(()=>l($.mode),"onClick")},$.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:Yte.find($=>$.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map($=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(pt,{value:$.name,onChange:r(E=>M($.id,{name:E.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(pt,{type:"password",autoComplete:"off",value:$.value,onChange:r(E=>M($.id,{value:E.target.value}),"onChange"),placeholder:"Value","aria-label":$.name.trim()?`Value for ${$.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!==$.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},$.id)),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,Yq()]),"onClick"),children:"Add another header"}),T?(0,t.jsx)("p",{className:"text-xs text-destructive",children:T}):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)(pt,{id:"generic-mcp-client-id",value:u,onChange:r($=>h($.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)(pt,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r($=>f($.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||!R||!!T,children:[w&&(0,t.jsx)(nt,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(Xat,"LinkConnectStep");var Yte=[{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 Zat({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(Zat,"SegmentedOption");function eit({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:T,onConnect:R}){const A=(0,m.useMemo)(()=>kw(s,h),[h,s]),D=b?A.find(De=>De.key===b)??null:mk(A),M=(0,m.useMemo)(()=>A.some(De=>De.capabilityProfile)?Array.from(A.reduce((De,Qe)=>{const mt=Qe.capabilityProfile.key,Ye=De.get(mt);return Ye?Ye.methods.push(Qe):De.set(mt,{key:mt,label:Qe.capabilityProfile?.label??Qe.label??Qe.key,description:Qe.capabilityProfile?.description??Qe.whenToUse,methods:[Qe]}),De},new Map)).map(([,De])=>De):[],[A]),$=D?.capabilityProfile?.key??D?.key??"",E=M.map(De=>De.key).join("|"),[B,z]=(0,m.useState)($||mk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""));(0,m.useEffect)(()=>{if($){z($);return}z(De=>M.some(Qe=>Qe.key===De)?De:mk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""))},[E,M,A,$]);const q=M.length>1?M.find(De=>De.key===B)?.methods??[]:A,U=(D?.credentialFields??[]).map(De=>({...De,configPath:ppe(De,D),helpUrl:D?.consoleLinks?.keys??D?.consoleLinks?.docs??""})),F=D?.credentialSources?.vercelConnect??null,K=h==="vercel_connect",G=K||U.every(De=>De.required===!1||(a[De.configPath]?.trim().length??0)>0),se=Jw(D),ee=se&&!tp(D),ne=K||!ee||o.trim().length>0&&(!D?.oauthClientSecretRequired||d||c.trim().length>0),he=!K||p.trim().length>0,Z=D?.auth==="oauth"&&se?SSe():null,re=[...D?.tenantFields??[],...D?.extensionFields??[]],ce=re.filter(De=>!De.hidden),H=ce.filter(De=>De.advanced!==!0),Q=ce.filter(De=>De.advanced===!0),Y=re.every(De=>{if(!De.required)return!0;const Qe=j[De.key];return typeof Qe=="boolean"||typeof Qe=="string"&&Qe.trim().length>0}),te=D?.configRequirements?.atLeastOneOf??[],ae=te.length===0||te.some(De=>{const Qe=j[De];return typeof Qe=="string"&&Qe.trim().length>0}),me=(M.length<=1||!!B)&&(q.length<=1?!!D:!!b),oe=s.availability?.robotEmail??null,ie=s.availability?.available===!1,ge=!K&&se&&!ee,be=M.length>1||q.length>1,le=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)(mm,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:B,onValueChange:r(De=>{const Qe=M.find(mt=>mt.key===De);Qe&&(z(De),v(q8(Qe.methods)))},"onValueChange"),options:M.map(De=>({value:De.key,title:De.label,description:De.description}))}),!B&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,ue=q.find(De=>De.oauthStrategy==="paperclip_cloud_connector"),Se=ue&&q.find(De=>Jw(De)&&!tp(De)),ye=D?.key===Se?.key,Ie=(0,m.useId)(),Ke=ue&&Se&&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":ye,"aria-controls":Ie,disabled:C,onClick:r(()=>v(ye?ue:Se),"onClick"),children:ye?"Use Paperclip instead":`Use your own ${QDe(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)(mm,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:b,onValueChange:r(De=>{const Qe=q.find(mt=>mt.key===De);Qe&&v(Qe)},"onValueChange"),options:q.map(De=>({value:De.key,title:De.label??(De.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,rt=Q.length>0||ge||be,dt=ye||!me,de=rt?(0,t.jsxs)("div",{className:"space-y-6",children:[le,Ke,Q.map(De=>(0,t.jsx)(Jte,{field:De,value:j[De.key],onChange:r(Qe=>N({...j,[De.key]:Qe}),"onChange")},De.key)),ge?(0,t.jsx)(Zq,{entry:s,method:D,callbackUrl:Z,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!1}):null]}):null,ze=I?.(de,dt)??null;if(zC(s,D)){const De=eq(w),Qe=e&&!ie&&!!oe&&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:[le,oe?(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:oe,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:oe}),(0,t.jsx)(RSe,{value:oe,ariaLabel:"Copy sharing email"})]}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below."})]}):(0,t.jsx)("div",{className:"rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground",children:"Google Sheets is not available on this instance yet."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paste links to the sheets you shared"}),(0,t.jsx)(Tn,{value:w,onChange:r(mt=>S(mt.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:De.ids.length>0?`${De.ids.length} ${De.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})]})]}),ze,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:T,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:R,disabled:C||!Qe,children:[C&&(0,t.jsx)(nt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":"Connect"]})]})]})}const gt=D?.connectorProfile==="asana.mcp",bt=gt?null:D?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[bt?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:bt,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:[gt?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Sign in with Asana to choose your workspace and connect it to Paperclip."}):null,D?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[D.capabilityProfile.label,": ",D.capabilityProfile.description]}),K&&F&&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)(pt,{id:"vercel-connect-connector",value:p,onChange:r(De=>f(De.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)(da,{tone:"danger",children:n})}):null,H.map(De=>(0,t.jsx)(Jte,{field:De,value:j[De.key],onChange:r(Qe=>N({...j,[De.key]:Qe}),"onChange")},De.key)),!K&&D?.auth==="oauth"&&ee?(0,t.jsx)("div",{id:Ie,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(Zq,{entry:s,method:D,callbackUrl:Z,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!0})}):null,K||!D||U.length===0?null:U.map(De=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:Dte(s.name,De.label,U.length)}),(0,t.jsx)(pt,{type:De.type==="text"&&De.secret===!1?"text":"password","aria-label":Dte(s.name,De.label,U.length),autoComplete:"off",value:a[De.configPath]??"",onChange:r(Qe=>i({...a,[De.configPath]:Qe.target.value}),"onChange"),placeholder:De.type==="text"&&De.secret===!1?De.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),De.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:De.helperMd}),De.helpUrl&&(0,t.jsxs)("a",{href:De.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"})]})]},De.configPath))]}),ze,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:T,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:R,disabled:C||!e||!me||!G||!ne||!he||!Y||!ae,children:[C&&(0,t.jsx)(nt,{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(eit,"KeyStep");function RSe({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)(vs,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(Ar,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(RSe,"CopyValueButton");function Zq({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)(RSe,{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)(pt,{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)(pt,{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(Zq,"OAuthClientFields");function Jte({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)(ui,{checked:s===!0,onCheckedChange:n})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:e.label}),e.type==="textarea"?(0,t.jsx)(Tn,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,className:"mt-2 min-h-24"}):e.type==="select"?(0,t.jsxs)("select",{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),className:"mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",children:[(0,t.jsx)("option",{value:"",disabled:!0,children:"Select an option"}),(e.options??[]).map(a=>(0,t.jsx)("option",{value:a.value,children:a.label},a.value))]}):(0,t.jsx)(pt,{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(Jte,"MethodConfigField");function tit({companyId:e,...s}){const n=X({queryKey:P.agents.list(e),queryFn:r(()=>Lt.list(e),"queryFn")});return(0,t.jsx)(CW,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(tit,"AccessStep");function CW({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,T=I?e.filter(U=>I.includes(U.id)):e,R=p?.canSetCompanyInstall??!0,A=p?.canCreateOrganizationGrant??!0,D=n!=="none",M=a??["user","organization"],$=(!D||i==="user"||i==="agent"||A)&&(j?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?R:d.size>0),E=h?e.find(U=>U.id===h)?.name??"the requesting agent":null,B=f?"Connect GitHub as":"Which humans can use this credential?",z=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?z:"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:B}),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)(gn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(gn,{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)(Th,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):M[0]==="agent"?(0,t.jsx)(Ji,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(sk,{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)(mm,{ariaLabel:f?B:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(U=>{const F=U;o(F),F==="agent"&&(c("specific"),d.size>1&&u(new Set([[...d][0]])))},"onValueChange"),options:[{value:"user",title:f?"My GitHub account":"Just me",description:f?"Agents use it only for runs where you are the responsible person.":void 0,icon:(0,t.jsx)(Th,{className:"h-4 w-4","aria-hidden":"true"})},{value:"agent",title:"A dedicated account for an agent",description:f?"That agent always uses this account, regardless of who starts the run.":void 0,icon:(0,t.jsx)(Ji,{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)(sk,{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:z}),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)(sk,{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)(mm,{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)(Ji,{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)(sit,{}),accessibleLabel:R?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:R?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!R}]}),!j&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Yy,{agents:T,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:!$||v||N,children:[N?(0,t.jsx)(nt,{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(CW,"AccessStepContent");function e6(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(e6,"connectionDefaultSummarySentence");function ESe({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)(sl,{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)(Hl,{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)(nl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(CW,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(tit,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(ESe,"ConnectionAccessDefaults");function sit(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(Ji,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(Ji,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(sit,"BotGroupIcon");function nit(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(nit,"accessSummaryLines");function rit({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)(vs,{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)(Vo,{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(rit,"ConnectionSetupCompletionScreen");function PSe(){const{newProjectOpen:e,closeNewProject:s}=AI(),{selectedCompanyId:n}=gs();return n&&e?(0,t.jsx)(ait,{companyId:n,onClose:s},n):null}r(PSe,"NewProjectDialog");function ait({companyId:e,onClose:s}){const n=Mt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>u3[Math.floor(Math.random()*u3.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=je({mutationFn:r(()=>ma.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{H0(f.id,e),n.invalidateQueries({queryKey:P.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(Vs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Qs,{showCloseButton:!1,"aria-describedby":void 0,className:"flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 shadow-sm sm:max-w-lg",onOpenAutoFocus:r(f=>{f.preventDefault(),h.current?.focus()},"onOpenAutoFocus"),children:d?(0,t.jsxs)("div",{className:"min-h-0 overflow-y-auto p-5",children:[(0,t.jsx)(Js,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(e4,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:w9(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)(Js,{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)(Vn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-input px-3 focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",children:[(0,t.jsx)(wm,{color:o,size:"sm"}),(0,t.jsx)("input",{ref:h,"aria-label":"Project name",value:a,disabled:p.isPending,onChange:r(f=>i(f.target.value),"onChange"),placeholder:"Project name",required:!0,className:"h-10 w-full min-w-0 border-0 bg-transparent text-base outline-none placeholder:text-muted-foreground md:text-sm"})]})]}),(0,t.jsx)("div",{role:"region","aria-label":"Source repositories",tabIndex:0,className:"min-h-0 overflow-y-auto overscroll-contain px-5 pb-1 outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",children:(0,t.jsx)(Kje,{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(ait,"NewProjectForm");var sg={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 MSe(e){return{"--sc":`var(${e})`}}r(MSe,"scStyle");function iit(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(iit,"sentenceCaseStatus");function Za({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",xz[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(Za,"StatusBadge$5");function DSe({status:e}){const s=mFe[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:MSe(s),children:n.replace(/_/g," ")})}r(DSe,"AgentStatusBadge");function Zh({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=oFe[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:MSe(a),children:[(0,t.jsx)(II,{status:n,size:"sm"}),iit(n)]})}r(Zh,"IssueStatusBadge");var Xte={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function LSe(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=AI(),{selectedCompanyId:a,selectedCompany:i}=gs(),o=Mt(),[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,T]=(0,m.useState)(!1),R=(0,m.useRef)(null),A=b||s.parentId||"",{data:D}=X({queryKey:P.goals.list(a),queryFn:r(()=>sg.list(a),"queryFn"),enabled:!!a&&e}),M=je({mutationFn:r(U=>sg.create(a,U),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:P.goals.list(a)}),E(),n()},"onSuccess")}),$=je({mutationFn:r(async U=>{if(!a)throw new Error("No organization selected");return fb.uploadImage(a,U,"goals/drafts")},"mutationFn")});function E(){c(""),u(""),p("planned"),x("task"),v(""),N(!1)}r(E,"reset");function B(){!a||!l.trim()||M.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...A?{parentId:A}:{}})}r(B,"handleSubmit");function z(U){U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&(U.preventDefault(),B())}r(z,"handleKeyDown");const q=(D??[]).find(U=>U.id===A);return(0,t.jsx)(Vs,{open:e,onOpenChange:r(U=>{U||(E(),n())},"onOpenChange"),children:(0,t.jsxs)(Qs,{showCloseButton:!1,className:W("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:z,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)(O0e,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Hy,{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(),R.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)(ud,{ref:R,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 $.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)(yr,{open:w,onOpenChange:k,children:[(0,t.jsx)(Ir,{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)(Za,{status:h})})}),(0,t.jsx)(lr,{className:"w-40 p-1",align:"start",children:Spe.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)(yr,{open:S,onOpenChange:C,children:[(0,t.jsx)(Ir,{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)(Tl,{className:"h-3 w-3 text-muted-foreground"}),Xte[f]??f]})}),(0,t.jsx)(lr,{className:"w-40 p-1",align:"start",children:_pe.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:Xte[U]??U},U))})]}),(0,t.jsxs)(yr,{open:I,onOpenChange:T,children:[(0,t.jsx)(Ir,{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)(bp,{className:"h-3 w-3 text-muted-foreground"}),q?q.title:"Parent goal"]})}),(0,t.jsxs)(lr,{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(""),T(!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),T(!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:B,children:M.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(LSe,"NewGoalDialog");function oit(e){const s=lit(e),n=cit(e);return`You're invited to join a Paperclip company as an agent.
|
|
306
|
+
`;function bnt(){const e=new Blob([gnt],{type:"application/javascript"}),s=URL.createObjectURL(e);try{return new Worker(s)}finally{URL.revokeObjectURL(s)}}r(bnt,"createSandboxedWorker");var Oq=new Map,v5=new Map,rE=new Set,aE=new Map,BNe=null;function vnt(e){BNe=e}r(vnt,"setDynamicParserResultNotifier");function zNe(e,s){e.worker.postMessage(s)}r(zNe,"sendToWorker");function ynt(e){return e.nextId++}r(ynt,"nextRequestId");function jnt(e,s){return`${s}\0${e}`}r(jnt,"lineCacheKey");function wnt(){BNe?.()}r(wnt,"notifyResultReady");function knt(e,s,n){return new Promise(a=>{const i=ynt(e);e.pendingResolves.set(i,a),zNe(e,{type:"parse",id:i,line:s,ts:n})})}r(knt,"parseLineAsync");function FC(e){for(const s of e.pendingResolves.values())s([]);e.pendingResolves.clear()}r(FC,"drainPendingRequests");function Nnt(e){return new Promise((s,n)=>{const a=bnt(),i={worker:a,ready:!1,nextId:1,pendingResolves:new Map},o=setTimeout(()=>{FC(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"&&FC(i)},s(i);return}if(c.type==="error"){clearTimeout(o),FC(i),a.terminate(),n(new Error(c.message));return}},a.onerror=l=>{clearTimeout(o),FC(i),a.terminate(),n(new Error(`Worker error: ${l.message}`))},zNe(i,{type:"init",source:e})})}r(Nnt,"initSandboxedWorker");function Snt(e){const s=new Map,n=new Set;return{parseStdoutLine:r((i,o)=>{const l=jnt(i,o),c=s.get(l);return c?c.slice():(n.has(l)||(n.add(l),knt(e,i,o).then(d=>{n.delete(l),s.set(l,d),wnt()})),[])},"parseStdoutLine")}}r(Snt,"buildParserModule");async function Fq(e){const s=v5.get(e);if(s)return s;if(rE.has(e))return null;const n=aE.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 rE.add(e),null;const o=await Nnt(await i.text());Oq.set(e,o);const l=Snt(o);return v5.set(e,l),l}catch{return rE.add(e),null}finally{aE.delete(e)}})();return aE.set(e,a),a}r(Fq,"loadDynamicParser");function Bq(e){const s=v5.has(e);v5.delete(e),rE.delete(e),aE.delete(e);const n=Oq.get(e);return n&&(FC(n),n.worker.terminate(),Oq.delete(e)),s}r(Bq,"invalidateDynamicParser");var iE=[],JM=new Map,zq=new Set,qNe=new Map,T$=new Set,M2=new Map,qq=new Set;function UNe(e){return qq.add(e),()=>qq.delete(e)}r(UNe,"onAdapterChange");function KNe(){for(const e of qq)e()}r(KNe,"notifyAdapterChange");vnt(KNe);function Cnt(){for(const e of[det,ket,Uet,Qet,btt,Rtt,Utt,Xtt,cst,vst,Ust,Lst,ltt,ant,b5,xnt])zq.add(e.type),qNe.set(e.type,e),vv(e)}r(Cnt,"registerBuiltInUIAdapters");function vv(e){const s=iE.findIndex(n=>n.type===e.type);s>=0?iE.splice(s,1,e):iE.push(e),JM.set(e.type,e),KNe()}r(vv,"registerUIAdapter");function WNe(e){return JM.get(e)??null}r(WNe,"findUIAdapter");Cnt();function tS(e){const s=JM.get(e);if(!s){let n=!1;return{type:e,label:e,parseStdoutLine:r((a,i)=>(n||(n=!0,Fq(e).then(o=>{o&&vv({type:e,label:e,parseStdoutLine:o.parseStdoutLine,createStdoutParser:o.createStdoutParser,ConfigFields:vy,buildAdapterConfig:Xk})})),b5.parseStdoutLine(a,i)),"parseStdoutLine"),ConfigFields:vy,buildAdapterConfig:Xk}}return s}r(tS,"getUIAdapter");function _nt(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=qNe.get(a);if(!i)continue;const o=n.has(a),l=s.has(a),c=T$.has(a);if(o&&l&&!c){T$.add(a);const d=(M2.get(a)??0)+1;M2.set(a,d);let u=!1;const h=i.parseStdoutLine,p=e.find(f=>f.type===a)?.label??a;vv({type:a,label:p,parseStdoutLine:r((f,x)=>(u||(u=!0,Fq(a).then(b=>{b&&M2.get(a)===d&&vv({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&&(T$.delete(a),M2.delete(a),Bq(a),vv(i))}for(const{type:a,label:i}of e){if(zq.has(a))continue;const o=JM.get(a);if(o&&o!==b5)continue;let l=!1;const c=o?.parseStdoutLine??b5.parseStdoutLine;vv({type:a,label:i,parseStdoutLine:r((d,u)=>(l||(l=!0,Fq(a).then(h=>{h&&vv({type:a,label:i,parseStdoutLine:h.parseStdoutLine,createStdoutParser:h.createStdoutParser,ConfigFields:o?.ConfigFields??vy,buildAdapterConfig:o?.buildAdapterConfig??Xk})})),c(d,u)),"parseStdoutLine"),ConfigFields:o?.ConfigFields??vy,buildAdapterConfig:o?.buildAdapterConfig??Xk})}}r(_nt,"syncExternalAdapters");function hW(){return[...iE]}r(hW,"listUIAdapters");function Uq(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(Uq,"resolveStdoutParser");function VNe(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(VNe,"appendTranscriptEntry");function Int(e,s){for(const n of s)VNe(e,n)}r(Int,"appendTranscriptEntries");function Ant(e,s=160){return e.length<=s?e:`${e.slice(0,s-3)}...`}r(Ant,"truncateTranscriptLine");function Tnt(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(Tnt,"formatTranscriptParserError");function Rnt(e,s,n,a){const i=Tnt(n)||"unknown parser error",o=Ant(e);return{kind:"result",ts:s,text:lm(`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(Rnt,"createTranscriptParseErrorEntry");function pW(e){const{entries:s,line:n,ts:a,parseLine:i,reset:o,redactionOptions:l}=e;try{Int(s,i(n,a).map(c=>TXe(c,l)))}catch(c){o?.(),VNe(s,Rnt(n,a,c,l))}}r(pW,"appendParsedTranscriptLine");function HNe(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:lm(u.chunk,l)});continue}if(u.stream==="system"){s.push({kind:"system",ts:u.ts,text:lm(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&&pW({entries:s,line:f,ts:u.ts,parseLine:i,reset:o,redactionOptions:l})}}return c}r(HNe,"foldTranscriptChunks");function GNe(e,s,n){const a=[],i={enabled:n?.censorUsernameInLogs??!1},{parseLine:o,reset:l}=Uq(s),c=HNe({entries:a,chunks:e,from:0,stdoutBuffer:"",parseLine:o,reset:l,redactionOptions:i}).trim();return c&&pW({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(GNe,"buildTranscript");var xte=[];function Ent(e,s){const n={enabled:s?.censorUsernameInLogs??!1},a=typeof e!="function"&&typeof e.createStdoutParser=="function";let i=Uq(e),o=[],l="",c=xte,d=[];const u=r(()=>{i=Uq(e),o=[],l="",c=xte},"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 GNe(f,e,s);const b=o.slice(),v=b.length-1;return v>=0&&(b[v]={...b[v]}),x&&pW({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=HNe({entries:o,chunks:f,from:c.length,stdoutBuffer:l,parseLine:i.parseLine,reset:i.reset,redactionOptions:n}),c=f,d=p(f)),d}}}r(Ent,"createIncrementalTranscript");function Pnt({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)(yr,{open:c,onOpenChange:d,children:[(0,t.jsx)(Ir,{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)(Uc,{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)(_r,{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)(Uc,{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)(lr,{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)(_r,{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)(_r,{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:lW[b.role]??b.role})]},b.id))]})]})}r(Pnt,"ReportsToPicker");var Mnt="__secret_folder__:";function Dnt(e){return!e||e==="active"?null:(0,t.jsx)(lt,{variant:"outline",className:"ml-auto text-(length:--text-nano) font-normal text-muted-foreground",children:e})}r(Dnt,"statusBadge");function QNe(e){return e.split("/").filter(s=>s.length>0)}r(QNe,"splitSecretPath$1");function oE(e){return e.join("/")}r(oE,"pathKey$1");function GS(e){return e.length>0?`/${e.join("/")}`:"/"}r(GS,"pathLabel");function Lnt(e,s){return e.length<s.length?!1:s.every((n,a)=>e[a]===n)}r(Lnt,"pathStartsWith");function gte(e){return`${Mnt}${oE(e)}`}r(gte,"folderValue");function $nt(e,s,n){const a=s.length,i=new Map,o=[];for(const c of e){const d=QNe(c.name);if(Lnt(d,s)){if(d.length>a+1){const u=d.slice(0,a+1),h=oE(u);if(!i.has(h)){const p=u[u.length-1]??"/",f=GS(u);i.set(h,{key:`folder-${h||"root"}`,value:gte(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-${oE(s)}`,value:gte(c),label:"Up one folder",title:GS(c),searchText:GS(c),kind:"back",folderPath:oE(c),pathHint:GS(c)})}return l.push(...i.values(),...o),{id:"browse-secrets",label:s.length>0?GS(s):"Browse secrets",options:l}}r($nt,"buildFolderGroup");function fW({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=>QNe(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||XOe(j))return N;const w=$nt(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)(Uy,{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)(ki,{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)(ki,{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"?dze:Kl;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)(ki,{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]}),Dnt(j.status)]})},"renderOption"),createItem:o?{render:r(j=>(0,t.jsxs)("span",{className:"flex items-center gap-1.5 text-sm",children:[(0,t.jsx)(bn,{className:"size-3.5 shrink-0"}),j.trim()?(0,t.jsxs)("span",{children:["Create secret ",(0,t.jsxs)("span",{className:"font-mono",children:["“",j.trim(),"”"]}),"…"]}):(0,t.jsx)("span",{children:"Create new secret…"})]}),"render"),onSelect:r(j=>o(j),"onSelect")}:void 0})}r(fW,"SecretPicker");var Ont=/^[a-z][a-z0-9_]*$/,bte="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 YNe({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?Ont.test(w)?a?.some(R=>R.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(R){v(R instanceof Error?R.message:"Failed to create secret"),x(!1)}}}r(I,"handleSubmit");const T=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)(eFe,{className:"text-sm font-medium",children:e==="create"?"Create secret":"Store value as secret"}),e==="store"?(0,t.jsxs)(tFe,{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(bte,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(R=>c(R.target.value),"onChange"),onBlur:r(()=>N(!0),"onBlur"),onKeyDown:r(R=>{R.key==="Enter"&&(R.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(bte,"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"?R=>u(R.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(R=>!R),"onClick"),children:h?(0,t.jsx)(Em,{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)(nt,{className:"h-3.5 w-3.5 animate-spin"}):null,T]})]})]})}r(YNe,"SecretPopoverForm");function JNe(e){return(0,t.jsx)(YNe,{mode:"create",...e})}r(JNe,"CreateSecretPopover");function Fnt(e){return(0,t.jsx)(YNe,{mode:"store",...e})}r(Fnt,"ConvertToSecretPopover");var Bnt=/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i,znt=[/^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 qnt(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(qnt,"looksHighEntropy");function Unt(e,s){return s?Bnt.test(e)||znt.some(n=>n.test(s))?!0:qnt(s):!1}r(Unt,"isSensitiveEnv");var vte=0;function Knt(){return vte+=1,`env-row-${vte}`}r(Knt,"nextRowId");function Ox(e="text"){return{id:Knt(),name:"",source:e,textValue:"",secretId:"",userSecretKey:"",required:!0,version:"latest"}}r(Ox,"emptyRow");function Wnt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="secret_ref"}r(Wnt,"isSecretRef");function Vnt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="plain"}r(Vnt,"isPlainObj");function Hnt(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="user_secret_ref"}r(Hnt,"isUserSecretRef");function R$(e){return!e||typeof e!="object"?[]:Object.entries(e).map(([s,n])=>{if(typeof n=="string")return{...Ox(),name:s,textValue:n};if(Wnt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Ox(),name:s,source:"secret",secretId:typeof n.secretId=="string"?n.secretId:"",version:a}}if(Hnt(n)){const a=typeof n.version=="number"?n.version:"latest";return{...Ox(),name:s,source:"user_secret",userSecretKey:typeof n.key=="string"?n.key:"",required:n.required!==!1,version:a}}return Vnt(n)?{...Ox(),name:s,source:"text",textValue:typeof n.value=="string"?n.value:""}:{...Ox(),name:s}})}r(R$,"rowsFromValue");function lE(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(lE,"valueFromRows");var yte="CLAUDE_CODE_OAUTH_TOKEN";function Bw(){return lE([{...Ox("user_secret"),name:"CLAUDE_CODE_OAUTH_TOKEN",userSecretKey:"CLAUDE_CODE_OAUTH_TOKEN",required:!0,version:"latest"}])??{}}r(Bw,"buildFixedClaudeOAuthBinding");var Gnt=/^[A-Za-z_][A-Za-z0-9_]*$/;function Qnt(e,s,n){const a=e.trim();if(!a)return null;if(!Gnt.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(Qnt,"validateName");function Ynt(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(Ynt,"computeDuplicateNames");function Jnt(e,s){return s===e.source?{kind:"noop"}:s==="secret"?e.textValue.trim()?{kind:"open-store",name:y5(e.name)||"secret",value:e.textValue}:{kind:"to-secret"}:{kind:"to-text",undoFrom:e.secretId?{...e}:null}}r(Jnt,"planSourceSwitch");function XNe(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(XNe,"computeRowHealth");function ZNe(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(ZNe,"computeUserSecretRowHealth");function y5(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(y5,"secretNameFromKey");function N1(e){return e.trim().toUpperCase().replace(/[^A-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)}r(N1,"envKeyFromSecretName");var Xnt="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",jte="min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40";function Znt({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),[T,R]=(0,m.useState)(!1),[A,D]=(0,m.useState)(null),M=XNe(e,n)??ZNe(e,a),$=e.source==="secret"?n.find(Z=>Z.id===e.secretId)??null:null,E=(a?.length??0)>0,B=e.source==="text"&&!e.sensitiveDismissed&&Unt(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 Z=window.setTimeout(()=>D(null),5e3);return()=>window.clearTimeout(Z)},[A]);function z(Z){if(Z==="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=Jnt(e,Z);switch(re.kind){case"noop":return;case"open-store":{const{name:ce,value:H}=re;window.setTimeout(()=>I({mode:"store",name:ce,value:H}),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(z,"switchSource");async function q(Z,re){const ce=await b(Z,re);u({source:"secret",secretId:ce.id,userSecretKey:"",required:!0,version:"latest",textValue:""}),v(`Secret ${ce.name} created`),I(null)}r(q,"submitSecretPopover");function U(){const Z=y5(e.name)||"secret",{textValue:re}=e;window.setTimeout(()=>I({mode:"store",name:Z,value:re}),0)}r(U,"openStoreAsSecret");const F=e.source==="text"?"Text value":e.source==="secret"?"Organization secret reference":"User secret reference",K=`${e.id}-name-error`,G=`${e.id}-health`,se=d.name||d.value,ee=$?Math.max(0,$.latestVersion):0,ne=e.version==="latest"?"latest":`v${e.version}`,he=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",se&&"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(Xnt,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(Z=>u({name:Z.target.value}),"onChange"),onBlur:p,onPaste:r(Z=>{e.name||f(Z.clipboardData.getData("text"))&&Z.preventDefault()},"onPaste"),onKeyDown:r(Z=>{Z.key==="Enter"&&(Z.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)(yr,{open:C!==null,onOpenChange:r(Z=>{Z||I(null)},"onOpenChange"),children:[(0,t.jsx)(fz,{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)(ta,{children:[(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)(ea,{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)(Wze,{className:"size-3.5"}):e.source==="secret"?(0,t.jsx)(ki,{className:"size-3.5"}):(0,t.jsx)(Th,{className:"size-3.5"}),(0,t.jsx)(nn,{className:"size-3 opacity-60"})]})})}),(0,t.jsx)(Wn,{side:"top",children:F})]}),(0,t.jsxs)(sa,{align:"start",className:"w-56",children:[(0,t.jsxs)(cs,{className:"flex-col items-start gap-0.5",onSelect:r(()=>z("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)(cs,{className:"flex-col items-start gap-0.5",onSelect:r(()=>z("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)(cs,{className:"flex-col items-start gap-0.5",onSelect:r(()=>z("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:jte,placeholder:"value",value:e.textValue,type:B?"password":"text",spellCheck:!1,disabled:o,"aria-label":"Variable value",onChange:r(Z=>u({textValue:Z.target.value}),"onChange"),onKeyDown:r(Z=>{Z.key==="Enter"&&s&&(Z.preventDefault(),x())},"onKeyDown")}),B?(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)(hc,{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)(Vn,{className:"size-3"})})]}):null]}):e.source==="secret"?(0,t.jsxs)("div",{className:"relative min-w-0 flex-1",children:[(0,t.jsx)(fW,{secretId:e.secretId,secrets:n,recentlyUsedSecrets:i,disabled:o,onSelect:r(Z=>u({secretId:Z,version:"latest"}),"onSelect"),onCreateNew:r(Z=>I({mode:"create",name:y5(Z)||Z.trim(),value:""}),"onCreateNew"),triggerClassName:W("rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0",$&&$.status==="active"&&"pr-24 has-[>svg]:!pr-24")}),$&&$.status==="active"?(0,t.jsxs)(yr,{open:T,onOpenChange:R,children:[(0,t.jsx)(fz,{asChild:!0,children:(0,t.jsx)("button",{type:"button",disabled:o,onClick:r(Z=>{Z.preventDefault(),Z.stopPropagation(),R(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",he?"bg-amber-500/15 text-amber-700 dark:text-amber-400":"text-muted-foreground hover:bg-accent"),children:ne})}),(0,t.jsxs)(lr,{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"}),R(!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:ee},(Z,re)=>ee-re).filter(Z=>Z>0).map(Z=>(0,t.jsxs)("button",{type:"button",role:"radio","aria-checked":e.version===Z,onClick:r(()=>{u({version:Z}),R(!1)},"onClick"),className:W("flex w-full items-center rounded px-2 py-1.5 text-sm hover:bg-accent",e.version===Z&&"font-medium text-amber-700 dark:text-amber-400"),children:["v",Z]},Z))]})]}):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(Z=>{const re=Z.target.value,ce=a?.find(H=>H.key===re);u({userSecretKey:re,...ce&&!e.name.trim()?{name:ce.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(Z=>Z.key===e.userSecretKey)?(0,t.jsxs)("option",{value:e.userSecretKey,children:["Unknown (",e.userSecretKey,")"]}):null,(a??[]).map(Z=>(0,t.jsxs)("option",{value:Z.key,children:[Z.name,Z.status!=="active"?` (${Z.status})`:""]},Z.id))]}):(0,t.jsx)("input",{className:jte,placeholder:"user-secret key",value:e.userSecretKey,spellCheck:!1,disabled:o,"aria-label":"User secret key",onChange:r(Z=>u({userSecretKey:Z.target.value}),"onChange")}),(0,t.jsxs)("select",{"aria-label":"Requirement",value:e.required?"required":"optional",disabled:o,onChange:r(Z=>u({required:Z.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)(lr,{align:"start",className:"w-auto p-3",onInteractOutside:r(Z=>{const re=Z.detail.originalEvent.target;re&&S.current?.contains(re)&&Z.preventDefault()},"onInteractOutside"),children:C?.mode==="store"?(0,t.jsx)(Fnt,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(Z=>Z.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):C?.mode==="create"?(0,t.jsx)(JNe,{initialName:C.name,initialValue:C.value,existingSecretNames:n.map(Z=>Z.name),onCancel:r(()=>I(null),"onCancel"),onSubmit:q}):null})]}),M?(0,t.jsx)("p",{id:G,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"&&!B&&(e.name.trim()||e.textValue)?(0,t.jsxs)(ta,{children:[(0,t.jsx)(ea,{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)(Ai,{className:"size-4"})})}),(0,t.jsx)(sa,{align:"end",children:(0,t.jsx)(cs,{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)(Vn,{className:"size-4"})})]})]})}r(Znt,"EnvironmentVariableRow");var ert=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function trt(e){const s=e.indexOf(" #");return s>=0?e.slice(0,s):e}r(trt,"stripInlineComment");function srt(e){const s=e.trim();if(s.length>=2){const n=s[0],a=s[s.length-1];if(n==='"'&&a==='"'||n==="'"&&a==="'")return s.slice(1,-1)}return trt(s).trim()}r(srt,"unquote");function nrt(e){const s=[];for(const n of e.split(/\r?\n/)){const a=n.trim();if(!a||a.startsWith("#"))continue;const i=ert.exec(a);if(!i)continue;const o=i[1],l=srt(i[2]);s.push({key:o,value:l})}return s}r(nrt,"parseDotenv");var rrt=["PAPERCLIP_"],art="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 Kq(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(Kq,"normalizedEnvEntries");function QS(e){return JSON.stringify(Kq(e))}r(QS,"normalizedEnvKey");var E$=3;function P$(e){const s=e.slice(0,E$).join(", ");return e.length>E$?`${s} +${e.length-E$} more`:s}r(P$,"formatChangedNames");function wte(e){return e.map(s=>({...s}))}r(wte,"cloneRows");function irt(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(irt,"rowDirtyFields");var yy=(0,m.forwardRef)(r(function({value:s,onChange:n,secrets:a,userSecretDefinitions:i,onCreateSecret:o,recentlyUsedSecrets:l,disabled:c,reservedPrefixes:d=rrt,footerHint:u,onDirtyChange:h,hideDraftActions:p=!1},f){const x=Gc(),b=(0,m.useRef)(null),[v,j]=(0,m.useState)(()=>R$(s)),N=(0,m.useRef)(v),[w,k]=(0,m.useState)(()=>wte(v)),S=(0,m.useMemo)(()=>QS(s),[]),C=(0,m.useRef)(S),I=(0,m.useRef)(S),T=(0,m.useRef)(null),[R,A]=(0,m.useState)(S),[D,M]=(0,m.useState)(()=>new Set(R$(s).map(le=>le.name.trim()).filter(Boolean))),[$,E]=(0,m.useState)(null);(0,m.useEffect)(()=>{N.current=v},[v]);function B(le,ue=N.current){C.current=le,A(le),k(wte(ue))}r(B,"markCommitted");function z(le){M(ue=>{const Se=new Set(ue);for(const ye of le){const Ie=ye.name.trim();Ie&&Se.add(Ie)}return Se})}r(z,"touchCommittedNames");function q(le){const ue=R$(le);return j(ue),z(ue),ue}r(q,"adoptExternalValue"),(0,m.useEffect)(()=>{const le=QS(s);if(le===I.current)return;I.current=le;const ue=QS(lE(N.current)),Se=ue!==C.current,ye=T.current===le;if(ye&&(T.current=null),!Se){B(le,q(s));return}(ye||ue===le)&&(z(N.current),B(le))},[s]);const U=(0,m.useMemo)(()=>lE(v),[v]),F=(0,m.useMemo)(()=>QS(U),[U]),K=F!==R;(0,m.useEffect)(()=>{h?.(!c&&K)},[c,K,h]);const G=(0,m.useMemo)(()=>{const le=new Map(Kq(lE(w)).map(([Ie,Ke])=>[Ie,JSON.stringify(Ke)])),ue=new Map(Kq(U).map(([Ie,Ke])=>[Ie,JSON.stringify(Ke)])),Se=[],ye=[];for(const[Ie,Ke]of ue)le.has(Ie)?le.get(Ie)!==Ke&&ye.push(Ie):Se.push(Ie);return{added:Se,changed:ye,removed:[...le.keys()].filter(Ie=>!ue.has(Ie))}},[w,U]),se=(0,m.useMemo)(()=>{const le=[];return G.added.length>0&&le.push(`New: ${P$(G.added)}`),G.changed.length>0&&le.push(`Edited: ${P$(G.changed)}`),G.removed.length>0&&le.push(`Removed: ${P$(G.removed)}`),le.join(" · ")},[G]);(0,m.useEffect)(()=>{if(c||!K)return;function le(ue){ue.preventDefault(),ue.returnValue=""}return r(le,"handleBeforeUnload"),window.addEventListener("beforeunload",le),()=>window.removeEventListener("beforeunload",le)},[c,K]);const ee=(0,m.useCallback)(()=>c||!K?null:(T.current=F,(0,up.flushSync)(()=>{n(U)}),U??{}),[c,U,F,K,n]);(0,m.useImperativeHandle)(f,()=>({flushPendingDraft:ee}),[ee]),(0,m.useEffect)(()=>{const le=b.current?.closest("form");if(!le)return;function ue(){ee()}return r(ue,"handleSubmit"),le.addEventListener("submit",ue,!0),()=>le.removeEventListener("submit",ue,!0)},[ee]),(0,m.useEffect)(()=>{const le=b.current;if(!le)return;const ue=le;function Se(ye){const Ie=ye.target;if(!(Ie instanceof Element)||ue.contains(Ie))return;const Ke=Ie.closest("button");if(!Ke||Ke.disabled)return;const rt=`${Ke.getAttribute("aria-label")??""} ${Ke.textContent??""}`;(Ke.type==="submit"||/\b(save|create|update|test|import)\b/i.test(rt))&&ee()}return r(Se,"handleDocumentClick"),document.addEventListener("click",Se,!0),()=>document.removeEventListener("click",Se,!0)},[ee]);function ne(le){j(le)}r(ne,"updateDraft");function he(le,ue){ne(v.map(Se=>Se.id===le?{...Se,...ue}:Se))}r(he,"patchRow");function Z(le){ne(v.filter(ue=>ue.id!==le))}r(Z,"removeRow");function re(){const le=Ox();j([...v,le]),E({rowId:le.id,field:"name"})}r(re,"addRow");function ce(le){const ue=v.find(Se=>Se.id===le)?.name.trim();ue&&M(Se=>{if(Se.has(ue))return Se;const ye=new Set(Se);return ye.add(ue),ye})}r(ce,"markTouched");function H(le,ue){const Se=nrt(le);if(Se.length===0)return!1;const ye=v.filter(Ie=>Ie.id!==ue).map(Ie=>({...Ie}));for(const{key:Ie,value:Ke}of Se){const rt=ye.find(dt=>dt.name.trim()===Ie);rt?(rt.name=Ie,rt.source="text",rt.textValue=Ke,rt.secretId="",rt.sensitiveDismissed=!1,rt.userSecretKey="",rt.required=!0):ye.push({...Ox(),name:Ie,textValue:Ke})}return ne(ye),x?.pushToast({title:`Imported ${Se.length} variable${Se.length===1?"":"s"}`,tone:"success"}),!0}r(H,"bulkImport");function Q(le){const ue=v.map(Ie=>({...Ie})),Se=ue[ue.length-1];let ye;Se&&!Se.name&&!Se.textValue&&!Se.secretId&&!Se.userSecretKey?ye=Se:(ye=Ox(),ue.push(ye)),ye.source="secret",ye.secretId=le.id,ye.version="latest",ye.name||(ye.name=N1(le.name)),ne(ue)}r(Q,"bindRecentSecret");function Y(){K&&(T.current=F,n(U))}r(Y,"saveDraft");function te(){T.current=null,I.current=QS(s);const le=q(s);B(I.current,le)}r(te,"revertDraft");const ae=(0,m.useMemo)(()=>Ynt(v),[v]),me=(0,m.useMemo)(()=>v.reduce((le,ue)=>XNe(ue,a)||ZNe(ue,i)?le+1:le,0),[v,a,i]),oe=(0,m.useMemo)(()=>{const le=new Set(v.filter(ue=>ue.source==="secret"&&ue.secretId).map(ue=>ue.secretId));return(l??[]).filter(ue=>ue.status==="active"&&!le.has(ue.id)).slice(0,8)},[l,v]),ie=v.length>0,ge=u===void 0?art:u,be=(0,m.useMemo)(()=>new Map(w.map(le=>[le.id,le])),[w]);return(0,t.jsx)(Pd,{children:(0,t.jsxs)("div",{ref:b,className:"@container/env space-y-2",children:[me>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)(Vi,{className:"size-3.5"}),me," bindings need attention"]}):null,ie?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"hidden gap-x-1.5 @[40rem]/env:grid @[40rem]/env:grid-cols-(--gtc-14)",children:[(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Name"}),(0,t.jsx)("span",{className:"text-(length:--text-micro) font-medium uppercase tracking-wide text-muted-foreground",children:"Value"}),(0,t.jsx)("span",{})]}),v.map((le,ue)=>{const Se=Qnt(le.name,ae,d),ye=D.has(le.name.trim());return(0,t.jsx)(Znt,{row:le,isLast:ue===v.length-1,secrets:a,userSecretDefinitions:i,recentlyUsedSecrets:l,disabled:c,nameIssue:Se,showNameIssue:ye,dirtyFields:irt(le,be.get(le.id)),onPatch:r(Ie=>he(le.id,Ie),"onPatch"),onRemove:r(()=>Z(le.id),"onRemove"),onNameBlur:r(()=>ce(le.id),"onNameBlur"),onNamePaste:r(Ie=>H(Ie,le.id),"onNamePaste"),onEnterInValueLast:re,onCreateSecret:o,onToast:r(Ie=>x?.pushToast({title:Ie,tone:"success"}),"onToast"),focusRequest:$?.rowId===le.id?$.field:null,onFocusConsumed:r(()=>E(null),"onFocusConsumed")},le.id)})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No environment variables"}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 pt-1",children:[(0,t.jsxs)("button",{type:"button",onClick: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)(bn,{className:"size-3.5"}),"Add variable"]}),oe.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)(ki,{className:"size-3"}),"Recently used:"]}),oe.map(le=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>Q(le),"onClick"),className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-mono text-(length:--text-micro) text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",title:`Bind ${le.name}`,children:["+ ",le.name]},le.id))]}):null]}),K&&!c&&!p?(0,t.jsxs)("div",{role:"status",className:"mt-3 flex w-full flex-col gap-3 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-3 text-amber-950 shadow-sm dark:bg-amber-500/15 dark:text-amber-100 @[34rem]/env:flex-row @[34rem]/env:items-center @[34rem]/env:justify-between",children:[(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-0.5",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,t.jsx)("span",{className:"size-2 rounded-full bg-amber-500 shadow-(--shadow-extract-13)"}),(0,t.jsx)("span",{children:"Unsaved changes"})]}),se?(0,t.jsx)("p",{className:"min-w-0 truncate pl-4 text-xs text-amber-950/80 dark:text-amber-100/80",title:se,children:se}):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)(Ni,{className:"size-4"}),"Revert"]}),(0,t.jsxs)("button",{type:"button",onClick:Y,className:"inline-flex h-9 items-center gap-1.5 rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90",children:[(0,t.jsx)(If,{className:"size-4"}),"Save"]})]})]}):null,ge?(0,t.jsx)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:ge}):null,v.some(le=>le.source==="user_secret"&&le.userSecretKey)?(0,t.jsxs)("p",{className:"inline-flex items-start gap-1 text-(length:--text-micro) text-muted-foreground/70",children:[(0,t.jsx)(Th,{className:"mt-0.5 size-3 shrink-0"}),(0,t.jsx)("span",{children:"User secrets resolve from the user responsible for the run. Required bindings fail until that user sets their value under Secrets → My secrets."})]}):null]})})},"EnvironmentVariablesEditor")),ort="env.",sA="access.",Wq=/^[A-Za-z_][A-Za-z0-9_]*$/;function eSe(e){return e?e.startsWith("access.")?"api":e.startsWith("env.")?"env":"config":"config"}r(eSe,"deliveryModeForConfigPath");function tSe(e){switch(e){case"env":return"Env var";case"api":return"API access";default:return"Config"}}r(tSe,"deliveryModeLabel");function lrt(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(lrt,"deliveryModeDescription");function sSe(e){return e?e.startsWith("access.")?e.slice(7):e.startsWith("env.")?e.slice(4):e:""}r(sSe,"aliasFromConfigPath");function crt(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(crt,"consumerTypeLabel");var drt={numeric:!0,sensitivity:"base"};function BC(e){return e.kind==="company"?e.secret.name:e.definition.name}r(BC,"getSecretPathRowName");function sN(e){return e.split("/").filter(s=>s.length>0)}r(sN,"splitSecretPath");function M$(e){return sN(e).join("/")}r(M$,"normalizeSecretPath");function kte(e,s){return s.every((n,a)=>e[a]===n)}r(kte,"startsWithSegments");function Nte(e,s){return e.localeCompare(s,void 0,drt)}r(Nte,"compareNames");function urt(e,s){const n=sN(s),a=e.map(c=>({row:c,name:BC(c),segments:sN(BC(c))})),i=new Set,o=[];for(const c of a){if(!kte(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(!kte(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)=>Nte(c.name,d.name)),o.sort((c,d)=>Nte(BC(c),BC(d))),{folders:l,secrets:o}}r(urt,"buildSecretPathListing");function mrt(e){const s=sN(e);return s.map((n,a)=>({name:n,path:s.slice(0,a+1).join("/")}))}r(mrt,"buildSecretPathBreadcrumbs");function hrt(e){return e.trim()?e.includes("/")?"Folder name cannot contain slashes.":null:"Folder name is required."}r(hrt,"validateSecretFolderSegment");function I_({name:e,basePath:s="",className:n,leafClassName:a}){const i=sN(e),o=sN(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(I_,"SecretPathName");function prt(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(prt,"fingerprintLabel");function nSe({fingerprint:e,length:s,className:n}){const{pushToast:a}=pa(),i=prt(e,s);if(!e)return(0,t.jsxs)("span",{className:W("inline-flex items-center gap-1 font-mono",n),children:[(0,t.jsx)(Cz,{className:"size-3 shrink-0"}),i]});const o=`sha256:${e}`;return(0,t.jsxs)("button",{type:"button",onClick:r(()=>{ha(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)(Cz,{className:"size-3 shrink-0"}),i,(0,t.jsx)(Ar,{className:"size-3 shrink-0 opacity-60"})]})}r(nSe,"FingerprintChip");function xW({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(xW,"ProposalJustification");function A_({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)(_r,{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(A_,"AgentRefChip");function gW({configPath:e}){const s=eSe(e),n=s==="env",a=s==="api";return(0,t.jsxs)(lt,{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)(gve,{className:"size-3"}):a?(0,t.jsx)(bM,{className:"size-3"}):null,tSe(s)]})}r(gW,"DeliveryBadge$1");function bW({className:e}){return(0,t.jsxs)(lt,{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)(hc,{className:"size-3"})," Proposed"]})}r(bW,"ProposedBadge");function XM(e){return sSe(e.configPath)}r(XM,"bindingEnvKey");function vW(e){return e.secretProposalId?{name:e.secretProposalName??"proposed secret",pending:!0}:{name:e.secretName??"secret",pending:!1}}r(vW,"bindingSecretLabel");function Ste(e){return e instanceof un?e.message||`Request failed: ${e.status}`:e instanceof Error?e.message:"Something went wrong. Try again."}r(Ste,"readableError");function rSe(e,s=[]){const n=Mt(),{pushToast:a}=pa(),[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 Sr.approveProposal(e,k.id,{overrides:{name:S,description:w.description.trim()||null,providerConfigId:w.providerConfigId||null}})}return Sr.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"} · ${XM(w)||"binding"}`,tone:"success"}),o(null),p(null),f()},"onSuccess"),onError:r(w=>p(Ste(w)),"onError")}),b=je({mutationFn:r(({proposal:w,reason:k})=>Sr.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(Ste(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)(frt,{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)(grt,{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(rSe,"useProposalReview");function frt({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)(Vs,{open:!!e,onOpenChange:r(p=>!p&&o(),"onOpenChange"),children:(0,t.jsx)(Qs,{className:"sm:max-w-lg",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:c?"Approve & create secret":"Approve binding"}),(0,t.jsx)(yn,{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)(A_,{agent:e.proposal.proposedBy,className:"font-medium text-foreground"})]}),(0,t.jsx)(xW,{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)(Ws,{htmlFor:"approve-folder",children:"Folder"}),(0,t.jsx)(pt,{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)(Ws,{htmlFor:"approve-name",children:"Name"}),(0,t.jsx)(pt,{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)(I_,{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)(Ws,{htmlFor:"approve-description",children:"Description"}),(0,t.jsx)(pt,{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)(Ws,{htmlFor:"approve-provider-config",children:"Provider vault"}),(0,t.jsxs)("select",{id:"approve-provider-config",value:e.providerConfigId,onChange:r(p=>i({...e,providerConfigId:p.target.value}),"onChange"),className:"h-9 w-full rounded-md border border-input bg-transparent px-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",children:[(0,t.jsx)("option",{value:"",children:"Deployment default"}),u.map(p=>(0,t.jsx)("option",{value:p.id,children:p.displayName},p.id))]})]}):null,(0,t.jsx)("div",{className:"rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-muted-foreground",children:(0,t.jsx)(nSe,{fingerprint:e.proposal.valueFingerprintSha256,length:e.proposal.valueLength})})]}):(0,t.jsx)(xrt,{draft:e,onChange:i}),s?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:s}):null,(0,t.jsxs)(mr,{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(frt,"ApproveDialog");function xrt({draft:e,onChange:s}){const{proposal:n}=e,a=vW(n),i=XM(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)(A_,{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)(gW,{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)(ki,{className:"size-3.5 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:a.name}),a.pending?(0,t.jsx)(bW,{}):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)(mi,{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(xrt,"BindingApproveBody");function grt({proposal:e,reason:s,error:n,pending:a,onReasonChange:i,onCancel:o,onConfirm:l}){const c=s.trim().length>0;return(0,t.jsx)(Vs,{open:!!e,onOpenChange:r(d=>!d&&o(),"onOpenChange"),children:(0,t.jsx)(Qs,{className:"sm:max-w-md",children:e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Reject proposal"}),(0,t.jsxs)(yn,{children:["The reason is sent back to"," ",(0,t.jsx)(A_,{agent:e.proposedBy,className:"text-foreground"}),". Dependent bindings are rejected too."]})]}),(0,t.jsxs)("div",{className:"space-y-1",children:[(0,t.jsx)(Ws,{htmlFor:"reject-reason",children:"Reason"}),(0,t.jsx)(Tn,{id:"reject-reason",value:s,onChange:r(d=>i(d.target.value),"onChange"),rows:3,autoFocus:!0,placeholder:"Why is this being rejected?"})]}),n?(0,t.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:n}):null,(0,t.jsxs)(mr,{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(grt,"RejectDialog");function aSe({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)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("span",{tabIndex:0,children:c})}),(0,t.jsx)(Wn,{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(aSe,"ProposalActions");function iSe(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}r(iSe,"asRecord$16");function oSe(e){const s=iSe(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(oSe,"readSecretRef");function brt(e){const s=iSe(e?.env);if(!s)return[];const n=[];for(const[a,i]of Object.entries(s)){const o=oSe(i);o&&n.push({name:a,...o})}return n}r(brt,"parseEnvSecretRefs");function vrt(e){if(!e)return[];const s=[];for(const[n,a]of Object.entries(e)){if(!n.startsWith("access."))continue;const i=oSe(a);i&&s.push({name:n.slice(sA.length),...i})}return s}r(vrt,"parseAccessGrants");function yrt(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(yrt,"summarizeAgentBindings");var Cte=0;function lSe(){return Cte+=1,`access-row-${Cte}`}r(lSe,"nextAccessRowId");function D$(e){return e.map(s=>({id:lSe(),alias:s.name,secretId:s.secretId,version:s.version}))}r(D$,"entriesToRows");function _te(e){const s={};for(const n of e){const a=n.alias.trim();!a||!Wq.test(a)||!n.secretId||(s[a]={type:"secret_ref",secretId:n.secretId,version:n.version})}return s}r(_te,"rowsToAccessMap");function Ite(e){return JSON.stringify(Object.keys(e).sort().map(s=>{const n=e[s];return[s,n.secretId,n.version??"latest"]}))}r(Ite,"normalizeAccessMapKey");function Ate({mode:e}){return e==="env"?(0,t.jsxs)(lt,{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)(gve,{className:"size-3"})," Env var"]}):(0,t.jsxs)(lt,{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)(bM,{className:"size-3"})," API access"]})}r(Ate,"DeliveryBadge");function jrt({config:e,secrets:s,onChange:n,onCreateSecret:a,disabled:i,proposals:o,onApproveProposal:l,onRejectProposal:c}){const d=(0,m.useMemo)(()=>(o??[]).filter($=>$.kind==="binding"),[o]),u=(0,m.useMemo)(()=>brt(e),[e]),h=(0,m.useMemo)(()=>vrt(e),[e]),p=(0,m.useMemo)(()=>yrt(u,h),[u,h]),f=(0,m.useMemo)(()=>_te(D$(h)),[h]),x=(0,m.useMemo)(()=>Ite(f),[f]),[b,v]=(0,m.useState)(()=>D$(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(D$(h)))},[x,h]);const C=r($=>s.find(E=>E.id===$)?.name??`${$.slice(0,8)}…`,"secretName");function I($){v($);const E=_te($);k.current=Ite(E),n(E)}r(I,"emit");function T($,E){I(b.map(B=>B.id===$?{...B,...E}:B))}r(T,"patchRow");function R($){I(b.filter(E=>E.id!==$))}r(R,"removeRow");function A(){v($=>[...$,{id:lSe(),alias:"",secretId:"",version:"latest"}])}r(A,"addRow");const D=(0,m.useMemo)(()=>{const $=new Map;for(const E of b){const B=E.alias.trim();B&&$.set(B,($.get(B)??0)+1)}return $},[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($=>(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)(ki,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:C($.secretId)}),$.envKeys.length>0?(0,t.jsx)(Ate,{mode:"env"}):null,$.apiAliases.length>0?(0,t.jsx)(Ate,{mode:"api"}):null,(0,t.jsx)("span",{className:"min-w-0 truncate font-mono text-(length:--text-micro) text-muted-foreground",children:[...$.envKeys.map(E=>`${ort}${E}`),...$.apiAliases.map(E=>`${sA}${E}`)].join(" · ")})]},$.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($=>{const E=vW($),B=XM($);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)(gW,{configPath:$.configPath}),(0,t.jsx)("code",{className:"font-mono",children:B||$.configPath}),(0,t.jsx)("span",{className:"text-muted-foreground",children:"→"}),(0,t.jsx)(ki,{className:"size-3 text-muted-foreground"}),(0,t.jsx)("span",{className:"font-medium",children:E.name}),E.pending?(0,t.jsx)(bW,{}):null]}),(0,t.jsxs)("p",{className:"flex flex-wrap items-center gap-1 text-muted-foreground",children:[(0,t.jsxs)("span",{children:["proposed by ",$.proposedBy.name]}),(0,t.jsx)("span",{"aria-hidden":"true",children:"·"}),(0,t.jsxs)("span",{className:"truncate italic",children:["“",$.justification,"”"]})]})]}),(0,t.jsx)(aSe,{proposal:$,onApprove:l,onReject:c,disabled:i,size:"xs"})]},$.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($=>{const E=$.alias.trim(),B=!!E&&!Wq.test(E),z=!!E&&(D.get(E)??0)>1,q=s.find(U=>U.id===$.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)(pt,{value:$.alias,onChange:r(U=>T($.id,{alias:U.target.value}),"onChange"),onBlur:r(U=>{const F=U.target.value.trim();if(F&&!Wq.test(F)){const K=N1(F);K&&K!==F&&T($.id,{alias:K})}},"onBlur"),placeholder:"ALIAS","aria-label":"Access alias",disabled:i,className:W("h-9 font-mono text-sm",(B||z)&&"border-destructive text-destructive")})}),(0,t.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5",children:[(0,t.jsxs)(yr,{open:j?.rowId===$.id,onOpenChange:r(U=>{!U&&j?.rowId===$.id&&N(null)},"onOpenChange"),children:[(0,t.jsx)(fz,{asChild:!0,children:(0,t.jsx)("div",{ref:r(U=>{U?w.current.set($.id,U):w.current.delete($.id)},"ref"),className:"min-w-0 flex-1",children:(0,t.jsx)(fW,{secretId:$.secretId,secrets:s,onSelect:r(U=>T($.id,{secretId:U,version:"latest",alias:!$.alias.trim()&&U?N1(C(U)):$.alias}),"onSelect"),onCreateNew:a?U=>{window.setTimeout(()=>{N({rowId:$.id,name:y5(U)||U.trim()})},0)}:void 0,disabled:i,triggerClassName:"h-9 min-h-9"})})}),(0,t.jsx)(lr,{align:"start",className:"w-auto p-3",onInteractOutside:r(U=>{const F=U.detail.originalEvent.target;F&&w.current.get($.id)?.contains(F)&&U.preventDefault()},"onInteractOutside"),children:j?.rowId===$.id&&a?(0,t.jsx)(JNe,{initialName:j.name,initialValue:"",existingSecretNames:s.map(U=>U.name),onCancel:r(()=>N(null),"onCancel"),onSubmit:r(async(U,F)=>{const K=await a(U,F);T($.id,{secretId:K.id,version:"latest",alias:$.alias.trim()||N1(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:$.version===void 0?"latest":String($.version),onChange:r(U=>{const F=U.target.value;T($.id,{version:F==="latest"?"latest":Number.parseInt(F,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,F)=>{const K=q.latestVersion-F;return K<=0?null:(0,t.jsxs)("option",{value:K,children:["v",K]},K)}):null]})]}),(0,t.jsx)("button",{type:"button",onClick:r(()=>R($.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)(ua,{className:"size-3.5"})})]}),B?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Invalid alias — use letters, digits and _"}):z?(0,t.jsx)("p",{className:"pl-0.5 text-(length:--text-micro) text-destructive",children:"Duplicate alias"}):null]},$.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)(bn,{className:"size-3.5"}),"Add API access"]})]}),(0,t.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/70",children:[lrt("api")," The agent reads them by alias through ",(0,t.jsx)("code",{children:"GET /agents/me/secrets"}),"."]})]})}r(jrt,"AgentSecretAccessEditor");function wrt(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}r(wrt,"asNonEmptyString$3");function krt(e){return wrt(e)!==null}r(krt,"hasLegacyWorkingDirectory");function Nrt(e){return e.isCreate?!1:krt(e.adapterConfig?.cwd)}r(Nrt,"shouldShowLegacyWorkingDirectoryField");var cSe=new Set;function Srt(e){return cSe.has(e)}r(Srt,"isAdapterTypeHidden");function Crt(e){cSe=new Set(e)}r(Crt,"setDisabledAdapterTypes");function _rt(e){return!Nh(e).hideFromVisualSelection}r(_rt,"isVisualAdapterChoice");function dSe(e,s=hW()){const n=e??qf;return s.map(a=>({value:a.type,label:n(a.type),comingSoon:!!Nh(a.type).comingSoon,hidden:Srt(a.type),experimental:!!Nh(a.type).experimental}))}r(dSe,"listAdapterOptions");function uSe(e={}){const s=e.enabled??!0,{data:n}=X({queryKey:P.adapters.all,queryFn:r(()=>ch.list(),"queryFn"),enabled:s,staleTime:3e5});return n&&_nt(n.filter(a=>a.source==="external").map(a=>({type:a.type,label:a.label,disabled:a.disabled,overrideDisabled:a.overridePaused}))),(0,m.useEffect)(()=>{n&&Crt(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(uSe,"useDisabledAdaptersSync");function Irt(e={}){const s=e.enabled??!0,{data:n}=X({queryKey:P.adapters.all,queryFn:r(()=>ch.list(),"queryFn"),enabled:s,staleTime:3e5});return n!==void 0}r(Irt,"useAdapterRegistryLoaded");function j5(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))}r(j5,"omitUndefinedEntries");function D2(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=j5(s.adapterType!==void 0?{...Object.fromEntries(vLe.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=j5({...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(D2,"buildAgentUpdatePatch");var Art="kubernetes";function Trt(e){return e.driver!=="sandbox"?!1:e.config?.provider===Art}r(Trt,"isKubernetesSandboxEnvironment");function yW(e,s){return e!=="kubernetes"?{forced:!1,kubernetesEnvironment:null}:{forced:!0,kubernetesEnvironment:s.find(n=>Trt(n))??null}}r(yW,"resolveForcedKubernetesEnvironment");var L$={identity:{},adapterConfig:{},heartbeat:{},debug:{},runtime:{}},YS={};function Rrt(e){return e==="claude_local"||e==="codex_local"||e==="paperclip_runner"||e==="opencode_local"}r(Rrt,"supportsAdapterModelRefresh");function Ert(e,s){return aNe(e,s).model}r(Ert,"resolvePaperclipRunnerTransitionModel");function Tte(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(Tte,"isOverlayDirty");function Vq(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)=>Vq(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&&Vq(o,a[i]))}return!1}r(Vq,"overlayValuesEqual");function Prt(e,s){const n=r((a,i)=>Object.fromEntries(Object.entries(a).filter(([o,l])=>!(o in i)||!Vq(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(Prt,"subtractPersistedOverlay");var Jm="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 Mrt(e){return e.split(",").map(s=>s.trim()).filter(Boolean)}r(Mrt,"parseCommaArgs");function Drt(e){return Array.isArray(e)?e.filter(s=>typeof s=="string").join(", "):typeof e=="string"?e:""}r(Drt,"formatArgList");var Lrt=[{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"}],$rt=[{id:"",label:"Auto"},{id:"plan",label:"Plan"},{id:"ask",label:"Ask"}],Ort=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"medium",label:"Medium"},{id:"high",label:"High"}],Frt=[{id:"",label:"Auto"},{id:"low",label:"Low"},{id:"high",label:"High"},{id:"max",label:"Max"}],Brt=2,Rte=10,zrt=1,mSe=300;function cE(e,s,n){return Math.max(s,Math.min(n,Math.floor(e)))}r(cE,"clampInteger");function qrt(e){return cE(e,0,mSe)*1e3}r(qrt,"clampDelayMsFromSeconds");function Urt({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(Urt,"ConfigSections");function hSe(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}=gs(),x=Mt(),b=(0,m.useRef)(null),v=uSe(),{data:j=[]}=X({queryKey:f?P.secrets.list(f):["secrets","none"],queryFn:r(()=>Sr.list(f),"queryFn"),enabled:!!f}),{data:N=[]}=X({queryKey:f?P.secrets.userDefinitions(f):["user-secret-definitions","none"],queryFn:r(()=>Sr.listUserSecretDefinitions(f),"queryFn"),enabled:!!f,retry:!1}),w=a?null:e.agent.id,{data:k=[]}=X({queryKey:f?P.secrets.proposals(f,"pending"):["secret-proposals","none"],queryFn:r(()=>Sr.listProposals(f,"pending"),"queryFn"),enabled:!!f&&!a,retry:!1}),S=(0,m.useMemo)(()=>k.filter(tt=>tt.kind==="binding"&&tt.target?.id===w),[k,w]),C=rSe(f,[]),{data:I}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn"),retry:!1}),T=(0,m.useMemo)(()=>{const tt=new Set(v);return I?.enableNativeRunner!==!0&&tt.add("paperclip_runner"),tt},[v,I?.enableNativeRunner]),R=I?.enableEnvironments===!0,A=I?.enableManagedSandboxOnly===!0,D=I===void 0||A,{data:M}=X({queryKey:P.instance.generalSettings,queryFn:r(()=>Or.getGeneral(),"queryFn"),retry:!1}),{data:$}=X({queryKey:P.instance.settings,queryFn:r(()=>Or.get(),"queryFn"),retry:!1}),{data:E=[]}=X({queryKey:f?P.environments.list(f):["environments","none"],queryFn:r(()=>Ri.list(f),"queryFn"),enabled:!!f&&(R||M?.executionMode==="kubernetes")}),{forced:B,kubernetesEnvironment:z}=(0,m.useMemo)(()=>yW(M?.executionMode,E),[M?.executionMode,E]),q=je({mutationFn:r(tt=>{if(!f)throw new Error("Select an organization to create secrets");return Sr.create(f,tt)},"mutationFn"),onSuccess:r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.list(f)})},"onSuccess")}),U=je({mutationFn:r(async({file:tt,namespace:Dt})=>{if(!f)throw new Error("Select an organization to upload images");return fb.uploadImage(f,tt,Dt)},"mutationFn")}),[F,K]=(0,m.useState)(L$),[G,se]=(0,m.useState)(!1),[ee,ne]=(0,m.useState)(0),he=(0,m.useRef)(null),Z=(0,m.useRef)(null),re=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(!a){if(he.current!==null&&e.agent!==he.current&&!re.current){const tt=Z.current;Z.current=null,K(Dt=>tt?Prt(Dt,tt):{...L$})}he.current=e.agent}},[a,a?void 0:e.agent]);const ce=!a&&(Tte(F)||G);function H(tt,Dt,xs){const Gs=F[tt];return Dt in Gs?Gs[Dt]:xs}r(H,"eff");function Q(tt,Dt,xs){K(Gs=>({...Gs,[tt]:{...Gs[tt],[Dt]:xs}}))}r(Q,"mark");function Y(){return b.current?.flushPendingDraft()??null}r(Y,"flushEnvironmentDraft");const te=(0,m.useCallback)(tt=>{a||K(Dt=>{const xs={...e.agent.adapterConfig??{},...Dt.adapterConfig},Gs={...Dt.adapterConfig};for(const[Bn,Cr]of Object.entries(tt))Gs[`${sA}${Bn}`]=Cr;for(const Bn of Object.keys(xs))Bn.startsWith("access.")&&(Bn.slice(7)in tt||(Gs[Bn]=void 0));return{...Dt,adapterConfig:Gs}})},[a,a?void 0:e.agent]),ae=(0,m.useCallback)(()=>{K({...L$}),se(!1),ne(tt=>tt+1)},[]),me=(0,m.useCallback)(async()=>{if(a)return;const tt=Y(),Dt=tt?{...F,adapterConfig:{...F.adapterConfig,env:tt}}:F;Tte(Dt)&&await e.onSave(D2(e.agent,Dt))},[a,ce,F,e]);(0,m.useEffect)(()=>{a||(e.onDirtyChange?.(ce),e.onSaveActionChange?.(me),e.onCancelActionChange?.(ae))},[a,ce,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange,me,ae]),(0,m.useEffect)(()=>{if(!a)return()=>{e.onSaveActionChange?.(null),e.onCancelActionChange?.(null),e.onDirtyChange?.(!1)}},[a,e.onDirtyChange,e.onSaveActionChange,e.onCancelActionChange]);const oe=a?{}:e.agent.adapterConfig??{},ie=a?{}:e.agent.runtimeConfig??{},ge=a?{}:ie.heartbeat??{},be=a?{}:ie.debug??{},le=a?e.values.adapterType:F.adapterType??e.agent.adapterType,ue=Ky(),Se=ue(le),ye=Se.supportsInstructionsBundle||Se.supportsSkills||Se.supportsLocalAgentJwt,Ie=ye&&!D&&Nrt({isCreate:a,adapterConfig:oe}),Ke=(0,m.useMemo)(()=>tS(le),[le]),rt=(0,m.useMemo)(()=>new Set(kBe(le)),[le]),dt=a?e.values:null,de=a?tt=>e.onChange(tt):null;a&&dt.claudeStoredSessionId;const ze=r(()=>{f&&x.invalidateQueries({queryKey:P.secrets.userDefinitions(f)})},"invalidateUserSecretDefinitions"),gt=r(tt=>{if(!a||!de)return;const Dt=dt.envBindings??{};de({envBindings:{...Dt,...Bw()},claudeStoredSessionId:tt}),ze()},"handleClaudeLoginStored"),bt=r(async()=>{if(a)return;const tt={...Y()??H("adapterConfig","env",oe.env??YS),...Bw()},Dt={...F,adapterConfig:{...F.adapterConfig,env:tt}};K(Dt),await e.onSave({...D2(e.agent,Dt),applyStoredClaudeLogin:!0}),ze()},"handleClaudeLoginStoredEdit"),De=r(async tt=>{if(a||!tt.companyIdentityDiffers)return;const Dt={...Y()??H("adapterConfig","env",oe.env??YS),CODEX_HOME:{type:"secret_ref",secretId:tt.secretId,version:"latest"}},xs={...F,adapterConfig:{...F.adapterConfig,env:Dt}};K(xs),Z.current=xs,re.current=!0;try{await e.onSave(D2(e.agent,xs))}catch(Gs){throw Z.current=null,Gs}finally{re.current=!1}ze()},"handleCodexAccountBindingEdit"),Qe=r(()=>{if(!a||!de)return;const tt=dt.envBindings??{};de({envBindings:{...tt,...Bw()},claudeApplyStoredLogin:!0}),ze()},"handleApplyStoredClaudeLogin"),mt=r(async()=>{if(a)return;const tt={...Y()??H("adapterConfig","env",oe.env??YS),...Bw()},Dt={...F,adapterConfig:{...F.adapterConfig,env:tt}};K(Dt),await e.onSave({...D2(e.agent,Dt),applyStoredClaudeLogin:!0}),ze()},"handleApplyStoredClaudeLoginEdit"),Ye=a?dt.defaultEnvironmentId??"":H("identity","defaultEnvironmentId",e.agent.defaultEnvironmentId??""),it=(0,m.useMemo)(()=>Ye?(E.find(tt=>tt.id===Ye)??null)?.driver==="local"?"":Ye:"",[E,Ye]),Nt=(0,m.useMemo)(()=>E.find(tt=>tt.id===it)??null,[it,E]),Ze=(0,m.useMemo)(()=>{const tt=$?.defaultEnvironmentId??null;return tt?(E.find(Dt=>Dt.id===tt)??null)?.driver==="local"?"":tt:""},[E,$?.defaultEnvironmentId]),Pe=(0,m.useMemo)(()=>E.find(tt=>tt.id===Ze)??null,[E,Ze]),Ce=(0,m.useMemo)(()=>{try{return Zk({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:$?.defaultEnvironmentId??null,localDefaultEnvironmentId:tN(E),managedSandboxOnly:I?.enableManagedSandboxOnly===!0,managedSandboxEnvironmentId:eN(E),visibleEnvironmentIds:E.map(tt=>tt.id)})}catch{return null}},[Ye,$?.defaultEnvironmentId,E,I?.enableManagedSandboxOnly]),Ve=(0,m.useMemo)(()=>E.find(tt=>tt.id===Ce)??null,[E,Ce]),{data:Ge}=X({queryKey:f?P.environments.capabilities(f):["environment-capabilities","none"],queryFn:r(()=>Ri.capabilities(f),"queryFn"),enabled:!!f&&Se.login!=null});(0,m.useEffect)(()=>{!a||!de||!B||!z||it!==z.id&&de({defaultEnvironmentId:z.id})},[a,de,B,z,it]);const ot=(0,m.useMemo)(()=>E.filter(tt=>{if(!rt.has(tt.driver)||tt.driver==="local")return!1;if(tt.driver!=="sandbox")return!0;const Dt=typeof tt.config?.provider=="string"?tt.config.provider:null;return Dt!==null&&Dt!=="fake"}),[E,rt]),Ee=(0,m.useMemo)(()=>!Nt||ot.some(tt=>tt.id===Nt.id)?ot:[...ot,Nt],[Nt,ot]),Je=R&&(B||it.length>0||ot.length>=1),_e=Pe?Hv(Pe):A?"Paperclip Computer":"Local",He=le==="paperclip_runner"?String(a?e.values.adapterSchemaValues?.provider??"codex":H("adapterConfig","provider",oe.provider==="acpx"&&oe.acpxAgent==="codex"?"codex":oe.provider??"codex")):void 0,ns=le==="opencode_local"&&Rpe.safeParse(F.runtime.runtimeConfig?.aiConnection??ie.aiConnection).data?.provider==="openrouter"?"openrouter":He,fe=f?P.agents.adapterModels(f,le,it||null,ns):["agents","none","adapter-models",le],{data:ct,error:Ue}=X({queryKey:fe,queryFn:r(()=>Lt.adapterModels(f,le,{environmentId:it||null,provider:ns}),"queryFn"),enabled:!!f}),[Et,$t]=(0,m.useState)(null),[js,Fe]=(0,m.useState)(!1),xt=ct??n??[],Wt="command",{data:Cs,refetch:Ts}=X({queryKey:f?P.agents.detectModel(f,le):["agents","none","detect-model",le],queryFn:r(()=>{if(!f)throw new Error("Select an organization to detect the model");return Lt.detectModel(f,le)},"queryFn"),enabled:!!(f&&ye&&le!=="opencode_local"&&le!=="paperclip_runner")}),Ct=Cs?.model??null;Cs?.candidates;const{data:ds=[]}=X({queryKey:f?P.agents.list(f):["agents","none","list"],queryFn:r(()=>Lt.list(f),"queryFn"),enabled:!!(!a&&f)}),Oe={mode:s,isCreate:a,adapterType:le,values:a?e.values:null,set:a?tt=>e.onChange(tt):null,config:oe,eff:H,mark:Q,models:xt,hideInstructionsFile:h||D,managedSandboxOnly:D},[xe,Gt]=(0,m.useState)(!1),[Pt,os]=(0,m.useState)(!1),ws=gNe(le),Hs=r(tt=>(0,t.jsxs)(t.Fragment,{children:[le==="claude_local"&&(0,t.jsx)(cet,{...Oe,section:tt}),(0,t.jsx)(Ke.ConfigFields,{...Oe,section:tt,hideModel:ye})]}),"renderAdapterFields"),[tr,Le]=(0,m.useState)(!1),[et,vt]=(0,m.useState)(!1);function $e(tt){if(a){const xs=Ke.buildAdapterConfig(dt);return tt&&Object.assign(xs,tt),j5(xs)}const Dt={...oe,...F.adapterConfig};return tt&&Object.assign(Dt,tt),j5(Dt)}r($e,"buildAdapterConfigForTest");const Ft=je({mutationFn:r(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");const tt=Y(),Dt=tt?{env:tt}:void 0;let xs=$,Gs=E,Bn=I?.enableManagedSandboxOnly===!0;if(!Ye)try{const[cr,rr,sr]=await Promise.all([x.ensureQueryData({queryKey:P.instance.settings,queryFn:r(()=>Or.get(),"queryFn")}),x.ensureQueryData({queryKey:P.environments.list(f),queryFn:r(()=>Ri.list(f),"queryFn")}),x.ensureQueryData({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn")})]);xs=cr,Gs=rr,Bn=sr?.enableManagedSandboxOnly===!0}catch{throw new Error("Could not load environment settings to determine which environment to test in. Retry the test.")}const Cr=Zk({agentDefaultEnvironmentId:Ye||null,instanceDefaultEnvironmentId:xs?.defaultEnvironmentId??null,localDefaultEnvironmentId:tN(Gs),managedSandboxOnly:Bn,managedSandboxEnvironmentId:eN(Gs),visibleEnvironmentIds:Gs.map(cr=>cr.id)}),Qr=$e(Dt),Nr=a?void 0:e.agent.id,Rr=a?void 0:cJ.safeParse(F.runtime.runtimeConfig?.aiConnection??e.agent.runtimeConfig.aiConnection).data;if(e.compactTestFeedback){const cr=le==="paperclip_runner"?Qr.provider==="codex"?"codex_local":Qr.provider==="acpx"&&Qr.acpxAgent==="grok"?"grok_local":Qr.provider==="acpx"&&Qr.acpxAgent==="claude"?"claude_local":le:le;return eNe({companyId:f,adapterType:le,providerAdapter:cr,adapterConfig:Qr,agentId:Nr,aiConnection:Rr,environmentId:Cr})}return Lt.testEnvironment(f,le,{adapterConfig:Qr,agentId:Nr,aiConnection:Rr,environmentId:Cr})},"mutationFn")}),[wt,Yt]=(0,m.useState)(!1),[Zt,us]=(0,m.useState)(null),ht="Test",kt=!a&&!!e.isSaving,Rs=wt||kt||!f,hs=(0,m.useRef)(Ft.reset);hs.current=Ft.reset;const jn=(0,m.useRef)(()=>{});jn.current=()=>{if(!a||!de)return;const tt=dt.envBindings??{},Dt=dt.claudeStoredSessionId!=null||dt.claudeApplyStoredLogin===!0,xs=yte in tt;if(!Dt&&!xs)return;const Gs={...tt};delete Gs[yte],de({envBindings:Gs,claudeStoredSessionId:null,claudeApplyStoredLogin:!1})},(0,m.useEffect)(()=>{hs.current(),us(null),jn.current()},[le,Ce]);const Es=Se.login!=null,an=Ft.data,Jt=an!=null&&ue(an.adapterType).login!=null,Xs=an&&Jt?an.checks.find(tt=>tt.code==="adapter_auth_missing")??null:null,Zs=typeof Ve?.config?.provider=="string"?Ve.config.provider:null,qr=Zs!=null&&Ge?.sandboxProviders?.[Zs]?.supportsLoginPty===!0,pr=Se.login!=null,jr=(a||!(F.runtime.runtimeConfig?.aiConnection??ie.aiConnection))&&Es&&Ve?.driver==="sandbox"&&!!Ce&&!!f&&!!Xs&&(!pr||qr),mn=(0,m.useCallback)(async()=>{if(!f)throw new Error("Select an organization to test adapter environment");Yt(!0),us(null),Ft.reset();try{return await Ft.mutateAsync()}catch(tt){throw us(tt instanceof Error?tt.message:"Environment test failed"),tt}finally{Yt(!1)}},[f,Ft]),Zn=(0,m.useRef)(()=>{});(0,m.useEffect)(()=>{Zn.current=()=>{Rs||mn().catch(()=>{})}},[mn,Rs]);const Tr=(0,m.useCallback)(()=>{Zn.current()},[]);(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionChange))return e.onTestActionChange(Tr),()=>{e.onTestActionChange?.(null)}},[l,e.onTestActionChange,Tr]),(0,m.useEffect)(()=>{if(!(!l||!e.onTestActionStateChange))return e.onTestActionStateChange({disabled:Rs,pending:wt}),()=>{e.onTestActionStateChange?.({disabled:!0,pending:!1})}},[l,e.onTestActionStateChange,Rs,wt]),(0,m.useEffect)(()=>{if(e.onTestFeedbackChange)return e.onTestFeedbackChange({errorMessage:Zt??(Ft.error instanceof Error?Ft.error.message:Ft.error?"Environment test failed":null),result:Ft.data??null,login:jr&&f&&Ce?{companyId:f,adapterType:le,environmentId:Ce}:null}),()=>{e.onTestFeedbackChange?.({errorMessage:null,result:null,login:null})}},[e.onTestFeedbackChange,Zt,Ft.data,Ft.error,jr,f,le,Ce]);const Wr=a?dt.model??"":H("adapterConfig","model",String(oe.model??"")),ut=typeof Wr=="string"?Wr:"";async function rs(){if(f){Fe(!0),$t(null);try{const tt=await Lt.adapterModels(f,le,{refresh:!0,environmentId:it||null,provider:ns});x.setQueryData(fe,tt)}catch(tt){$t(tt instanceof Error?tt.message:"Failed to refresh adapter models.")}finally{Fe(!1)}}}r(rs,"handleRefreshModels");const Ls=le==="codex_local"?"modelReasoningEffort":le==="cursor"?"mode":le==="opencode_local"?"variant":le==="grok_local"?"reasoningEffort":le==="pi_local"?"thinking":"effort",Os=le==="codex_local"?iW(ut,"Auto").map(tt=>({id:tt.value,label:tt.label})):le==="cursor"?$rt:le==="opencode_local"?Lrt:le==="kimi_local"?Frt:le==="pi_local"?[{id:"",label:"Auto"},...["off","minimal","low","medium","high","xhigh"].map(tt=>({id:tt,label:tt}))]:le==="claude_local"||le==="grok_local"?[{id:"",label:"Auto"},...p5(le,ut).map(tt=>({id:tt,label:tt==="xhigh"?"X-High":tt[0].toUpperCase()+tt.slice(1)}))]:Ort,Us=a?dt.thinkingEffort:le==="codex_local"?H("adapterConfig","modelReasoningEffort",String(oe.modelReasoningEffort??oe.reasoningEffort??"")):le==="cursor"?H("adapterConfig","mode",String(oe.mode??"")):le==="opencode_local"?H("adapterConfig","variant",String(oe.variant??"")):H("adapterConfig",Ls,String(oe[Ls]??"")),Ps=le!=="gemini_local"&&le!=="cursor_cloud"&&le!=="paperclip_runner",fr=le==="codex_local"?a?!!dt.search:H("adapterConfig","search",!!oe.search):!1,xr=(0,m.useMemo)(()=>{if(a)return{heartbeat:{enabled:dt.heartbeatEnabled,intervalSec:dt.intervalSec}};const tt={...ie.heartbeat&&typeof ie.heartbeat=="object"?ie.heartbeat:{},...F.heartbeat};return{...ie,heartbeat:tt}},[a,F.heartbeat,ie,dt]),wr=uJ(xr.heartbeat),nr=uJ(wr.maxTurnContinuation),Fr=HLe(nr.enabled,!0),kr=cE(yJ(nr.maxAttempts,Brt),0,Rte),_t=cE(yJ(nr.delayMs,zrt*1e3)/1e3,0,mSe);function qs(tt){Q("heartbeat","maxTurnContinuation",{...nr,...tt})}r(qs,"updateMaxTurnContinuation");const hn=(0,t.jsx)(yy,{ref:b,onDirtyChange:se,hideDraftActions:!a&&e.hideInlineSave,value:a?dt.envBindings??YS:H("adapterConfig","env",oe.env??YS),secrets:j,userSecretDefinitions:N,onCreateSecret:r(async(tt,Dt)=>await q.mutateAsync({name:tt,value:Dt}),"onCreateSecret"),onChange:r(tt=>a?de({envBindings:tt??{},envVars:""}):Q("adapterConfig","env",tt),"onChange")},ee);return!a&&e.content==="secrets"?(0,t.jsxs)("div",{className:W("relative",i&&"space-y-6"),children:[ce&&!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:me,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:hn})]}),(0,t.jsxs)("div",{"data-config-section":"secrets",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"mb-3 text-sm font-medium",children:"Secret access"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Secret access"}),(0,t.jsxs)("div",{className:W(i?"space-y-3 rounded-lg border border-border p-4":"space-y-3 px-4 pb-3"),children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:wi.secretAccess}),(0,t.jsx)(jrt,{config:{...oe,...F.adapterConfig},secrets:j,onChange:te,onCreateSecret:r((tt,Dt)=>q.mutateAsync({name:tt,value:Dt}),"onCreateSecret"),proposals:S,onApproveProposal:C.requestApprove,onRejectProposal:C.requestReject}),C.dialogs]})]})]}):(0,t.jsxs)(Urt,{order:e.sectionOrder,className:W("relative",i&&"space-y-6"),children:[ce&&!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:me,disabled:!a&&e.isSaving,children:!a&&e.isSaving?"Saving...":"Save"})]})}),!a&&(0,t.jsxs)("div",{"data-config-section":"identity",className:W(!i&&"border-b border-border"),children:[i?(0,t.jsx)("h3",{className:"text-sm font-medium mb-3",children:e.sectionTitles?.identity??"Identity"}):(0,t.jsx)("div",{className:"px-4 py-2 text-xs font-medium text-muted-foreground",children:"Identity"}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[(0,t.jsx)(Ss,{label:"Name",hint:wi.name,children:(0,t.jsx)(za,{value:H("identity","name",e.agent.name),onCommit:r(tt=>Q("identity","name",tt),"onCommit"),immediate:!0,className:Jm,placeholder:"Agent name"})}),(0,t.jsx)(Ss,{label:"Title",hint:wi.title,children:(0,t.jsx)(za,{value:H("identity","title",e.agent.title??""),onCommit:r(tt=>Q("identity","title",tt||null),"onCommit"),immediate:!0,className:Jm,placeholder:"e.g. VP of Engineering"})}),(0,t.jsx)(Ss,{label:"Reports to",hint:wi.reportsTo,children:(0,t.jsx)(Pnt,{agents:ds,value:H("identity","reportsTo",e.agent.reportsTo??null),onChange:r(tt=>Q("identity","reportsTo",tt),"onChange"),excludeAgentIds:[e.agent.id],chooseLabel:"Choose manager…"})}),ye&&!e.hidePromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Prompt Template",hint:wi.promptTemplate,children:(0,t.jsx)(ud,{value:H("adapterConfig","promptTemplate",String(oe.promptTemplate??"")),onChange:r(tt=>Q("adapterConfig","promptTemplate",tt??""),"onChange"),placeholder:"You are agent {{ agent.name }}. Your role is {{ agent.role }}...",contentClassName:"min-h-(--sz-88px) text-sm font-mono",imageUploadHandler:r(async tt=>{const Dt=`agents/${e.agent.id}/prompt-template`;return(await U.mutateAsync({file:tt,namespace:Dt})).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."})]})]})]}),B?(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:z?(0,t.jsxs)("div",{className:W(Jm,"flex items-center text-muted-foreground"),children:[z.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."})})})]}):Je?(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:Jm,value:it,onChange:r(tt=>{const Dt=tt.target.value;if(a){de({defaultEnvironmentId:Dt});return}Q("identity","defaultEnvironmentId",Dt||null)},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",_e]}),Ee.map(tt=>(0,t.jsx)("option",{value:tt.id,children:Hv(tt)},tt.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:Tr,disabled:Rs,children:wt?`${ht}...`:ht})]}),(0,t.jsxs)("div",{className:W(i?"border border-border rounded-lg p-4 space-y-3":"px-4 pb-3 space-y-3"),children:[o&&(0,t.jsx)(Ss,{label:"Adapter type",hint:wi.adapterType,children:(0,t.jsx)(fSe,{value:le,disabledTypes:T,onChange:r(tt=>{if(a){const{adapterType:Dt,...xs}=tb,Gs={...xs,adapterType:tt};tt==="codex_local"?Gs.dangerouslyBypassSandbox=!0:tt==="gemini_local"?Gs.model="auto":tt==="kimi_local"?Gs.model="kimi-code/kimi-for-coding":tt==="cursor"?Gs.model="auto":tt==="opencode_local"?Gs.model="openai/gpt-5.2-codex":tt==="paperclip_runner"&&(Gs.model=Yk),de(Gs)}else K(Dt=>({...Dt,adapterType:tt,adapterConfig:{model:tt==="gemini_local"?"auto":tt==="kimi_local"?"kimi-code/kimi-for-coding":tt==="opencode_local"?"openai/gpt-5.2-codex":tt==="cursor"?"auto":tt==="paperclip_runner"?Ert(le,oe.model):"",effort:"",modelReasoningEffort:"",variant:"",mode:"",...tt==="codex_local"?{dangerouslyBypassApprovalsAndSandbox:!0}:tt==="paperclip_runner"?{...aNe(le,H("adapterConfig","model",oe.model))}:{}}}))},"onChange")})}),!a&&f&&(0,t.jsx)(Zke,{companyId:f,agentId:e.agent.id,agentName:e.agent.name,adapterType:le==="paperclip_runner"?H("adapterConfig","provider",oe.provider)==="codex"?"codex_local":H("adapterConfig","provider",oe.provider)==="opencode"?"opencode_local":H("adapterConfig","provider",oe.provider)==="acpx"&&H("adapterConfig","acpxAgent",oe.acpxAgent)==="grok"?"grok_local":H("adapterConfig","provider",oe.provider)==="acpx"&&H("adapterConfig","acpxAgent",oe.acpxAgent)==="claude"?"claude_local":le:le,routerAdapterType:le,value:cJ.safeParse(F.runtime.runtimeConfig?.aiConnection??ie.aiConnection).data,model:String(H("adapterConfig","model",oe.model)??""),environmentId:it||void 0,legacy:!0,onChange:r(tt=>Q("runtime","runtimeConfig",{...ie,aiConnection:tt}),"onChange")}),d&&!e.compactTestFeedback&&(Zt||Ft.error)&&(0,t.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:Zt??(Ft.error instanceof Error?Ft.error.message:"Environment test failed")}),d&&!e.compactTestFeedback&&Ft.data&&(0,t.jsx)(Yrt,{result:Ft.data}),d&&jr&&(0,t.jsx)(jW,{companyId:f,adapterType:le,environmentId:Ce,onStored:a?gt:bt,onApplyStored:a?Qe:mt,onAccountBinding:a?void 0:De},`${le}:${Ce}`),Ie&&(0,t.jsx)(Ss,{label:"Working directory (deprecated)",hint:wi.cwd,children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2.5 py-1.5",children:[(0,t.jsx)(Po,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)(za,{value:a?dt.cwd:H("adapterConfig","cwd",String(oe.cwd??"")),onCommit:r(tt=>a?de({cwd:tt}):Q("adapterConfig","cwd",tt||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,{})]})}),Hs("adapter"),ye&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(wW,{models:xt,value:ut,onChange:r(tt=>{const Dt=p5(le,tt),xs=["codex_local","claude_local","grok_local"].includes(le)&&!!Us&&!Dt.includes(String(Us));if(a){de({model:tt,...xs?{thinkingEffort:""}:{}});return}Q("adapterConfig","model",tt||void 0),xs&&(Q("adapterConfig",Ls,void 0),Q("adapterConfig","reasoningEffort",void 0))},"onChange"),open:tr,onOpenChange:Le,defaultLabel:le==="claude_local"?"Default (claude-opus-5)":void 0,allowDefault:le!=="opencode_local"&&le!=="pi_local"&&le!=="paperclip_runner",required:le==="opencode_local"||le==="pi_local",groupByProvider:le==="opencode_local"||le==="pi_local",preserveOrder:mW(le),creatable:!0,detectedModel:Ct,detectedModelCandidates:[],onDetectModel:le==="opencode_local"||le==="paperclip_runner"?void 0:async()=>(await Ts()).data?.model??null,onRefreshModels:Rrt(le)?rs:void 0,refreshingModels:js,detectModelLabel:"Detect model",emptyDetectHint:"No model detected. Select or enter one manually."}),(Et||Ue)&&(0,t.jsx)("p",{className:"text-xs text-destructive",children:Et??(Ue instanceof Error?Ue.message:"Failed to load adapter models.")}),le==="opencode_local"&&Nt&&Nt.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 ",Nt.name,"."]}),Ps&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Jrt,{value:Us,options:Os,onChange:r(tt=>a?de({thinkingEffort:tt}):Q("adapterConfig",Ls,tt||void 0),"onChange"),open:et,onOpenChange:vt}),le==="codex_local"&&fr&&Us==="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 oe.bootstrapPromptTemplate=="string"&&oe.bootstrapPromptTemplate&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ss,{label:"Bootstrap prompt (legacy)",hint:wi.bootstrapPrompt,children:(0,t.jsx)(ud,{value:H("adapterConfig","bootstrapPromptTemplate",String(oe.bootstrapPromptTemplate??"")),onChange:r(tt=>Q("adapterConfig","bootstrapPromptTemplate",tt||void 0),"onChange"),placeholder:"Optional initial setup prompt for the first run",contentClassName:"min-h-(--sz-44px) text-sm font-mono",imageUploadHandler:r(async tt=>{const Dt=`agents/${e.agent.id}/bootstrap-prompt`;return(await U.mutateAsync({file:tt,namespace:Dt})).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."})]}),Hs("configuration"),(ye||le==="process"||ws?.fields.some(tt=>Aq(tt.key)==="advanced"))&&(0,t.jsx)(sE,{title:"Advanced",open:Pt,onToggle:r(()=>os(!Pt),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[ye&&(0,t.jsxs)(t.Fragment,{children:[" ",!D&&(0,t.jsx)(Ss,{label:"Command",hint:wi.localCommand,children:(0,t.jsx)(za,{value:a?dt.command:H("adapterConfig",Wt,String(oe.command??"")),onCommit:r(tt=>a?de({command:tt}):Q("adapterConfig",Wt,tt||null),"onCommit"),immediate:!0,className:Jm,placeholder:{claude_local:"claude",codex_local:"codex",gemini_local:"gemini",kimi_local:"kimi",pi_local:"pi",cursor:"agent",opencode_local:"opencode"}[le]??le.replace(/_local$/,"")})}),(0,t.jsx)(Ss,{label:"Extra args (comma-separated)",hint:wi.extraArgs,children:(0,t.jsx)(za,{value:a?dt.extraArgs:H("adapterConfig","extraArgs",Drt(oe.extraArgs)),onCommit:r(tt=>a?de({extraArgs:tt}):Q("adapterConfig","extraArgs",tt?.trim()?Mrt(tt):null),"onCommit"),className:Jm,placeholder:"e.g. --verbose, --foo=bar"})})]}),Hs("advanced")]})})]})]}),e.environmentVariablesPlacement!=="secrets"&&(ye||ws?.fields.some(tt=>Aq(tt.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:ye?hn:Hs("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)(RC,{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)(RC,{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)(Hee,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:dt.heartbeatEnabled,onCheckedChange:r(tt=>de({heartbeatEnabled:tt}),"onCheckedChange"),number:dt.intervalSec,onNumberChange:r(tt=>de({intervalSec:tt}),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:dt.heartbeatEnabled}),(0,t.jsx)(sE,{title:"Advanced Run Policy",open:xe,onToggle:r(()=>Gt(!xe),"onToggle"),children:(0,t.jsx)("div",{className:"space-y-3",children:Hs("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)(RC,{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)(RC,{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)(Hee,{label:"Heartbeat on interval",hint:wi.heartbeatInterval,checked:H("heartbeat","enabled",ge.enabled===!0),onCheckedChange:r(tt=>Q("heartbeat","enabled",tt),"onCheckedChange"),number:H("heartbeat","intervalSec",Number(ge.intervalSec??300)),onNumberChange:r(tt=>Q("heartbeat","intervalSec",tt),"onNumberChange"),numberLabel:"sec",numberPrefix:"Run heartbeat every",numberHint:wi.intervalSec,showNumber:H("heartbeat","enabled",ge.enabled===!0)})}),(0,t.jsx)(sE,{title:"Advanced Run Policy",bordered:i,open:xe,onToggle:r(()=>Gt(!xe),"onToggle"),children:(0,t.jsxs)("div",{className:"space-y-3",children:[Hs("runPolicy"),ye&&(0,t.jsx)(t.Fragment,{children:!a&&(0,t.jsxs)(t.Fragment,{children:[!ws?.fields.some(tt=>tt.key==="timeoutSec")&&(0,t.jsx)(Ss,{label:"Timeout (sec)",hint:wi.timeoutSec,children:(0,t.jsx)(Sc,{value:H("adapterConfig","timeoutSec",Number(oe.timeoutSec??0)),onCommit:r(tt=>Q("adapterConfig","timeoutSec",tt),"onCommit"),immediate:!0,className:Jm})}),!ws?.fields.some(tt=>tt.key==="graceSec")&&(0,t.jsx)(Ss,{label:"Interrupt grace period (sec)",hint:wi.graceSec,children:(0,t.jsx)(Sc,{value:H("adapterConfig","graceSec",Number(oe.graceSec??15)),onCommit:r(tt=>Q("adapterConfig","graceSec",tt),"onCommit"),immediate:!0,className:Jm})})]})}),(0,t.jsx)(Cd,{label:"Wake on demand",hint:wi.wakeOnDemand,checked:H("heartbeat","wakeOnDemand",ge.wakeOnDemand!==!1),onChange:r(tt=>Q("heartbeat","wakeOnDemand",tt),"onChange")}),(0,t.jsx)(Ss,{label:"Cooldown (sec)",hint:wi.cooldownSec,children:(0,t.jsx)(Sc,{value:H("heartbeat","cooldownSec",Number(ge.cooldownSec??10)),onCommit:r(tt=>Q("heartbeat","cooldownSec",tt),"onCommit"),immediate:!0,className:Jm})}),(0,t.jsx)(Ss,{label:"Max concurrent runs",hint:wi.maxConcurrentRuns,children:(0,t.jsx)(Sc,{value:H("heartbeat","maxConcurrentRuns",Number(ge.maxConcurrentRuns??20)),onCommit:r(tt=>Q("heartbeat","maxConcurrentRuns",tt),"onCommit"),immediate:!0,className:Jm})}),(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:wi.maxTurnContinuationEnabled,checked:Fr,onChange:r(tt=>qs({enabled:tt}),"onChange")}),Fr?(0,t.jsxs)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[(0,t.jsx)(Ss,{label:"Continuation attempts",hint:wi.maxTurnContinuationMaxAttempts,children:(0,t.jsx)(Sc,{value:kr,onCommit:r(tt=>qs({maxAttempts:cE(tt,0,Rte)}),"onCommit"),immediate:!0,className:Jm})}),(0,t.jsx)(Ss,{label:"Continuation delay (sec)",hint:wi.maxTurnContinuationDelaySec,children:(0,t.jsx)(Sc,{value:_t,onCommit:r(tt=>qs({delayMs:qrt(tt)}),"onCommit"),immediate:!0,className:Jm})})]}):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)(zv,{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)(zv,{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:H("debug","providerTrace",be.providerTrace)==="raw",onChange:r(tt=>Q("debug","providerTrace",tt?"raw":void 0),"onChange")}),H("debug","providerTrace",be.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)(zv,{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)(mNe,{state:wt?"running":Zt||Ft.error?"fail":an?.status??"idle",result:an??null,error:Zt??(Ft.error instanceof Error?Ft.error.message:null),onTest:Tr,disabled:Rs})]})}r(hSe,"AgentConfigForm");var Hq=new Set(["authenticated","failed","timed_out","cancelled"]),Gq=2e3;function Qq({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 ha(e),a(!0)}catch{a(!1)}i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(!1),1500)},"onClick"),children:n?(0,t.jsx)(vs,{className:"size-3"}):(0,t.jsx)(Ar,{className:"size-3"})})}r(Qq,"AdapterLoginCopyButton");function Krt({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)(vs,{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)(Ds,{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(Krt,"AdapterLoginTerminalState");var Wrt={claude_local:"Anthropic",codex_local:"OpenAI"};function pSe(e){const s=Wrt[e];return s?`Sign in to ${s}`:"Sign in to the environment"}r(pSe,"adapterLoginTitle");function jW(e){return Ky()(e.adapterType).login?.panelMode==="submitted_browser_code"?(0,t.jsx)(Qrt,{...e}):(0,t.jsx)(Vrt,{...e})}r(jW,"AdapterLoginPanel");var $$=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 Vrt({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(()=>Lt.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(()=>Lt.cancelAdapterAuthLogin(e,s,u),"mutationFn"),onSuccess:k,onError:r(re=>{f(re instanceof Error?re.message:"Could not cancel the login.")},"onError")}),C=X({queryKey:["adapter-login-active-session",e,s],queryFn:r(async()=>{try{const re=await Lt.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 $$(re.sessionId);return re}catch(re){if(re instanceof un&&re.status===404)return null;throw re}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[I,T]=(0,m.useState)(!1),R=X({queryKey:["adapter-login-status",e,s,u],queryFn:r(()=>Lt.getAdapterAuthLoginStatus(e,s,u),"queryFn"),enabled:!!u&&!I,retry:r((re,ce)=>ce instanceof un&&ce.status===404?!1:re<3,"retry"),refetchInterval:r(re=>{const ce=re.state.data?.status;return ce&&Hq.has(ce)?!1:Gq},"refetchInterval")});(0,m.useEffect)(()=>{const re=R.data?.prompt??null;re&&b(re)},[R.data]);const A=R.data??w.data??null,D=A?.status??null,M=x,$=D?Hq.has(D):!1,E=!!u&&!$,B=w.isPending||E||v==="saving",z=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(z.current||!C.isFetched)return;z.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=R.error;if(!(re instanceof un&&re.status===404)||!N.current||I)return;T(!0);const ce=u;(async()=>(ce&&await Lt.cancelAdapterAuthLogin(e,s,ce).catch(()=>{}),T(!1),k()))()},[R.error,I,u,e,s,k]);const q=(0,m.useRef)(!1),U=je({mutationFn:r(async()=>{const re=C.error;re instanceof $$&&await Lt.cancelAdapterAuthLogin(e,s,re.sessionId)},"mutationFn"),onSuccess:r(async()=>{q.current=!1,z.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")}),F=(0,m.useRef)(w.mutate);F.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&&F.current())}},[a,C.isSuccess,C.isError,C.data,C.error]);const K=(0,m.useRef)(!1),G=(0,m.useRef)(i);G.current=i,(0,m.useEffect)(()=>{D!=="authenticated"||K.current||(K.current=!0,G.current?.(u??void 0))},[D]);const se=(0,m.useRef)(null),ee=(0,m.useRef)(o);ee.current=o;const ne=R.data?.codexAccountBinding??null,he=(0,m.useCallback)(async re=>{const ce=ee.current;if(ce){j("saving");try{await ce(re),j("bound")}catch{j("failed")}}},[]);(0,m.useEffect)(()=>{D!=="authenticated"||!u||se.current!==u&&(!ne||!ne.companyIdentityDiffers||!ee.current||(se.current=u,he(ne)))},[D,u,ne,he]);const Z=(0,m.useRef)(d);if(Z.current=d,(0,m.useEffect)(()=>{Z.current?.(M?.url??null)},[M]),l==="onboarding"){const re=$&&D&&D!=="authenticated";return(0,t.jsx)(wNe,{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 $$&&(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)(zZe,{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:pSe(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:B,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)(nt,{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)(Qq,{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)(Qq,{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)(qn,{className:"size-3"})})})]})]})]}),$&&D&&(0,t.jsx)(Krt,{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)(nt,{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)(vs,{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)(Ds,{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&&he(ne)},"onClick"),children:"Retry"})]})]})]})}r(Vrt,"DisplayedCodeLoginPanel");var Hrt=new Set(["failed","timed_out","cancelled"]),Ete="The login did not finish. Start the login again.",Grt=9e5,Pte="The login timed out. Start the login again.";function Qrt({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,T]=(0,m.useState)(null),[R,A]=(0,m.useState)(!1),[D,M]=(0,m.useState)(!1),[$,E]=(0,m.useState)(!1),[B,z]=(0,m.useState)(!1),q=(0,m.useRef)(!1),[U,F]=(0,m.useState)(!1),K=(0,m.useRef)(!1),G=r(()=>{v(null),N(null),k(!1),C(""),T(null),A(!1),M(!1),z(!1),E(!1),q.current=!1},"resetLocalState"),se=X({queryKey:["claude-oauth-token-status",e],queryFn:r(async()=>{try{return await Lt.getClaudeOAuthTokenStatus(e)}catch(Ze){if(Ze instanceof un&&Ze.status===404)return null;throw Ze}},"queryFn"),retry:r((Ze,Pe)=>Pe instanceof un&&Pe.status===404?!1:Ze<2,"retry")}).data??null,ee=je({mutationFn:r(()=>Lt.startClaudeSetupTokenLogin(e,{environmentId:n,aiConnection:h,...se&&!h?{overwrite:{expectedSecretId:se.secretId,expectedLatestVersion:se.latestVersion}}:{}}),"mutationFn"),onSuccess:r(Ze=>{K.current=!1,G(),x(Ze.sessionId)},"onSuccess"),onError:r(Ze=>{v(Ze instanceof Error?Ze.message:"Could not start the login.")},"onError")}),ne=r(()=>{K.current=!1,x(null),G()},"clearActiveSession"),he=je({mutationFn:r(()=>Lt.cancelClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(()=>{ne()},"onSuccess"),onError:r(Ze=>{if(Ze instanceof un&&Ze.status===404){ne();return}v(Ze instanceof Error?Ze.message:"Could not cancel the login.")},"onError")}),Z=(0,m.useCallback)(Ze=>{Lt.cancelClaudeSetupTokenLogin(e,Ze).catch(()=>{})},[e]),re=X({queryKey:["claude-setup-token-active-session",e],queryFn:r(async()=>{try{const Ze=await Lt.getActiveClaudeSetupTokenLoginSession(e);if(!Ze)return null;if(h&&Ze.environmentId!==n||!!Ze.aiConnection!=!!h||h&&(Ze.aiConnection?.provider!==h.provider||Ze.aiConnection?.method!==h.method||Ze.aiConnection?.connectionId!==h.connectionId||Ze.aiConnection?.ownership!==h.ownership||Ze.aiConnection?.allAgents!==h.allAgents||JSON.stringify(Ze.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 Ze}catch(Ze){if(Ze instanceof un&&Ze.status===404)return null;throw Ze}},"queryFn"),retry:!1,gcTime:0,staleTime:0}),[ce,H]=(0,m.useState)(!1),Q=!!f&&!D&&!B&&!ce,Y=X({queryKey:["claude-setup-token-status",e,f],queryFn:r(()=>Lt.getClaudeSetupTokenLoginStatus(e,f),"queryFn"),enabled:Q,retry:r((Ze,Pe)=>Pe instanceof un&&Pe.status===404?!1:Ze<3,"retry"),refetchInterval:r(Ze=>{if(D||B)return!1;const Pe=Ze.state.data?.status;return Pe&&Hq.has(Pe)?!1:Gq},"refetchInterval")});(0,m.useEffect)(()=>{const Ze=Y.error;if(Ze instanceof un&&Ze.status===404){if(K.current){if(ce)return;H(!0);const Pe=f;(async()=>(Pe&&await Lt.cancelClaudeSetupTokenLogin(e,Pe).catch(()=>{}),H(!1),ne()))();return}z(!0)}},[Y.error,ce,f,e]);const te=(0,m.useRef)(!1);(0,m.useEffect)(()=>{if(te.current||!re.isFetched)return;te.current=!0;const Ze=re.data;Ze&&(K.current=!0,G(),x(Ze.sessionId),Ze.prompt&&(N(Ze.prompt.authorizationUrl),Ze.prompt.transportAdvisory&&k(!0)))},[re.isFetched,re.data]);const ae=X({queryKey:["claude-setup-token-prompt",e,f],enabled:Q&&!j,queryFn:r(async()=>{try{return await Lt.getClaudeSetupTokenLoginPrompt(e,f)}catch(Ze){if(Ze instanceof un&&Ze.status===404)return null;throw Ze}},"queryFn"),refetchInterval:r(Ze=>D||Ze.state.data?.authorizationUrl?!1:Gq,"refetchInterval")});(0,m.useEffect)(()=>{const Ze=ae.data?.authorizationUrl??null;Ze&&N(Ze),ae.data?.transportAdvisory&&k(!0)},[ae.data]);const me=je({mutationFn:r(Ze=>Lt.submitClaudeSetupTokenBrowserCode(e,f,Ze),"mutationFn"),onError:r(Ze=>{v(Ze instanceof Error?Ze.message:"Could not submit the browser code.")},"onError")}),oe=je({mutationFn:r(()=>Lt.completeClaudeSetupTokenLogin(e,f),"mutationFn"),onSuccess:r(Ze=>{T(Ze.storedSessionId),a?.(Ze.storedSessionId)},"onSuccess"),onError:r(()=>{A(!0)},"onError")}),ie=Y.data?.status??ee.data?.status??null,ge=Y.data?.expiresAt??ee.data?.expiresAt??null,be=(0,m.useRef)(oe.mutate);be.current=oe.mutate,(0,m.useEffect)(()=>{ie==="authenticated"&&!q.current&&(q.current=!0,be.current())},[ie]);const le=I!==null,ue=R||B||!!(ie&&Hrt.has(ie)),Se=ie==="authenticated"&&!le&&!R,ye=!!f&&!le&&!ue&&!D,Ie=ee.isPending||ye;(0,m.useEffect)(()=>{if(!ye)return;const Ze=ge!==null?new Date(ge).getTime():NaN,Pe=Number.isFinite(Ze)?Math.max(0,Ze-Date.now()):Grt,Ce=setTimeout(()=>{f&&Z(f),M(!0)},Pe);return()=>clearTimeout(Ce)},[ye,ge,f,Z]);const Ke=S.trim(),rt=ye&&!!j&&!Se&&HDe(Ke)&&!me.isPending&&!$,dt=(0,m.useRef)(c);dt.current=c;const de=(0,m.useRef)(d);de.current=d;const ze=r(()=>{rt&&(v(null),me.mutate(Ke),E(!0),dt.current?.(),u!=="onboarding"&&C(""))},"handleSubmit"),gt=(0,m.useRef)(!1),bt=(0,m.useRef)(ee.mutate);bt.current=ee.mutate,(0,m.useEffect)(()=>{if(!(!o||gt.current)){if(re.isError){gt.current=!0,v(re.error instanceof Error?re.error.message:"Could not check for an active login.");return}re.isSuccess&&(gt.current=!0,!re.data&&bt.current())}},[o,re.isSuccess,re.isError,re.data,re.error]);const De=(0,m.useRef)(ze);De.current=ze;const Qe=u==="onboarding",mt=(0,m.useRef)(!1);(0,m.useEffect)(()=>{!Qe||!mt.current||(mt.current=!1,rt&&De.current())},[Qe,rt,S]);const Ye=(0,m.useRef)(!1),it=(0,m.useRef)(l);it.current=l,(0,m.useEffect)(()=>{!le||Ye.current||(Ye.current=!0,it.current?.(f??void 0))},[le]),(0,m.useEffect)(()=>{$&&(!b&&!ue&&!D||(E(!1),de.current?.()))},[$,b,ue,D]);const Nt=(0,m.useRef)(p);if(Nt.current=p,(0,m.useEffect)(()=>{Nt.current?.(j)},[j]),u==="onboarding"){const Ze=ue||D;return(0,t.jsxs)(wNe,{loading:!j&&!b&&!Ze,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)(Ds,{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}):Ze?(0,t.jsx)("p",{role:"alert",className:"pl-2 text-xs text-destructive",children:D&&!ue?Pte:Ete}):(0,t.jsx)(GM,{value:S,onChange:C,onSubmit:ze,onPaste:r(()=>{mt.current=!0},"onPaste"),masked:!0,disabled:me.isPending||Se||$})]})}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:pSe(s)}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5",children:[ye&&(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:he.isPending,onClick:r(()=>he.mutate(),"onClick"),children:"Cancel"}),i&&se&&!ye&&!le&&!U&&(0,t.jsx)(L,{type:"button",variant:"default",size:"sm",className:"h-7 px-2.5 text-xs",onClick:r(()=>{i(),F(!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(()=>ee.mutate(),"onClick"),children:se&&!ye&&!le?"Sign in to replace":"Sign in"})]})]}),se&&!ye&&!le&&!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)(vs,{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:[ye&&!j&&!Se&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(nt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Preparing..."})]}),ye&&j&&!Se&&(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)(Ds,{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)(Qq,{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)(qn,{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(Ze=>C(Ze.target.value),"onChange"),onKeyDown:r(Ze=>{Ze.key==="Enter"&&(Ze.preventDefault(),ze())},"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:!rt,onClick:ze,children:"Submit"})]})]})]}),Se&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-muted-foreground",children:[(0,t.jsx)(nt,{className:"size-3 animate-spin shrink-0"}),(0,t.jsx)("span",{children:"Completing the login…"})]}),le&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-(length:--text-micro) text-foreground",children:[(0,t.jsx)(vs,{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)(Ds,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Ete})]}),D&&!ue&&!le&&(0,t.jsxs)("div",{className:"flex items-start gap-2 text-(length:--text-micro) text-destructive",children:[(0,t.jsx)(Ds,{className:"size-3 shrink-0"}),(0,t.jsx)("span",{children:Pte})]})]})]})}r(Qrt,"SubmittedBrowserCodeLoginPanel");function Yrt({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(Yrt,"AdapterEnvironmentResult$1");function fSe({value:e,onChange:s,disabledTypes:n}){const[a,i]=(0,m.useState)(!1),o=Nh(e),l=(0,m.useMemo)(()=>dSe(c=>Jk[c]??qf(c)).filter(c=>!n.has(c.value)),[n]);return(0,t.jsxs)(yr,{open:a,onOpenChange:i,children:[(0,t.jsx)(Ir,{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)(Tq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{className:"truncate",children:Jk[e]??qf(e)}),o.experimental&&(0,t.jsx)(Mte,{})]}),(0,t.jsx)(nn,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,t.jsx)(lr,{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)(Tq,{className:"h-3.5 w-3.5"}):null,(0,t.jsx)("span",{children:c.label}),c.experimental&&(0,t.jsx)(Mte,{})]}),c.comingSoon&&(0,t.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground",children:"Coming soon"})]},c.value))})]})}r(fSe,"AdapterTypeDropdown");function Mte(){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(Mte,"ExperimentalBadge$1");function wW({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),T=w.trim(),R=!!(u&&T&&!e.some(E=>E.id.toLowerCase()===T.toLowerCase())),A=(0,m.useMemo)(()=>{const E=new Set;h&&E.add(h);for(const B of p??[])B&&E.add(B);return E},[h,p]),D=(0,m.useMemo)(()=>e.filter(E=>{if(A.has(E.id))return!1;if(!w.trim())return!0;const B=w.toLowerCase(),z=Eq(E.id)??"";return E.id.toLowerCase().includes(B)||E.label.toLowerCase().includes(B)||z.toLowerCase().includes(B)}),[e,w,A]),M=(0,m.useMemo)(()=>{if(!c)return[{provider:"models",entries:d?D:[...D].sort((B,z)=>B.id.localeCompare(z.id))}];const E=new Map;for(const B of D){const z=Eq(B.id)??"other",q=E.get(z)??[];q.push(B),E.set(z,q)}return Array.from(E.entries()).sort(([B],[z])=>B.localeCompare(z)).map(([B,z])=>({provider:B,entries:[...z].sort((q,U)=>q.id.localeCompare(U.id))}))},[D,c,d]);async function $(){if(f){C(!0);try{const E=await f();E&&(n(E),i(!1),k(""))}finally{C(!1)}}}return r($,"handleDetectModel"),(0,t.jsx)(Ss,{label:"Model",hint:wi.model,children:(0,t.jsxs)(yr,{open:a,onOpenChange:r(E=>{i(E),E||k("")},"onOpenChange"),children:[(0,t.jsx)(Ir,{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)(lr,{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(()=>{$()},"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)(lt,{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)(lt,{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 B=e.find(z=>z.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:B?.label??E}),(0,t.jsx)(lt,{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"}),R&&(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(T),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:T})]}),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(B=>(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",B.id===s&&"bg-accent"),onClick:r(()=>{n(B.id),i(!1)},"onClick"),children:(0,t.jsx)("span",{className:"block w-full text-left truncate",title:B.id,children:c?WZe(B.id):B.label})},B.id))]},E.provider)),D.length===0&&!R&&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(wW,"ModelDropdown");function Jrt({value:e,options:s,onChange:n,open:a,onOpenChange:i}){const o=s.find(l=>l.id===e)??s[0];return(0,t.jsx)(Ss,{label:"Thinking effort",hint:wi.thinkingEffort,children:(0,t.jsxs)(yr,{open:a,onOpenChange:i,children:[(0,t.jsx)(Ir,{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)(lr,{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(Jrt,"ThinkingEffortDropdown");function xSe(e){const s=`paperclip.agent-appearance.${e}`;function n(){try{const l=dpe.safeParse(JSON.parse(sessionStorage.getItem(s)??"null"));if(l.success)return l.data}catch{}const o=$R();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(xSe,"useAgentAppearanceDraft");var JS=null,L2=new Set,XS={subscribe(e){return L2.add(e),()=>{L2.delete(e)}},getSnapshot(){return JS},acquire(e){if(JS)return!1;JS=e;for(const s of L2)s();return!0},release(e){if(JS===e){JS=null;for(const s of L2)s()}}};function T_({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)(()=>kN(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)(XS.subscribe,XS.getSnapshot,()=>null),[k,S]=(0,m.useState)(!1),[C,I]=(0,m.useState)(!0),[T,R]=(0,m.useState)(!1),[A,D]=(0,m.useState)(!1),M=k&&!C&&!T&&o==="auto"&&a!=="rest";return(0,m.useEffect)(()=>{if(typeof matchMedia!="function"||typeof IntersectionObserver!="function")return;const $=matchMedia("(prefers-reduced-motion: reduce)"),E=r(()=>I($.matches),"change");E(),$.addEventListener("change",E);const B=new IntersectionObserver(z=>S(z[0]?.isIntersecting??!1));return b.current&&B.observe(b.current),()=>{B.disconnect(),$.removeEventListener("change",E)}},[]),(0,m.useEffect)(()=>{M&&w===null&&XS.acquire(N.current),M||XS.release(N.current)},[M,w]),(0,m.useEffect)(()=>()=>XS.release(N.current),[]),(0,m.useEffect)(()=>{if(!M||w!==N.current)return;let $=!1;return D(!1),Promise.all([Wc(()=>import("./runtime-IAg0vdY9.js"),__vite__mapDeps([0,1])),Wc(()=>import("./definition-CK1a00WC.js"),__vite__mapDeps([2,3,1]))]).then(([E,B])=>{$||!v.current||(j.current=E.createCharacter(v.current,B.characterDefinition(x,i),{animation:B.animationId(a),trackingRegion:l?.current??b.current??void 0,followCursor:d,followRotation:u,trackingScope:c,displaySize:n,onError:r(()=>R(!0),"onError")}),D(!0))}).catch(()=>{$||R(!0)}),()=>{$=!0,j.current?.destroy(),j.current=null,D(!1)}},[M,w,l,c,n,d,u]),(0,m.useEffect)(()=>{j.current&&Wc(()=>import("./definition-CK1a00WC.js").then($=>{j.current?.setDefinition($.characterDefinition(x,i)),j.current?.setAnimation($.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",HOe[n],h),children:[(0,t.jsx)(_r,{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(T_,"AgentCharacter");var Xrt=new Set(["claude_local","codex_local","opencode_local","grok_local"]);function gSe(e,{cloud:s,nativeRunnerEnabled:n}){return e==="paperclip_runner"?n:s?Xrt.has(e):!0}r(gSe,"isNewAgentAdapterAllowed");var Zrt={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=Nh(e).icon,a=Zrt[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 eat(){const{selectedCompanyId:e}=gs(),{appearance:s}=xSe(`${e}:new-agent`);return(0,t.jsx)(T_,{appearance:s,state:"sleepy",muted:!0,size:256,className:"size-48",trackingScope:"page"})}r(eat,"AgentBasicsCharacter");function bSe({open:e,onClose:s,onContinue:n,initialAdapter:a="",onInvite:i}){const o=(0,m.useId)(),l=!!Ac(),c=X({queryKey:P.instance.experimentalSettings,queryFn:Or.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}=X({queryKey:P.adapters.all,queryFn:ch.list,enabled:e}),k=(j??[]).filter(C=>C.loaded&&!C.disabled&&gSe(C.type,{cloud:l,nativeRunnerEnabled:c.data?.enableNativeRunner===!0})&&!["process","http"].includes(C.type)&&!Nh(C.type).comingSoon),S=k.some(C=>C.type===h);return(0,t.jsx)(Vs,{open:e,onOpenChange:r(C=>{C||s()},"onOpenChange"),children:(0,t.jsxs)(Qs,{className:W("flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 sm:max-w-(--sz-640px)",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)(Pn,{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)(eat,{}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Js,{className:"text-3xl font-semibold tracking-tight",children:b==="name"?"Meet your next agent":"Choose an adapter"}),(0,t.jsx)(yn,{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)(pt,{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=Nh(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)(vs,{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)(gl,{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)(el,{className:"size-4"})]})]})]})]})})}r(bSe,"AgentBasicsDialog");var tat={subscription:"Subscription",api:"API"};function sat({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)(eS,{initial:!1,mode:"sync",children:(0,t.jsx)(fl.span,{className:"absolute inset-0 flex items-center justify-center whitespace-nowrap",initial:{opacity:0,y:Yee},animate:{opacity:1,y:0,transition:NZe},exit:{opacity:0,y:Yee,transition:SZe},children:tat[e]},e)})})}r(sat,"CredentialTag");function nat({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)(sat,{mode:s})]})}r(nat,"ModelSourceTile");function vSe({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)(eS,{initial:!1,mode:"popLayout",children:u.map(h=>(0,t.jsx)(fl.div,{layout:!0,transition:vNe,exit:{opacity:0,transition:DZe},className:W("flex min-w-0",o?"w-(--sz-source-tile-two-up)":"flex-1"),children:(0,t.jsx)(nat,{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(vSe,"ModelSourceTiles");var O$={subscription:"Use API key instead",api:"Use subscription instead"},rat={subscription:"api",api:"subscription"};function ySe({mode:e,onChange:s}){return(0,t.jsxs)("button",{type:"button",onClick:r(()=>s(rat[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(O$).map(n=>(0,t.jsx)("span",{"aria-hidden":!0,className:"invisible col-start-1 row-start-1 whitespace-nowrap",children:O$[n]},n)),(0,t.jsx)(eS,{initial:!1,mode:"sync",children:(0,t.jsx)(fl.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:dW},exit:{opacity:0,transition:CZe},children:O$[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)(gl,{className:"mr-1 size-3.5"}),"Back"]}):(0,t.jsx)("span",{}),(0,t.jsx)(fl.div,{layout:!0,transition:AZe,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)(fl.span,{className:"flex items-center whitespace-nowrap",initial:{opacity:0},animate:{opacity:1},transition:TZe,children:[d==="spinner"?(0,t.jsx)(nt,{className:"mr-1 size-4 animate-spin"}):null,c,d==="arrow"?(0,t.jsx)(el,{className:"ml-1 size-3.5"}):null]},`${c}:${d}`)})})]})}r(jSe,"FooterNav");function wSe({companyId:e,adapterType:s,environmentId:n,canLogin:a,localEnvironment:i=!1,onConnected:o,onBack:l,testConnection:c,testError:d,managedAccount:u}){const h=X({queryKey:P.health,queryFn:su.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"),[T,R]=(0,m.useState)(""),[A,D]=(0,m.useState)(!1),[M,$]=(0,m.useState)(null),[E,B]=(0,m.useState)(null),z=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",F=Yke(e,q),K=u?{...F,options:[],subscriptions:[],loading:!1}:F,[G,se]=(0,m.useState)(null),ee=K.subscriptions.length?K.subscriptions.find(ge=>ge.id===(G??K.subscriptions[0]?.id)):void 0,[ne,he]=(0,m.useState)(null),Z=K.options.find(ge=>ge.id===(ne??K.options[0]?.id)),re=u?{...K.storedLogin,data:void 0,isPending:!1,isError:!1}:K.storedLogin,ce=(0,m.useRef)(null),H=b??(K.subscriptions.length>0||s==="claude_local"&&!ee&&re.data?"subscription":K.options.length?"api":"subscription"),Q=H==="api"?"api_key":"subscription",Y=u?.intent.connectionId&&(u.fixedMethod!==!1||u.initialMethod===Q),te=u?{...u.intent,connectionId:Y?u.intent.connectionId:void 0,name:Y?u.intent.name:u.nameForMethod?.(Q)??u.intent.name}:void 0,ae=pwe(e,te??{provider:U,method:"subscription",name:`My ${z} subscription`,ownership:"personal",agentIds:[],allAgents:!0},p&&H==="subscription"&&!ee&&!re.data,{allowHostClaude:h.data?.deploymentMode==="local_trusted"}),me=X({queryKey:P.agents.authSignal(e,s,n),queryFn:r(()=>Lt.getAdapterAuthSignal(e,s,n??void 0),"queryFn"),retry:!1,enabled:!u});async function oe(){if(A||u?.disabled)return;const ge=++f.current;D(!0),$(null);try{if(u&&te){if(H==="subscription"&&!p)return;const ue=ce.current??await(H==="api"?Kc.create(e,{...te,method:"api_key",apiKey:T.trim()}):ae.connect(te));ce.current=ue,R(""),ge===f.current&&u.onComplete({...ue,method:H==="api"?"api_key":"subscription"});return}let be=H==="api"?Z?Z.aiConnection?{env:{},aiConnection:Z.aiConnection}:{env:{[q]:Z.binding}}:E??{env:{},credentials:{[q]:T.trim()}}:{...ee?.aiConnection?{aiConnection:ee.aiConnection}:{},env:ee?.binding?{CODEX_HOME:ee.binding}:{},...s==="claude_local"&&!ee&&re.data?{env:Bw(),applyStoredClaudeLogin:!0}:{}};if(H==="subscription"&&p&&!ee&&!re.data&&(ce.current??=await ae.connect(),be={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}}),be.credentials&&(await Kc.create(e,{provider:U,method:"api_key",name:`My ${z} API`,ownership:"personal",apiKey:be.credentials[q],agentIds:[],allAgents:!0}),be={env:{},aiConnection:{provider:U,method:"api_key",mode:"responsible_user"}}),ge!==f.current)return;H==="api"&&(R(""),Z||B(be));const le=await c(be);if(ge!==f.current)return;le?o(be):$("The provider did not respond. Check the connection and try again.")}catch(be){if(ge!==f.current)return;u&&R(""),$(be instanceof Error?be.message:"Could not connect to the provider.")}finally{ge===f.current&&D(!1)}}r(oe,"connect");const ie=H==="subscription"&&a&&n&&!ee&&!K.loading&&!re.data&&(!!u||me.data?.status!=="present"||G==="");return(0,t.jsxs)("div",{className:"min-w-0 max-w-full",children:[(0,t.jsx)(vSe,{label:"Connect your model provider",sources:[{id:s,label:z,icon:(0,t.jsx)(kW,{type:s})}],mode:H,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:H,onChange:r(ge=>{x(),N(j),ce.current=null,v(ge),R(""),B(null),$(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","."]}),H==="subscription"&&K.subscriptions.length>0&&(0,t.jsx)(dk,{options:K.subscriptions,value:ee?.id??"",onChange:se,loading:!1,error:!1,kind:"subscription",disabled:A}),(0,t.jsx)(fl.div,{initial:!1,animate:{height:j?"auto":0,opacity:j?1:0},transition:{height:_d,opacity:VM},className:"overflow-hidden",children:j&&(0,t.jsx)("div",{className:"pt-5",children:H==="api"?(0,t.jsxs)(HM,{instruction:K.options.length?"Choose a saved API key or enter a new one":`Provide your ${z} API key to connect`,children:[(0,t.jsx)(dk,{...K,value:Z?.id??"",disabled:A,onChange:r(ge=>{he(ge),R(""),B(null),$(null)},"onChange")}),!Z&&(0,t.jsx)(GM,{label:"API key",masked:!0,autoFocus:!0,value:T,placeholder:E?"Key entered. Retry the connection.":"Enter API key here",onChange:r(ge=>{he(""),R(ge),B(null)},"onChange"),onSubmit:r(()=>{oe()},"onSubmit"),disabled:A})]}):ie?(0,t.jsx)(jW,{companyId:e,adapterType:s,environmentId:n,chrome:"onboarding",aiConnection:te??{provider:U,method:"subscription",name:`My ${z} subscription`,ownership:"personal",agentIds:[],allAgents:!0},autoStart:!0,onStored:r(()=>{},"onStored"),onPromptReady:r(ge=>{k(ge),C(be=>ge?be==="preparing"?"ready":be:"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){$("The login did not return a saved connection. Try again.");return}const le=f.current;C("connecting"),Kc.loginResult(e,ge).then(ue=>{le===f.current&&u.onComplete({...ue,method:"subscription"})}).catch(()=>{le===f.current&&(C("ready"),$("Could not retrieve the saved connection. Go back and retry."))});return}const be={env:{},aiConnection:{provider:U,method:"subscription",mode:"responsible_user"}};B(be),o(be)},"onConnected")}):ee?null:p&&!re.data?(0,t.jsx)(uW,{adapterType:s,login:{...ae,retry:r(()=>{$(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."})})}),H==="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&&ie?S==="waiting"?"Waiting for code":S==="connecting"?"Connecting":`Sign in to ${z}`:A?"Connecting":H==="subscription"&&(re.data||ee)?"Use saved subscription":H==="api"&&Z?"Use saved API key":"Connect",primaryDisabled:u?.disabled||!!u&&H==="subscription"&&!a&&!p||i&&h.isPending||ae.preparing||!!ae.error||!u&&me.isPending||K.loading||s==="claude_local"&&re.isPending||!j&&!(H==="subscription"&&ee)||!!ie&&(!w||S!=="ready")||H==="api"&&!T.trim()&&!E&&!Z,loading:A,primaryIcon:j&&ie?S==="ready"?"none":"spinner":void 0,onPrimary:r(()=>{if(ie){if(!w||S!=="ready")return;window.open(w,"_blank","noreferrer,noopener"),C("waiting")}else oe()},"onPrimary")})]})}r(wSe,"AgentProviderConnection");function w5(e){return e.provider==="openrouter"?(0,t.jsx)(iat,{...e}):(0,t.jsx)(aat,{...e})}r(w5,"AiConnectionCredentialStep");function aat({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=Mt(),k=X({queryKey:P.environments.list(e),queryFn:r(()=>Ri.list(e),"queryFn")}),S=X({queryKey:P.environments.capabilities(e),queryFn:r(()=>Ri.capabilities(e),"queryFn")}),C=X({queryKey:P.instance.settings,queryFn:Or.get}),I=X({queryKey:P.instance.experimentalSettings,queryFn:Or.getExperimental}),T=X({queryKey:P.instance.generalSettings,queryFn:Or.getGeneral}),R=yW(T.data?.executionMode,k.data??[]);let A=null,D;try{A=R.forced?R.kubernetesEnvironment?.id??null:Zk({agentDefaultEnvironmentId:p??j,instanceDefaultEnvironmentId:C.data?.defaultEnvironmentId,localDefaultEnvironmentId:tN(k.data),managedSandboxOnly:I.data?.enableManagedSandboxOnly,managedSandboxEnvironmentId:eN(k.data),visibleEnvironmentIds:k.data?.map(F=>F.id)})}catch(F){D=F instanceof Error?F.message:"Could not resolve the sign-in environment."}const M=(k.data??[]).filter(F=>F.status==="active"&&(F.driver==="local"||F.driver==="sandbox"&&typeof F.config.provider=="string"&&S.data?.sandboxProviders?.[F.config.provider]?.supportsLoginPty===!0));!R.forced&&!p&&!j&&!M.some(F=>F.id===A)&&(A=M[0]?.id??null);const $=k.data?.find(F=>F.id===A),E=typeof $?.config.provider=="string"?$.config.provider:"",B=$?.driver==="sandbox"&&S.data?.sandboxProviders?.[E]?.supportsLoginPty===!0,z=[k,S,C,I,T].some(F=>F.isPending),q=D??[k,S,C,I,T].find(F=>F.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)(pt,{value:b,onChange:r(F=>v(F.target.value),"onChange"),disabled:!!i})]}),!p&&!R.forced&&M.length>1&&(0,t.jsxs)(Da,{value:A??"",onValueChange:N,children:[(0,t.jsx)(Ma,{"aria-label":"Sign-in environment",children:(0,t.jsx)(Ea,{placeholder:"Sign-in environment"})}),(0,t.jsx)(Pa,{children:M.map(F=>(0,t.jsx)(Sn,{value:F.id,children:F.name},F.id))})]}),q&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:q}),z?(0,t.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:"Preparing sign-in…"}):(0,t.jsx)(wSe,{companyId:e,adapterType:s==="anthropic"?"claude_local":s==="xai"?"grok_local":"codex_local",environmentId:A,canLogin:B,localEnvironment:$?.driver==="local",onBack:x,onConnected:r(()=>{},"onConnected"),testConnection:r(async()=>!1,"testConnection"),managedAccount:{intent:U,nameForMethod:c,initialMethod:n,fixedMethod:a??!!i,disabled:z||!!q||!b.trim(),onComplete:r(F=>{w.invalidateQueries({queryKey:["ai-connections",e]}),f(F)},"onComplete")}},A??"local")]})}r(aat,"SubscriptionConnectionStep");function iat({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=Mt(),j=je({mutationFn:r(()=>Kc.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)(pt,{value:p,onChange:r(N=>f(N.target.value),"onChange"),disabled:!!n})]}),j.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:j.error.message}),(0,t.jsx)(kNe,{providerName:"OpenRouter",value:x,onChange:b,onSubmit:r(()=>j.mutate(),"onSubmit"),disabled:j.isPending,placeholder:"Enter API key here",autoFocus:!0}),(0,t.jsxs)("div",{className:"flex justify-between gap-2",children:[(0,t.jsx)(L,{variant:"ghost",onClick:h,children:"Cancel"}),(0,t.jsx)(L,{disabled:!p.trim()||!x.trim()||j.isPending,onClick:r(()=>j.mutate(),"onClick"),children:j.isPending?"Connecting…":"Connect"})]})]})}r(iat,"ApiKeyConnectionStep");var oat=null;function sS(){const e=(0,m.useContext)(fI),{data:s,isFetched:n,isError:a}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn"),enabled:e!=null},e??(oat??=new IN));return e?{enabled:!a&&s?.enableChatConnectors===!0,loaded:n}:{enabled:!1,loaded:!0}}r(sS,"useChatConnectorsEnabled");var lat=new RegExp(`\\b(${["mcp","server","profile","policy","gateway","transport","stdio","endpoint"].join("|")})s?\\b`,"gi");function kSe(e){return e.replace(lat,"").replace(/\s{2,}/g," ").replace(/\s+([.,])/g,"$1").trim()}r(kSe,"sanitizeProsumerCopy");var cat={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."}},dat={tagline:"Give your agents access to this app.",short:"Give your agents access to this app."};function NSe(e,s){const n=cat[e];if(n)return n;if(s){const a=kSe(s);if(a)return{tagline:a,short:a}}return dat}r(NSe,"appCopyFor");function Dte(e,s,n){return n<=1?`Your ${e} key`:kSe(s)||`Your ${e} key`}r(Dte,"credentialFieldLabel");var uat=1500;function Cp(e=uat){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 ha(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 NW(){const e=Gc()?.pushToast;return(0,m.useCallback)(async(s,n="Copied")=>{try{return await ha(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(NW,"useCopyToast");var mat="/cloud/connections/handoff",hat="/cloud/connections/reauth",k5="paperclip.cloud-oauth-handoff.v1",tg=class extends Error{static{r(this,"OAuthHandoffError")}code;constructor(e,s){super(e),this.code=s,this.name="OAuthHandoffError"}};function SW(e){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new tg("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 tg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");return{kind:"paperclip_cloud",session:s.session}}r(SW,"parseHandoff");function pat(e,s){return e===404||s==="SESSION_NOT_AVAILABLE"?new tg("This sign-in expired. Start the connection again.","expired"):e===401||e===403?new tg("Paperclip Cloud could not authorize this connection for your account.","forbidden"):new tg("Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(pat,"handoffFailure");async function fat(e,s){const n=s.request??fetch;let a,i;for(let o=0;o<2;o+=1)try{if(a=await n(mat,{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 tg(i instanceof Error?i.message:"Paperclip Cloud couldn’t prepare secure sign-in. Try again.","unavailable")}r(fat,"postCloudHandoff");function xat(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!==hat||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(xat,"exactReauthenticationTarget");async function nN(e,s={}){const n=SW(e.handoff);if(!n){const l=Y3(e.authorizationUrl);if(!l.ok)throw new tg(l.message,"invalid_handoff");return{kind:"authorization",url:l.url,host:l.host}}const a=await fat(n.session,s),i=await a.json().catch(()=>null);if(!a.ok){if(i?.error==="RECENT_LOGIN_REQUIRED"){const l=xat(i.reauthenticationUrl,n.session);if(l)return l}throw pat(a.status,i?.error)}const o=Y3(typeof i?.authorizationUrl=="string"?i.authorizationUrl:void 0);if(!o.ok)throw new tg("Paperclip Cloud returned an invalid provider sign-in address.","invalid_handoff");return{kind:"authorization",url:o.url,host:o.host}}r(nN,"prepareOAuthNavigation");function R_(e,s=window.sessionStorage){const n=SW({kind:"paperclip_cloud",session:e});if(!n)throw new tg("Paperclip Cloud returned an invalid sign-in handoff.","invalid_handoff");const a={version:1,session:n.session,savedAt:Date.now()};s.setItem(k5,JSON.stringify(a))}r(R_,"savePendingCloudHandoff");function gat(e=window.sessionStorage){const s=e.getItem(k5);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 SW({kind:"paperclip_cloud",session:n.session})}catch{return e.removeItem(k5),null}}r(gat,"readPendingCloudHandoff");function Lte(e=window.sessionStorage){e.removeItem(k5)}r(Lte,"clearPendingCloudHandoff");function ZM(e){return!!(e&&fpe({...e,methods:e.methods.filter(s=>(s.purpose??"tool")!=="channel"&&s.transport!=="chat_sdk")}))}r(ZM,"appSupportsToolCatalogSetup");var bat=SDe.filter(e=>gpe(e).some(s=>tp(s))).map(e=>e.slug);function vat(e){return bat.some(s=>s===e)}r(vat,"isMcpDirectOAuthConnectSlug");function E_(e,s){const n=new URLSearchParams({source:e});return s&&n.set("intent",s),`/apps/connect?${n.toString()}`}r(E_,"appSourceConnectHref");function yat(e,s){return`/apps/connect?${new URLSearchParams({source:e,resume:s}).toString()}`}r(yat,"appSourceResumeHref");function F$(e){return e?`/apps/vercel-connect?${new URLSearchParams({source:e}).toString()}`:"/apps/vercel-connect"}r(F$,"vercelConnectSourceHref");function jat(e){return e.serviceSlug??e.appKey??e.sourceSlug??void 0}r(jat,"resolveAppsConnectRouteKey");function wat(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=SN(n);return!s&&a?.methods.some(i=>i.transport==="chat_sdk")&&!a.methods.some(i=>(i.purpose??"tool")!=="channel"&&i.transport!=="chat_sdk")?!1:hI(n)&&e.get("reconnect")?.trim()?!0:n==="agentmail"||s?fpe(a):ZM(a)}r(wat,"canEnterAppsConnect");var B$=" for the organization",kat=" for the company";function $te(e,s){const n=e.trim();if(s!=="organization")return n;const a=n.toLocaleLowerCase();return a.endsWith(B$)?n:a.endsWith(kat)?`${n.slice(0,n.length-16).trimEnd()}${B$}`:`${n}${B$}`}r($te,"connectionNameForGrantKind");function Nat(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(Nat,"grantStatusLabel");function Sat(e){switch(e){case"active":return"connected";case"needs_reauthorization":case"expired":return"attention";case"revoked":return"inactive";default:return"missing"}}r(Sat,"grantStatusTone");function Cat(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(Cat,"grantAccountLabel");function _at(e){return new Set((e?.members??[]).filter(s=>s.subjectType==="user").map(s=>s.subjectId))}r(_at,"audienceUserIds");function Iat(e){return e.find(s=>s.kind==="organization"&&s.isDefault)??e.find(s=>s.kind==="organization")??null}r(Iat,"organizationGrant");function Aat(e,s){return s?e.find(n=>n.kind==="user"&&n.subjectUserId===s)??null:null}r(Aat,"personalGrantFor");function Tat(e,s){if(!s)return null;const n=e.find(a=>a.userId===s);return n&&(n.name?.trim()||n.email?.trim())||null}r(Tat,"memberLabel");var Ote=0;function Yq(){return Ote+=1,{id:`header-${Ote}`,name:"",value:""}}r(Yq,"newCustomHeaderRow");function S1(e){try{return new URL(e).host||null}catch{return null}}r(S1,"endpointHost");function SSe(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(SSe,"oauthCallbackUrlForBrowser");function z$(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(z$,"defaultGenericMcpName");function Fte(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(Fte,"genericConnectGuidance");function CSe(e){const s=new Set;for(const n of e){const a=n.name.trim();if(!a&&!n.value.trim())continue;const i=ULe(a);if(!i.ok)return xJ(a,i.reason);const o=gLe(n.value);if(!o.ok)return xJ(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(CSe,"customHeaderError");function Rat(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(Rat,"genericConnectPayload");function Eat(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&&CSe(e.headers)===null:!0:!1}r(Eat,"canSubmitGenericConnect");function rN(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(rN,"installStateFrom");function _Se(e,s){return e.onAll||e.agentIds.has(s)}r(_Se,"isAgentInstalled");function ISe(e,s){return s.onAll?[{targetType:"company",targetId:e}]:[...s.agentIds].map(n=>({targetType:"agent",targetId:n}))}r(ISe,"installPayload");var Pat="Has access — tick to load its tools into this agent's context.";function ASe(e){return`paperclip.connector-enrollment-access:${e}`}r(ASe,"enrollmentAccessStorageKey");function Mat(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(Mat,"validEnrollmentAccessState");function Dat(e,s,n){try{window.sessionStorage.setItem(ASe(s),JSON.stringify({...n,companyId:e}))}catch{}}r(Dat,"saveEnrollmentAccessState");function Lat(e){const s=ASe(e);try{const n=window.sessionStorage.getItem(s);if(window.sessionStorage.removeItem(s),!n)return null;const a=JSON.parse(n);return Mat(a)?a:null}catch{return null}}r(Lat,"consumeEnrollmentAccessState");function Bte(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(Bte,"githubRecoveryUrl");function zte(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(zte,"oauthCallbackErrorMessage");var $at={key:"setup",success:"complete"};function qte(e){return e.requestedAppKey||e.hasPrefilledLink||e.zapierSource?"key":"gallery"}r(qte,"requestedConnectionInitialStep");function Oat(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 hg(n)!==e.requestedAppKey?null:hI(e.requestedAppKey)}r(Oat,"requestedConnectionEntry");function Fat(e){return!e.reconnectConnection||!e.reconnectApplication||e.reconnectConnection.applicationId!==e.reconnectApplication.id?!1:e.requestedAppKey?hg(e.reconnectApplication)===e.requestedAppKey:e.byo&&e.applicationId===e.reconnectApplication.id}r(Fat,"retainedReconnectMatches");function Bat(e){return e.credentialSource==="vercel_connect"&&!e.available&&!e.retainedReconnectMatches}r(Bat,"isVercelConnectUnavailable");function zat(e){return e.available===!1&&!(e.reconnectConnectionId&&e.reconnectSourceMatches)}r(zat,"isConnectionDefinitionUnavailable");function qat(e){return!e.hasRequestedEntry||e.supportedMethodCount===0||e.unsupportedOAuth||e.vercelUnavailable||e.definitionUnavailable?e.reconnectConnectionId?"reconnect_unavailable":"fallback":"ready"}r(qat,"requestedConnectionSetupResolution");function Ute(e,s,n,a){const i=$at[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(Ute,"appConnectHref");function $2(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($2,"withConnectionIntent");var Kte=["Pick app","Add your key"],Wte={gallery:0,key:1},Uat={key:0},Kat=["Add MCP URL"],Wat=["Sign in"];function q$(e,s=!1){return s&&e?.auth!=="none"&&(!e?.grantKinds||e.grantKinds.includes("user"))?"user":e?.grantKinds?.length===1||e?.grantKinds&&!e.grantKinds.includes("organization")?e.grantKinds[0]:"organization"}r(q$,"defaultGrantKindFor");function Vat(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(Vat,"configuredAgentIdentity");function zC(e,s){const n=typeof s=="string"?s:s?.key;return e?.slug==="google-sheets"&&n==="local"}r(zC,"isGoogleSheetsRobotMethod");function ZS(e){return e?Object.fromEntries([...e.tenantFields??[],...e.extensionFields??[]].filter(s=>s.defaultValue!==void 0).map(s=>[s.key,s.defaultValue])):{}}r(ZS,"defaultMethodConfig");function kw(e,s){if(!e)return[];const n=nA(e);return s==="vercel_connect"?n.filter(a=>!!a.credentialSources?.vercelConnect):n}r(kw,"connectionMethodsForCredentialSource");function nA(e){return gpe(e).filter(s=>(s.purpose??"tool")!=="channel")}r(nA,"availableToolConnectionMethods");function O2(e,s){const n=nA(e);return s?n.find(a=>a.key===s)??null:q8(n)}r(O2,"availableToolConnectionMethod");function mk(e){return q8(e)}r(mk,"recommendedSetupConnectionMethod");function Vte(e){return mk(e?e.methods.filter(s=>(s.purpose??"tool")==="tool"&&(s.oauthStrategy==="paperclip_cloud_connector"||s.oauthStrategy==="paperclip_id_connector")):[])}r(Vte,"recommendedManagedConnectorMethod");function Hte(e){if(!e)return!1;const s=nA(e),n=s.length===1?s[0]:null;return!!(n&&tp(n)&&!DDe(n))}r(Hte,"canUseAutomaticOAuthFastPath");function Gte(e){if(!e)return null;const s=nA(e),n=s.length===1?s[0]:null;return n&&tp(n)?n:null}r(Gte,"automaticOAuthMethod");function Hat(e){const s=e.metadata;if(!s)return null;const n=s.sourceTemplateKey??s.galleryKey;return typeof n=="string"?n:null}r(Hat,"appSourceSlug");function Gat(e){const s=e.config?.sourceTemplateKey??e.transportConfig.sourceTemplateKey;return typeof s=="string"?s:null}r(Gat,"connectionSourceSlug");function Qte(e,s,n,a={}){if(!e)return null;const i=new Set(s.filter(o=>o.status!=="archived"&&Hat(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)||Gat(o)===e;return o.status!=="archived"&&(!a.draftOnly||o.status==="draft")&&o.authKind==="oauth"&&l})??null}r(Qte,"reusableOAuthConnection");function TSe(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(TSe,"readConnectionIntentOAuthOutcome");function e4(e={}){const[s]=hi(),n=ga(),{selectedCompanyId:a}=gs(),i=_9(),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&&u1(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||u1(l)||A3(l))),h=X({queryKey:["tools","connection",d],queryFn:r(()=>es.getConnection(d),"queryFn"),enabled:u}),p=l||h.data?.config?.sourceTemplateKey,f=s.get("method")||h.data?.config?.connectionMethodKey;if(u&&h.isPending)return(0,t.jsx)("p",{className:"p-6 text-sm text-muted-foreground",children:"Loading connection…"});if(u&&h.isError)return(0,t.jsxs)("div",{role:"alert",className:"space-y-3 p-6",children:[(0,t.jsx)("p",{children:"Could not load this connection. Your saved access and credentials have not changed."}),(0,t.jsx)(L,{variant:"outline",onClick:r(()=>{h.refetch()},"onClick"),children:"Try again"})]});if(A3(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"&&u1(p)&&(!f||LR(p,f))){const x=Mpe(p,s.get("targetToolkit"));return(0,t.jsx)(kHe,{...e,upstreamServiceName:e.upstreamServiceName??x?.name,interactionId:o,providerId:p,connection:h.data},`${o||"page"}:${p}`)}return(0,t.jsx)(Qat,{...e})}r(e4,"ConnectionSetupFlow");function Qat({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=Mt(),S=Ln(),C=(0,m.useCallback)((yt,Ne)=>{o==="page"&&(Ne?S(yt,Ne):S(yt))},[o,S]),I=ga(),{selectedCompany:T,selectedCompanyId:R}=gs(),{enabled:A}=sS(),{enabled:D}=_9(),{setBreadcrumbs:M}=Fn(),{pushToast:$}=pi(),[E]=hi(),B=d?.trim()||E.get("intent")?.trim()||null,z=I.appKey??E.get("appKey")??void 0,q=E.get("source")?.trim()||null,U=u||E.get("new")==="1",F=E.get("stage")?.trim()||null,K=E.get("method")?.trim()||null,G=E.get("resume")?.trim()||null,se=E.get("oauth"),ee=E.get("code"),ne=Bte(E.get("installation_url")),he=Bte(E.get("management_url")),Z=p?.id??(E.get("reconnect")?.trim()||null),re=E.get("identity")==="user"?"user":E.get("identity")==="organization"?"organization":null,ce=i==="vercel_connect",H=l??q,Q=i==="paperclip_vault"&&vat(H)?H:null,Y=jat({serviceSlug:l,appKey:z,sourceSlug:q}),te=(l??q??z)==="zapier",ae=te?void 0:Y,me=!!p||o==="page"&&(a||E.get("byo")==="1"),[oe]=(0,m.useState)(()=>o==="page"&&E.get("cloud_connector")==="enrolled"&&ae?Lat(ae):null),[ie]=(0,m.useState)(()=>{const yt=E.get("link")?.trim()??"";return{link:/^https?:\/\//i.test(yt)?yt:"",name:p?.name??E.get("name")?.trim()??"",applicationId:p?.applicationId??(E.get("applicationId")?.trim()||void 0)}}),[ge,be]=(0,m.useState)(()=>qte({requestedAppKey:ae,routeStage:F,resumeConnectionId:G,hasPrefilledLink:!!ie.link,zapierSource:te})),[le,ue]=(0,m.useState)(null),[Se,ye]=(0,m.useState)(""),[Ie,Ke]=(0,m.useState)(ie.link),[rt,dt]=(0,m.useState)(ie.name||(te?"Zapier":"")),[de,ze]=(0,m.useState)(!1),[gt,bt]=(0,m.useState)(""),[De,Qe]=(0,m.useState)("auto"),[mt,Ye]=(0,m.useState)(()=>[Yq()]),[it,Nt]=(0,m.useState)(""),[Ze,Pe]=(0,m.useState)(""),[Ce,Ve]=(0,m.useState)(!1),[Ge,ot]=(0,m.useState)(null),[Ee,Je]=(0,m.useState)(!1),[_e,He]=(0,m.useState)({}),[ns,fe]=(0,m.useState)(""),[ct,Ue]=(0,m.useState)(""),[Et,$t]=(0,m.useState)(""),[js,Fe]=(0,m.useState)(v&&v.mode!=="responsible_user"?`ai-${v.method}`:""),[xt,Wt]=(0,m.useState)(null),[Cs,Ts]=(0,m.useState)({}),[Ct,ds]=(0,m.useState)(""),[Oe,xe]=(0,m.useState)(null),[Gt,Pt]=(0,m.useState)(null),[os,ws]=(0,m.useState)({}),[Hs,tr]=(0,m.useState)("all"),[Le,et]=(0,m.useState)(new Set),[vt,$e]=(0,m.useState)(()=>new Set(oe?.agentIds??(c?[c]:[]))),[Ft,wt]=(0,m.useState)(oe?.grantKind??re??(c?"user":"organization")),[Yt,Zt]=(0,m.useState)(oe?.installChoice??(c?"specific":"all")),us=!!(G&&(se==="failed"||se==="denied")),[ht,kt]=(0,m.useState)(us?"error":"entry"),[Rs,hs]=(0,m.useState)(()=>us?zte(se,ee):null),[jn,Es]=(0,m.useState)(null),an=(0,m.useRef)(!1),Jt=(0,m.useRef)(!1),Xs=(0,m.useRef)(null),Zs=(0,m.useRef)(null),[qr,pr]=(0,m.useState)(null),jr=(0,m.useRef)(null),[mn,Zn]=(0,m.useState)(null),[Tr,Wr]=(0,m.useState)(null),ut=(0,m.useRef)(null),[rs,Ls]=(0,m.useState)(h.length>0&&!!f),[Os,Us]=(0,m.useState)(null),[Ps,fr]=(0,m.useState)(null),[xr,wr]=(0,m.useState)(null),nr=(0,m.useCallback)(()=>{o!=="dialog"||jr.current?.closed===!1||(jr.current=window.open("about:blank","paperclip-connection-oauth","popup,width=720,height=760,resizable=yes,scrollbars=yes"))},[o]),Fr=(0,m.useCallback)(yt=>{if(o!=="dialog"){Mm(yt);return}Wr(yt);const Ne=jr.current;if(!Ne||Ne.closed){kt("error"),hs("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue."),j?.("needs_retry");return}Ne.location.assign(yt),Ne.focus()},[o,j]),kr=(0,m.useCallback)(()=>{jr.current=null,hs(null),kt("redirecting"),j?.("authorizing")},[j]);(0,m.useEffect)(()=>{if(o!=="dialog"||ht!=="redirecting")return;const yt=window.setInterval(()=>{jr.current?.closed&&(kt("error"),hs("The sign-in window closed. If authorization did not finish, try again."),Wr(null),j?.("needs_retry"))},1e3);return()=>window.clearInterval(yt)},[o,ht,j]);const _t=(0,m.useCallback)(async yt=>{ut.current?.abort();const Ne=new AbortController;ut.current=Ne;try{const at=await nN(yt,{signal:Ne.signal});if(at.kind==="reauthentication"){const It=o==="dialog"?jr.current:window;if(!It||It.closed||!yt.handoff)throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");R_(yt.handoff.session,It.sessionStorage),kt("starting")}else Es(at.host),kt("redirecting");Fr(at.url)}catch(at){if(Ne.signal.aborted)return;kt("error"),hs(at instanceof Error?at.message:"Paperclip couldn’t start secure sign-in. Try again."),j?.("needs_retry")}finally{ut.current===Ne&&(ut.current=null)}},[o,j,Fr]);(0,m.useEffect)(()=>()=>ut.current?.abort(),[]),(0,m.useEffect)(()=>{if(o!=="dialog"||!B)return;const yt=r(Ne=>{const at=TSe(Ne,window.location.origin,B);if(at==="connected"){kt("entry"),Wr(null),x?.({resolvedByCallback:!0});return}if(at==="declined"){kt("error"),hs("Authorization was cancelled. You can try again."),j?.("needs_retry");return}at==="failed"&&(kt("error"),hs("Authorization did not complete. Try again when you’re ready."))},"receiveOAuthOutcome");return window.addEventListener("message",yt),()=>window.removeEventListener("message",yt)},[B,o,x,b]),(0,m.useEffect)(()=>{if(o!=="dialog"||B||!mn)return;let yt=!1,Ne=!1;const at=window.setInterval(async()=>{if(Ne||yt)return;const It=jr.current;if(!It||It.closed){Zn(null),kt("error"),hs("The sign-in window closed. Try again to finish connecting GitHub.");return}let ps;try{ps=new URL(It.location.href)}catch{return}if(!(ps.origin!==window.location.origin||!ps.pathname.includes(mn))){if(ps.searchParams.has("oauth")){Zn(null),kt("error"),hs("Authorization did not complete. Finish setup in the sign-in window or try again.");return}if(ps.searchParams.get("success")==="1"){Ne=!0;try{const Bs=await es.getConnection(mn);!yt&&Bs.status==="active"&&(Zn(null),It.close(),x?.({connectionId:Bs.id}))}catch{yt||(Zn(null),kt("error"),hs("Could not confirm the connection. Try again."))}finally{Ne=!1}}}},1e3);return()=>{yt=!0,window.clearInterval(at)}},[B,mn,o,x]);const qs=r(()=>{Qe("auto"),Ye([Yq()]),Nt(""),Pe(""),Ve(!1),ot(null),Je(!1)},"resetGenericAuthState"),hn=r(yt=>{if(o==="page"&&!B&&i==="paperclip_vault"&&u1(yt.slug)){C(`/apps/connect?source=${yt.slug}`);return}if(yt.slug==="zapier"){ue(null),ye(""),Ke(""),dt("Zapier"),ze(!1),bt(""),qs(),He({}),Pt(null),be("key"),C($2("/apps/connect?source=zapier",B));return}if(i==="paperclip_vault"&&Hte(yt)){C(E_(yt.slug,B));return}ue(yt),ye(yt.name),Ke(""),dt(""),ze(!1),bt(""),qs(),He({}),fe(""),Ue(""),$t("");const Ne=mk(kw(yt,i));Fe(Ne?.key??""),Ts(ZS(Ne)),ds(""),xe(null),Pt(null),$e(new Set(c?[c]:[])),Zt(c?"specific":"all"),wt(Br??q$(Ne,!!c)),be("key"),C(i==="vercel_connect"?$2(F$(yt.slug),B):E_(yt.slug,B))},"useMatchedGalleryEntry"),tt=r(()=>{be("gallery"),C($2(i==="vercel_connect"?F$():a?"/apps/byo":"/apps",B))},"backToGallery");(0,m.useEffect)(()=>{if(o==="page")return M([{label:"Connectors",href:"/apps"},{label:ce?"Vercel Connect":a?"Connect your own tool":"Connect an app"}]),()=>M([])},[a,o,M,ce]);const Dt=X({queryKey:P.apps.gallery(R??"__none__"),queryFn:r(()=>es.listGallery(R),"queryFn"),select:(0,m.useCallback)(yt=>B?{...yt,apps:yt.apps.map(Ne=>({...Ne,methods:Ne.methods.filter(at=>v?at.ai?.provider===v.provider&&(v.mode==="responsible_user"||at.ai.method===v.method):at.transport!=="runtime_auth")})).filter(Ne=>Ne.methods.length>0)}:yt,[B,v?.provider,v?.method,v?.mode]),enabled:!!R}),xs=(0,m.useMemo)(()=>(Dt.data?.apps??[]).filter(yt=>D||!A3(yt.slug)).filter(yt=>yt.slug==="agentmail"||A||!yt.methods.some(Ne=>Ne.transport==="chat_sdk")||ZM(yt)),[Dt.data,A,D]),Gs=ae?hI(ae):null,Bn=Gs?.methods.find(yt=>Jw(yt)&&!tp(yt)),Cr=!(Bn&&js===Bn.key)&&!!Gs?.methods.some(yt=>yt.oauthStrategy==="paperclip_cloud_connector"||yt.oauthStrategy==="paperclip_id_connector"),Qr=!!le?.methods.some(yt=>yt.oauthStrategy==="paperclip_cloud_connector"||yt.oauthStrategy==="paperclip_id_connector"),Nr=le&&Cr&&!Qr?Vte(Gs):null,[Rr,cr]=(0,m.useState)(null),rr=X({queryKey:["cloud-connector","enrollment"],queryFn:r(()=>es.getCloudConnectorEnrollment(),"queryFn"),refetchInterval:Rr?2e3:!1,enabled:!!(R&&Cr&&!Qr)}),[sr,Va]=(0,m.useState)(null),Ta=(0,m.useCallback)(()=>{jr.current?.close(),jr.current=null,cr(null)},[]),$s=(0,m.useCallback)(()=>{!R||!ae||Dat(R,ae,{grantKind:Ft,installChoice:Yt,agentIds:Yt==="specific"?[...vt]:[]})},[Ft,vt,Yt,ae,R]),pn=(0,m.useCallback)(yt=>{const Ne=Y3(yt);if(!Ne.ok){Ta(),Va(Ne.message);return}if(o==="dialog"){cr(Ne.url);const at=jr.current;at&&!at.closed?(at.location.assign(Ne.url),at.focus()):Va("Open authorization in a new tab to continue.");return}Mm(Ne.url)},[o,Ta]);(0,m.useEffect)(()=>{!Rr||rr.data?.status!=="active"||(Ta(),Va(null),Dt.refetch())},[Rr,rr.data?.status,Dt.refetch,Ta]);const dr=je({mutationFn:r(()=>es.startCloudConnectorEnrollment(R,T?.name,ae?Ute(ae,"key",i,{resumeConnectionId:G,reconnectConnectionId:Z,interactionId:B})+(o==="dialog"?"&enrollment_host=dialog":""):void 0),"mutationFn"),onSuccess:r(yt=>{if(!yt.verificationUrl){Ta(),Va("Paperclip Cloud did not return an enrollment link. Try again.");return}pn(yt.verificationUrl)},"onSuccess"),onError:r(yt=>{Ta(),Va(yt instanceof Error?yt.message:"Paperclip couldn’t reach Paperclip Cloud. Try again.")},"onError")}),Yn=X({queryKey:P.tools.applications(R??"__none__"),queryFn:r(()=>es.listApplications(R),"queryFn"),enabled:!!R&&(!!Q||!!G||!!Z),refetchOnMount:"always"}),wn=X({queryKey:P.tools.connections(R??"__none__"),queryFn:r(()=>es.listConnections(R),"queryFn"),enabled:!!R&&(!!Q||!!G||!!Z),refetchOnMount:"always"}),Vr=(0,m.useMemo)(()=>u?null:Qte(Q,Yn.data?.applications??[],wn.data?.connections??[],U?{applicationId:ie.applicationId,draftOnly:!0}:{}),[Yn.data,wn.data,U,Q,ie.applicationId,u]),as=(0,m.useMemo)(()=>Z?(wn.data?.connections??[]).find(yt=>yt.id===Z)??null:null,[wn.data,Z]),Mn=(0,m.useRef)(null);(0,m.useEffect)(()=>{if(!p||!wn.isFetchedAfterMount||!as||Mn.current===as.id)return;const yt=as.config?.url??as.transportConfig?.url??as.transportConfig?.serverUrl??as.config?.serverUrl;typeof yt!="string"||!/^https?:\/\//i.test(yt)||(Mn.current=as.id,Ke(Ne=>Ne||yt))},[p,wn.isFetchedAfterMount,as]);const $n=(0,m.useMemo)(()=>as?(Yn.data?.applications??[]).find(yt=>yt.id===as.applicationId)??null:null,[Yn.data,as]),zn=Fat({requestedAppKey:ae,byo:me,applicationId:ie.applicationId,reconnectConnection:as,reconnectApplication:$n}),Cn=(0,m.useMemo)(()=>G?(wn.data?.connections??[]).find(yt=>yt.id===G)??null:null,[wn.data,G]),Er=Cn??as,Br=Er?Er.credentialPolicy==="per_user"?"user":Er.credentialPolicy==="per_agent"?"agent":"organization":re,we=Cn?.authKind==="oauth"?Cn:Vr,Xt=Vr?Vr.credentialPolicy==="per_user"?"user":Vr.credentialPolicy==="per_agent"?"agent":"organization":null,fn=Br??Xt;(0,m.useEffect)(()=>{fn&&wt(fn)},[fn]);const br=(0,m.useMemo)(()=>Ie&&!le?d3(Ie,xs):null,[le,xs,Ie]),aa=le?O2(le,js||null):null,ei=aa&&tp(aa)?aa:Gte(le),ms=i==="paperclip_vault"&&ei?le:null,Ae=i==="paperclip_vault"&&Hte(le)?le:null,Ut=!!Q&&(!Yn.isFetchedAfterMount||!wn.isFetchedAfterMount),Ht=r(yt=>{be(yt),le&&C(Ute(le.slug,yt,i,{connectionMethodKey:le.methods.find(Ne=>Ne.key===js)?.ai?js:void 0,resumeConnectionId:G,reconnectConnectionId:Z,interactionId:B}))},"setAppStep"),cn=Cn??as??we,rn=le?.agentInstructions,er=le&&rn?xt?.slug===le.slug?xt.value:cn?cn.agentInstructions??{...Lk(rn),enabled:!1}:Lk(rn):null,Dr=!er||!!er.text.trim(),zt=je({mutationFn:r(async yt=>(er&&JSON.stringify(er)!==JSON.stringify(yt.agentInstructions)&&await es.updateConnection(yt.id,{agentInstructions:er}),es.startOAuth(yt.id,{asCurrentUser:yt.credentialPolicy==="per_user",...yt.credentialPolicy==="per_agent"?{asAgentId:Vat(yt)??[...vt][0]}:{},...B?{interactionId:B}:{}})),"mutationFn"),onSuccess:r(yt=>{_t(yt)},"onSuccess"),onError:r(yt=>{const Ne=yt instanceof un&&yt.body&&typeof yt.body=="object"?yt.body.details:null;kt("error"),j?.("needs_retry"),hs(Ne?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":yt instanceof Error?yt.message:"Paperclip couldn’t start secure sign-in. Try again.")},"onError")}),ls=zt.mutate,_n=(0,m.useCallback)(yt=>{j?.("authorizing"),nr(),o==="dialog"&&!B&&Zn(yt.id),ls(yt)},[ls,j,nr,o,B]),ar=r(async yt=>{if(c)return;const Ne=ISe(R,(fn??Ft)!=="agent"&&Yt==="all"?{onAll:!0,agentIds:new Set}:{onAll:!1,agentIds:vt});await es.putConnectionInstalls(yt,Ne)},"applyAccessInstalls"),dn=fn??Ft,ca=je({mutationFn:r(async yt=>{const Ne=yt??le;let at;if(Ne){const It=fn??Ft,ps=O2(Ne,js||null),Bs=zC(Ne,ps)?eq(Ct).ids:[],ja=Se.trim(),ia=$te(ja||Ne.name,It);at=await es.connectApp(R,{galleryKey:Ne.slug,...er?{agentInstructions:er}:{},...js?{connectionMethodKey:js}:{},name:ia,credentialSource:i,...i==="paperclip_vault"?{credentialValues:_e}:{},...i==="vercel_connect"?{vercelConnect:{connector:Et.trim()}}:{},...ns.trim()?{oauthClient:{clientId:ns.trim(),...ct?{clientSecret:ct}:{}}}:{},configValues:zC(Ne,ps)?{allowedSpreadsheetIds:Bs}:Object.keys(Cs).length>0?Cs:void 0,applicationId:ie.applicationId,...G??Xs.current?{resumeConnectionId:G??Xs.current}:Z?{reconnectConnectionId:Z}:{},...It!=="organization"?{grantKind:It}:{},...It==="agent"?{subjectAgentId:[...vt][0]}:{}}),Xs.current=null}else{const It=Rat({link:Ie,name:rt,authMode:De,needsKey:de,keyValue:gt,headers:mt,oauthClientId:it,oauthClientSecret:Ze}),ps=$te(It.name??z$(Ie)??"Custom app",dn);at=await es.connectApp(R,{...It,...Z?{reconnectConnectionId:Z}:{},...te||br?.slug==="zapier"?{galleryKey:"zapier",connectionMethodKey:"generated-url"}:{},name:ps,applicationId:ie.applicationId,...dn!=="organization"?{grantKind:dn}:{},...dn==="agent"?{subjectAgentId:[...vt][0]}:{}})}return at.auth?.kind==="oauth"&&!G&&!Z&&await ar(at.connectionId),at},"mutationFn"),onSuccess:r(yt=>{if(yt.auth?.kind==="oauth"){if(Pt(yt),yt.auth.manualClientRequired){ot(Fte("oauth_manual_client_required",null)),Qe("oauth"),Ve(!0),Je(!1);return}if(o==="dialog"||B){kt("starting"),Je(!le),_n(yt.connection);return}const at=yt.auth.startUrl?.trim();if(!at){kt("starting"),Je(!0),_n(yt.connection);return}Je(!0),_t({authorizationUrl:at,handoff:yt.auth.handoff});return}ot(null),Pt(yt);const Ne={};for(const at of yt.actions.readOnly)Ne[at.catalogEntryId]=!0;for(const at of yt.actions.canMakeChanges)Ne[at.catalogEntryId]=!0;ws(Ne),zi.mutate({result:yt,enabled:Ne})},"onSuccess"),onError:r(yt=>{const Ne=yt instanceof un&&yt.body&&typeof yt.body=="object"?yt.body.details:null;if(ms){kt("error"),j?.("needs_retry"),hs(Ne?.code==="invalid_grant"?"Your authorization expired or was revoked. Reconnect to continue.":yt instanceof Error?yt.message:"Paperclip couldn’t start secure sign-in. Try again.");return}if(!le&&Ie){const at=typeof Ne?.code=="string"?Ne.code:null,It=Fte(at,yt instanceof Error?yt.message:null);ot(It),Je(!1),It.focus==="credentials"&&(ze(!0),Ve(!0));return}$({title:"Couldn’t connect",body:yt instanceof Error?yt.message:"Please check your key and try again.",tone:"error"})},"onError")}),ur=ca.mutate,Ei=(0,m.useCallback)(yt=>{const Ne=yt??le;(Ne?O2(Ne,js||null):null)?.auth==="oauth"&&nr(),ur(yt)},[js,le,ur,nr]);(0,m.useEffect)(()=>{if(!ae||Dt.isLoading||!Dt.data||Z&&(!wn.isFetchedAfterMount||!Yn.isFetchedAfterMount))return;const yt=Oat({requestedAppKey:ae,galleryApps:Dt.data.apps,reconnectConnection:as,applications:Yn.data?.applications??[]}),Ne=!!yt?.methods.some(Re=>Re.oauthStrategy==="paperclip_cloud_connector"||Re.oauthStrategy==="paperclip_id_connector");if(Cr&&!Ne&&rr.isLoading)return;const at=kw(yt,i),It=v??(as?.connectionPurpose==="ai"?gJ.safeParse(as.config?.ai).data:void 0),ps=at.find(Re=>It?Re.ai?.provider===It.provider&&(!("mode"in It)||It.mode!=="responsible_user")&&Re.ai.method===It.method:Re.key===K)??(Cr&&!Ne?Vte(Gs):null)??mk(at),Bs=at.length===1?at[0]:null,ja=i==="paperclip_vault"&&!!Gte(yt),ia=Bat({credentialSource:i,available:Dt.data.credentialSources?.vercelConnect.available===!0,retainedReconnectMatches:!!(Z&&zn)}),Ur=at.length===1&&Bs?.auth==="oauth"&&!tp(Bs)&&!Jw(Bs),_a=zat({available:yt?.availability?.available,reconnectConnectionId:Z,reconnectSourceMatches:zn}),Ti=qat({reconnectConnectionId:Z,hasRequestedEntry:!!yt,supportedMethodCount:at.length,unsupportedOAuth:Ur,vercelUnavailable:ia,definitionUnavailable:_a});if(Ti!=="ready"){if(ue(null),be("gallery"),Ti==="reconnect_unavailable"&&Z){wr(Z);return}C($2(i==="vercel_connect"?F$():"/apps/connect",B),{replace:!0});return}if(wr(null),!!yt){if(le?.slug!==yt.slug){ue(yt),ye(yt.name),Ke(""),dt(""),ze(!1),bt(""),He({}),fe(""),Ue(""),$t(""),Fe(ps?.key??""),Ts(ZS(ps)),ds(""),xe(null),Pt(null);const Re=oe?.companyId===R?oe:null;wt(Br??Re?.grantKind??q$(ps,!!c)),$e(new Set(Re?.agentIds??(c?[c]:[]))),Zt(Re?.installChoice??(c?"specific":"all")),be(qte({requestedAppKey:ae,routeStage:F,resumeConnectionId:G,hasPrefilledLink:!!ie.link,zapierSource:te}))}else Qr!==Ne&&(ue(yt),Fe(ps?.key??""),Ts(ZS(ps)));if(!(ja&&(!Yn.isFetchedAfterMount||!wn.isFetchedAfterMount))&&!(ja&&Jt.current)&&ja&&(Yn.isError||wn.isError)){kt("error"),hs("Paperclip couldn’t check for an existing connection. Try again."),be("key");return}}},[v,K,Yn.isError,Yn.isFetchedAfterMount,Yn.data,wn.isError,wn.isFetchedAfterMount,rr.data?.configured,rr.isLoading,js,i,le?.slug,Qr,Dt.data,Dt.isLoading,C,Br,as,Z,zn,G,Gs,ae,c,oe,F,te]),(0,m.useEffect)(()=>{Zs.current=null,pr(null)},[G]),(0,m.useEffect)(()=>{const yt=Cn??as;if(!yt||!le||Zs.current===yt.id)return;const Ne=V8(yt),at=typeof Ne.sourceTemplateKey=="string"?Ne.sourceTemplateKey:null;if(at&&at!==le.slug)return;const It=typeof Ne.connectionMethodKey=="string"?Ne.connectionMethodKey:null,ps=It?kw(le,i).find(ja=>ja.key===It)??null:null;if(ye(yt.name||le.name),ps){Fe(ps.key);const ja=Ne.methodConfig&&typeof Ne.methodConfig=="object"?Ne.methodConfig:{};Ts({...ZS(ps),...Object.fromEntries(Object.entries(ja).filter(ia=>typeof ia[1]=="string"||typeof ia[1]=="boolean"))})}const Bs=Ne.oauth&&typeof Ne.oauth=="object"?Ne.oauth:null;Bs?.clientRegistrationSource==="manual"&&typeof Bs.clientId=="string"&&fe(Bs.clientId),se==="failed"||se==="denied"?(kt("error"),hs(zte(se,ee))):(kt("entry"),hs(null)),be("key"),Zs.current=yt.id,pr(yt.id)},[i,le,ee,se,Cn,as]);const zi=je({mutationFn:r(async yt=>{const{result:Ne,enabled:at}=yt,It=Object.entries(at).filter(([,ia])=>ia).map(([ia])=>ia),ps=Wje(Ne,ia=>!!at[ia]),Bs=Yt==="all"?"all_agents":{agentIds:Array.from(vt)},ja=await es.finishApp(R,Ne.connectionId,{enabledCatalogEntryIds:It,askFirstCatalogEntryIds:ps,...er?{agentInstructions:er}:{},access:Bs,...c?{preserveExistingAccess:!0}:{}});return await ar(Ne.connectionId),ja},"mutationFn"),onSuccess:r(async(yt,Ne)=>{await k.invalidateQueries({queryKey:["tools"]}),await k.invalidateQueries({queryKey:P.apps.attention(R)}),Ht("success"),x?.({connectionId:Ne.result.connectionId})},"onSuccess"),onError:r(yt=>{Ht("key"),$({title:"Couldn’t finish setup",body:yt instanceof Error?yt.message:"Please try again.",tone:"error"})},"onError")});if(!R)return(0,t.jsx)("div",{className:"p-6 text-sm text-muted-foreground",children:"Select an organization to connect apps."});if((G||Z)&&(wn.isError||Yn.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[yt,Ne]=await Promise.all([wn.refetch(),Yn.refetch()]);!yt.isError&&!Ne.isError&&(hs(null),kt("entry"))},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(G&&wn.isFetchedAfterMount&&!Cn)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(Z&&wn.isFetchedAfterMount&&Yn.isFetchedAfterMount&&(!as||!zn))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:as?"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((G||Z)&&Dt.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(()=>{Dt.refetch()},"onClick"),children:"Try again"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>C("/apps"),"onClick"),children:"Back to apps"})]})]});if(Z&&xr===Z)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(G&&(!wn.isFetchedAfterMount||Dt.isLoading||!le||qr!==Cn?.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)(gn,{className:"h-8 w-48"}),(0,t.jsx)(gn,{className:"h-40 w-full rounded-xl"})]});if(Z&&(!wn.isFetchedAfterMount||!Yn.isFetchedAfterMount||Dt.isLoading||ae&&!le))return(0,t.jsxs)("div",{className:"mx-auto max-w-xl space-y-4","aria-label":"Loading retained connection setup",children:[(0,t.jsx)(gn,{className:"h-8 w-48"}),(0,t.jsx)(gn,{className:"h-40 w-full rounded-xl"})]});if(rs&&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)(N9,{choices:h.map(yt=>({id:yt.id,name:yt.name,description:yt.status==="active"&&yt.enabled?"Ready to use":"Setup needs attention"})),pendingId:Os,onSelect:r(async yt=>{Us(yt),fr(null);try{await f(yt)}catch(Ne){fr(Ne instanceof Error?Ne.message:"Couldn’t use this connection."),Us(null)}},"onSelect")}),Ps?(0,t.jsx)(da,{tone:"danger",className:"mt-4",children:Ps}):null,(0,t.jsxs)("div",{className:"mt-5 flex flex-wrap gap-2",children:[(0,t.jsx)(L,{type:"button",variant:"outline",onClick:r(()=>Ls(!1),"onClick"),children:p?"Review connection setup":"Connect new"}),N?(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:N,children:"Cancel"}):null]})]});const Lo=kw(le,i),Pi=Nr?[Nr]:Lo,Me=le?js?Pi.find(yt=>yt.key===js)??null:Pi[0]??null:null,Ns=le?Me?.auth??"none":De==="none"?"none":De==="oauth"?"oauth":"api_key",on=ge==="key"?((yt,Ne)=>(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ESe,{extra:yt,forceOpen:Ne,companyId:R,sentence:e6({grantKind:dn,authKind:Ns,installChoice:Yt,installCount:vt.size,lockedAgentId:c??null,preserveAgentAccess:!!(ms&&(we||as))}),notice:[Dt.data?.capabilities?.canCreateOrganizationGrant===!1?Dt.data.capabilities.organizationGrantReason??"Only a connection manager can share this credential with the organization.":null,Dt.data?.capabilities?.canSetCompanyInstall===!1?Dt.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(at=>!!at),authKind:Ns,grantKinds:fn?[fn]:Me?.grantKinds,grantKind:dn,setGrantKind:wt,installChoice:Yt,setInstallChoice:Zt,installAgentIds:vt,setInstallAgentIds:$e,lockedAgentId:c,capabilities:Dt.data?.capabilities,githubIdentity:le?.slug==="github",identityLoading:!!ms&&Ut,preserveAgentAccess:!!(ms&&(we||as)),disabled:ca.isPending||zt.isPending},"connection-defaults"),le&&rn&&er&&(0,t.jsx)("div",{className:"mt-6",children:(0,t.jsx)(k9,{provider:le.name,template:rn,value:er,onChange:r(at=>Wt({slug:le.slug,value:at}),"onChange"),disabled:ca.isPending||zt.isPending})}),e&&(0,t.jsx)("div",{className:"mt-6",children:e})]})):null,ya=ms&&ei&&Jw(ei)?ei:null,Ha=ya&&ms?(0,t.jsx)(Zq,{entry:ms,method:ya,callbackUrl:SSe(),clientId:ns,onClientIdChange:fe,clientSecret:ct,onClientSecretChange:Ue,required:!1}):null,qa=on?.()??null,li=Ha?on?.(Ha,ht==="error"||ns.trim().length>0)??null:qa,Ba=!!(ms&&ge==="key"&&(Ae||ht!=="entry")),yl=!!(ge==="key"&&le&&Cr&&!Qr&&rr.data?.configured===!0),ba=!!(ge==="key"&&le&&Cr&&!Qr&&(rr.isLoading||rr.isError||rr.data?.configured!==!0));if(Ba&&ms)return(0,t.jsx)(Jq,{entry:ms,resuming:!!G,phase:ht,error:Rs,recoveryActions:ee==="github_installation_required"?{installationUrl:ne,managementUrl:he}:void 0,authorizationHost:jn,authorizationUrl:Tr,guidance:le?.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(yt=>(0,t.jsx)("li",{children:yt},yt))})]}):null,defaults:li,settingsValid:n&&Dr,onOpenAuthorization:kr,onRetry:r(async()=>{const yt=!an.current;an.current=!0,hs(null),kt("starting");const Ne=Gt?.connection??we;if(Ne&&Ha&&ns.trim()){Xs.current=Ne.id,Ei(ms);return}if(Ne){_n(Ne);return}if(yt&&!G&&!Yn.isError&&!wn.isError){Ei(ms);return}Jt.current=!0;try{const[at,It]=await Promise.all([Yn.refetch(),wn.refetch()]);if(at.isError||It.isError){kt("error"),hs("Paperclip couldn’t check for an existing connection. Try again.");return}const ps=(G?(It.data?.connections??[]).find(Bs=>Bs.id===G&&Bs.authKind==="oauth")??null:null)??Qte(Q,at.data?.applications??[],It.data?.connections??[],U?{applicationId:ie.applicationId,draftOnly:!0}:{});ps&&!G&&wt(ps.credentialPolicy==="per_user"?"user":ps.credentialPolicy==="per_agent"?"agent":"organization"),ps?_n(ps):ca.mutate(ms)}finally{Jt.current=!1}},"onRetry"),onBack:r(()=>{ut.current?.abort(),kt("entry"),hs(null),tt()},"onBack"),onCancel:r(()=>{ut.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});if(Ee&&!le&&Ie&&ge==="key")return(0,t.jsx)(Jq,{identity:{name:rt.trim()||S1(Ie)||"this server",unverifiedHost:S1(Ie)},steps:{labels:Kte,activeIndex:Wte.key},phase:ht,error:Rs,authorizationHost:jn,authorizationUrl:Tr,defaults:qa,onOpenAuthorization:kr,onRetry:r(()=>{hs(null);const yt=Gt?.connection;if(yt){kt("starting"),_n(yt);return}Je(!1),kt("entry")},"onRetry"),onBack:r(()=>{ut.current?.abort(),Je(!1),kt("entry"),hs(null)},"onBack"),onCancel:r(()=>{ut.current?.abort(),(N??(()=>C("/apps")))()},"onCancel")});const Hi=Gt?.application.name??le?.name??(rt.trim()||z$(Ie)||"this app"),Go=ce?xs.filter(yt=>kw(yt,i).length>0):xs,$o=te?Dt.data?.apps.find(yt=>yt.slug==="zapier")??null:null,rl=(as?.connectionPurpose==="ai"?gJ.safeParse(as.config?.ai).data:void 0)??le?.methods.find(yt=>yt.key===js)?.ai??(!js&&le?.methods.every(yt=>yt.ai)?le.methods[0]?.ai:void 0),Oo=le?w?.({app:le,name:Se||le.name,grantKind:dn,agentIds:[...vt],allAgents:Yt==="all",onBack:r(()=>tt(),"onBack")})??(rl&&R?(0,t.jsx)(t.Fragment,{children:(0,t.jsx)(w5,{companyId:R,provider:rl.provider,fixedMethod:!!(v&&v.mode!=="responsible_user"),initialMethod:as?.connectionPurpose==="ai"?(as.config?.ai).method:rl.method,connectionId:as?.connectionPurpose==="ai"?as.id:void 0,name:as?.connectionPurpose==="ai"?as.name:Se||`My ${le.name} ${rl.method==="subscription"?"subscription":"API"}`,ownership:(as?.connectionPurpose==="ai"?as.credentialPolicy==="shared":dn==="organization")?"shared":"personal",agentIds:[...vt],allAgents:Yt==="all",onCancel:r(()=>N?N():C("/apps"),"onCancel"),onComplete:r(yt=>{x?.({connectionId:yt.connectionId}),x||C(`/apps/${yt.connectionId}/permissions`)},"onComplete")})}):void 0):void 0,Qo=as?.connectionPurpose==="ai"?["Reconnect account"]:Oo!==void 0?["Connect account"]:te?Kat:le&&Pi.length>1?["Choose connection"]:le&&Pi[0]?.auth==="oauth"?["Sign in"]:zC(le,js)?["Share sheet"]:le?["Add your key"]:Kte,Rc=as?.connectionPurpose==="ai"?0:(te||le)&&ge!=="gallery"&&ge!=="success"?Uat[ge]:ge==="success"?Qo.length:Wte[ge];return(0,t.jsxs)("div",{className:"max-w-5xl",children:[ge!=="success"&&!(a&&ge==="gallery")&&(0,t.jsx)(LM,{subtitle:ge==="gallery"?ce?"Choose a reviewed app to connect through Vercel.":"Pick the app you want your agents to use.":Qo.length<=1?void 0:`Step ${Rc+1} of ${Qo.length}`,step:ge,activeIndex:Rc,labels:Qo,appIdentity:te?{name:"Zapier",logoUrl:$o?.branding.logoUrl??null,darkLogoUrl:$o?.branding.darkLogoUrl??null}:le&&ge!=="gallery"?{name:le.name,logoUrl:le.branding.logoUrl,darkLogoUrl:le.branding.darkLogoUrl??null}:void 0,unverifiedHost:!le&&!te&&ge!=="gallery"?S1(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)(Jat,{loading:Dt.isLoading,initialLink:Ie,apps:Go,vercelConnect:ce,vercelConnectAvailability:Dt.data?.credentialSources?.vercelConnect??null,byo:me,byoOnly:a,source:E.get("source"),onPick:hn,onUseLink:r(yt=>{const Ne=d3(yt,xs);ue(null),ye(""),Ke(yt),dt(Ne?.name??z$(yt)??""),ze(!1),bt(""),He({}),ds(""),xe(null),$e(new Set(c?[c]:[])),Zt(c?"specific":"all"),wt(Br??(c?"user":"organization")),be("key")},"onUseLink")}),yl&&le?(0,t.jsxs)("div",{className:"mx-auto max-w-xl rounded-xl border border-border bg-card p-6",children:[(0,t.jsxs)("h2",{className:"text-lg font-semibold text-foreground",children:[le.name," sign-in is unavailable"]}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["This instance is connected to Paperclip, but ",le.name," sign-in is not currently available. Try again shortly or contact your instance administrator."]}),Bn?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Fe(Bn.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:tt,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:Dt.isFetching,onClick:r(()=>{Dt.refetch()},"onClick"),children:[Dt.isFetching?(0,t.jsx)(nt,{className:"h-4 w-4 animate-spin"}):null,"Try again"]})]})]}):ge==="key"&&le&&ba?(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)(Q0,{className:"h-5 w-5"})}),(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"Connect with Paperclip"}),(0,t.jsxs)("p",{className:"mt-2 text-sm text-muted-foreground",children:["You must connect this instance to Paperclip to connect to ",le.name," (you only need to do this once)."]})]})]}),Bn?(0,t.jsxs)(L,{type:"button",variant:"link",className:"mt-4 h-auto p-0 text-xs",onClick:r(()=>Fe(Bn.key),"onClick"),children:["Use your own ",le.name," OAuth app"]}):null,rr.isError||sr?(0,t.jsx)(da,{tone:"danger",className:"mt-4",children:sr??"Paperclip couldn’t check Cloud registration. Try again."}):null,Rr?(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:Rr,target:"_blank",rel:"noopener noreferrer",children:"Open authorization in a new tab"})]}):null,qa,(0,t.jsxs)("div",{className:"mt-6 flex items-center justify-between gap-3",children:[(0,t.jsx)(L,{type:"button",variant:"ghost",onClick:tt,children:"Back"}),(0,t.jsxs)(L,{type:"button",disabled:rr.isLoading||dr.isPending,onClick:r(()=>{Va(null),nr(),$s(),dr.mutate()},"onClick"),children:[dr.isPending?(0,t.jsx)(nt,{className:"h-4 w-4 animate-spin"}):null,rr.data?.status==="pending"?"Continue":"Connect with Paperclip"]})]})]})}):ge==="key"&&le&&Oo!==void 0?Oo:ge==="key"&&le?(0,t.jsx)(eit,{settingsValid:n&&Dr,entry:le,error:ca.isError?ca.error instanceof Error?ca.error.message:"Please check your key and try again.":null,values:_e,onChange:He,oauthClientId:ns,onOAuthClientIdChange:fe,oauthClientSecret:ct,canReuseOAuthClientSecret:!!(Er?.config?.oauth&&Er.config.oauth.clientId===ns.trim()&&Er.hasSavedOAuthClientSecret),onOAuthClientSecretChange:Ue,credentialSource:i,vercelConnector:Et,onVercelConnectorChange:$t,vercelConnectAvailability:Dt.data?.credentialSources?.vercelConnect??null,methodKey:js,onMethodChange:r(yt=>{Fe(yt?.key??""),!Br&&yt?.grantKinds&&!yt.grantKinds.includes(Ft)&&wt(q$(yt,!!c)),He({}),fe(""),Ue(""),$t(""),Ts(ZS(yt))},"onMethodChange"),configValues:Cs,onConfigChange:Ts,googleSheetsLinks:Ct,googleSheetsError:Oe,onGoogleSheetsLinksChange:r(yt=>{ds(yt),xe(null)},"onGoogleSheetsLinksChange"),submitting:ca.isPending,renderDefaults:on??void 0,onBack:tt,onConnect:r(()=>{if(zC(le,js)){const at=eq(Ct);if(at.invalidCount>0){xe("That doesn't look like a Google Sheets link.");return}if(at.ids.length===0){xe("Paste at least one Google Sheets link.");return}}const yt=O2(le,js||null),Ne=!!(yt?.credentialFields?.length||yt?.tenantFields?.some(at=>!at.hidden)||yt?.extensionFields?.some(at=>!at.hidden));if(yt&&tp(yt)&&we&&!Ne&&!ns.trim()){an.current=!0,hs(null),kt("starting"),_n(we);return}yt&&tp(yt)&&(an.current=!0,hs(null),kt("starting")),Ei()},"onConnect")}):null,ge==="key"&&!le&&!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)(gn,{className:"h-6 w-2/3 rounded-md"}),(0,t.jsx)(gn,{className:"mt-3 h-4 w-full rounded-md"}),(0,t.jsx)(gn,{className:"mt-8 h-11 w-40 rounded-md"})]}),ge==="key"&&!le&&Ie&&!te&&(0,t.jsx)(Xat,{link:Ie,name:rt,needsKey:de,keyValue:gt,onKeyChange:bt,authMode:De,onAuthModeChange:r(yt=>{Qe(yt),ot(null),yt!=="auto"&&ze(!1),yt!=="bearer"&&yt!=="auto"&&bt("")},"onAuthModeChange"),headers:mt,onHeadersChange:r(yt=>{Ye(yt),ot(null)},"onHeadersChange"),oauthClientId:it,onOAuthClientIdChange:Nt,oauthClientSecret:Ze,onOAuthClientSecretChange:Pe,advancedOpen:Ce,onAdvancedOpenChange:Ve,guidance:Ge,matchedEntry:br,onUseMatchedEntry:br?()=>hn(br):void 0,submitting:ca.isPending||Ee,defaults:qa,onBack:tt,onConnect:r(()=>{ot(null),ca.mutate(void 0)},"onConnect")}),ge==="key"&&!le&&te&&(0,t.jsx)(Yat,{link:Ie,onLinkChange:Ke,submitting:ca.isPending,defaults:qa,onBack:tt,onConnect:r(()=>ca.mutate(void 0),"onConnect")}),ge==="success"&&(0,t.jsx)(rit,{appName:Hi,logoUrl:le?.branding.logoUrl,darkLogoUrl:le?.branding.darkLogoUrl,summary:nit({grantKind:dn,authKind:Ns,installChoice:Yt,installCount:vt.size,enabledCount:Object.values(os).filter(Boolean).length}),statedDefault:e6({grantKind:dn,authKind:Ns,installChoice:Yt,installCount:vt.size,lockedAgentId:c??null}),onDone:N??(()=>C("/apps"))})]})}r(Qat,"StandardConnectionSetupFlow");function Jq({entry:e,identity:s,resuming:n=!1,phase:a,error:i,recoveryActions:o,authorizationHost:l,authorizationUrl:c,steps:d={labels:Wat,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)(LM,{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)(pc,{className:"h-5 w-5 text-destructive"}):a==="entry"?(0,t.jsx)(dd,{className:"h-5 w-5 text-muted-foreground"}):(0,t.jsx)(nt,{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)(DM,{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(Jq,"OAuthConnectStateScreen");function Yat({link:e,onLinkChange:s,submitting:n,defaults:a,onBack:i,onConnect:o}){const l=Xq(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)(pt,{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)(nt,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Checking…":"Check link"]})]})]})}r(Yat,"ZapierConnectStep");function Jat({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=Xq(f),I=C?d3(C,n):null,T=c==="zapier",R=r(()=>{const A=Xq(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)(gn,{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)(da,{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)(Gr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,t.jsx)(pt,{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=NSe(A.slug,A.description),M=nA(A),$=M.length===0||M.every(B=>B.auth==="oauth"&&!tp(B)&&!Jw(B)),E=A.availability?.available===!1||o&&l?.available!==!0;return(0,t.jsxs)("button",{type:"button",disabled:$||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",$||E?"cursor-not-allowed opacity-60":"hover:border-foreground/30 hover:bg-accent/40"),children:[(0,t.jsx)(Vo,{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."}):$?(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)(pc,{className:"h-4 w-4 text-muted-foreground"}),T?"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:T?"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."}),!T&&(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)(Vo,{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"){R();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)(pt,{ref:w,type:T||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"&&R()},"onKeyDown"),placeholder:T?"https://mcp.zapier.com/api/v1/connect?token=…":"https://example.com/actions",className:"h-10"}),(0,t.jsx)(L,{type:"button",variant:"outline",onClick:R,children:"Continue"})]}),v&&(0,t.jsx)("div",{className:"text-xs text-destructive",children:v})]})]})]})}r(Jat,"GalleryStep");function Xq(e){try{const s=new URL(e.trim());return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.toString()}catch{return null}}r(Xq,"normalizeAppLink");function Xat({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=S1(e),T=o==="custom_headers"?CSe(c):null,R=Eat({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"?xpe(e):e,M=r(($,E)=>{d(c.map(B=>B.id===$?{...B,...E}:B))},"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)(DM,{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)(Vo,{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)(da,{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)(pt,{id:"generic-mcp-key",type:"password",autoComplete:"off",value:a,onChange:r($=>i($.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)(sl,{open:x,onOpenChange:b,children:[(0,t.jsxs)(Hl,{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)(nl,{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:Yte.map($=>(0,t.jsx)(Zat,{label:$.label,selected:o===$.mode,onClick:r(()=>l($.mode),"onClick")},$.mode))}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:Yte.find($=>$.mode===o)?.hint}),o==="custom_headers"?(0,t.jsxs)("div",{className:"space-y-3",children:[c.map($=>(0,t.jsxs)("div",{className:"flex items-start gap-2",children:[(0,t.jsx)(pt,{value:$.name,onChange:r(E=>M($.id,{name:E.target.value}),"onChange"),placeholder:"Header name","aria-label":"Header name",className:"h-10 font-mono"}),(0,t.jsx)(pt,{type:"password",autoComplete:"off",value:$.value,onChange:r(E=>M($.id,{value:E.target.value}),"onChange"),placeholder:"Value","aria-label":$.name.trim()?`Value for ${$.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!==$.id)),"onClick"),disabled:c.length===1,children:"Remove"})]},$.id)),(0,t.jsx)(L,{type:"button",variant:"outline",size:"sm",onClick:r(()=>d([...c,Yq()]),"onClick"),children:"Add another header"}),T?(0,t.jsx)("p",{className:"text-xs text-destructive",children:T}):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)(pt,{id:"generic-mcp-client-id",value:u,onChange:r($=>h($.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)(pt,{id:"generic-mcp-client-secret",type:"password",autoComplete:"off",value:p,onChange:r($=>f($.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||!R||!!T,children:[w&&(0,t.jsx)(nt,{className:"mr-2 h-4 w-4 animate-spin"}),w?"Checking…":"Check link"]})]})]})}r(Xat,"LinkConnectStep");var Yte=[{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 Zat({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(Zat,"SegmentedOption");function eit({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:T,onConnect:R}){const A=(0,m.useMemo)(()=>kw(s,h),[h,s]),D=b?A.find(De=>De.key===b)??null:mk(A),M=(0,m.useMemo)(()=>A.some(De=>De.capabilityProfile)?Array.from(A.reduce((De,Qe)=>{const mt=Qe.capabilityProfile.key,Ye=De.get(mt);return Ye?Ye.methods.push(Qe):De.set(mt,{key:mt,label:Qe.capabilityProfile?.label??Qe.label??Qe.key,description:Qe.capabilityProfile?.description??Qe.whenToUse,methods:[Qe]}),De},new Map)).map(([,De])=>De):[],[A]),$=D?.capabilityProfile?.key??D?.key??"",E=M.map(De=>De.key).join("|"),[B,z]=(0,m.useState)($||mk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""));(0,m.useEffect)(()=>{if($){z($);return}z(De=>M.some(Qe=>Qe.key===De)?De:mk(A)?.capabilityProfile?.key||(M.length===1?M[0].key:""))},[E,M,A,$]);const q=M.length>1?M.find(De=>De.key===B)?.methods??[]:A,U=(D?.credentialFields??[]).map(De=>({...De,configPath:ppe(De,D),helpUrl:D?.consoleLinks?.keys??D?.consoleLinks?.docs??""})),F=D?.credentialSources?.vercelConnect??null,K=h==="vercel_connect",G=K||U.every(De=>De.required===!1||(a[De.configPath]?.trim().length??0)>0),se=Jw(D),ee=se&&!tp(D),ne=K||!ee||o.trim().length>0&&(!D?.oauthClientSecretRequired||d||c.trim().length>0),he=!K||p.trim().length>0,Z=D?.auth==="oauth"&&se?SSe():null,re=[...D?.tenantFields??[],...D?.extensionFields??[]],ce=re.filter(De=>!De.hidden),H=ce.filter(De=>De.advanced!==!0),Q=ce.filter(De=>De.advanced===!0),Y=re.every(De=>{if(!De.required)return!0;const Qe=j[De.key];return typeof Qe=="boolean"||typeof Qe=="string"&&Qe.trim().length>0}),te=D?.configRequirements?.atLeastOneOf??[],ae=te.length===0||te.some(De=>{const Qe=j[De];return typeof Qe=="string"&&Qe.trim().length>0}),me=(M.length<=1||!!B)&&(q.length<=1?!!D:!!b),oe=s.availability?.robotEmail??null,ie=s.availability?.available===!1,ge=!K&&se&&!ee,be=M.length>1||q.length>1,le=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)(mm,{ariaLabel:`Access level for ${s.name}`,className:"mt-2",value:B,onValueChange:r(De=>{const Qe=M.find(mt=>mt.key===De);Qe&&(z(De),v(q8(Qe.methods)))},"onValueChange"),options:M.map(De=>({value:De.key,title:De.label,description:De.description}))}),!B&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Choose an access level to continue."})]}):null,ue=q.find(De=>De.oauthStrategy==="paperclip_cloud_connector"),Se=ue&&q.find(De=>Jw(De)&&!tp(De)),ye=D?.key===Se?.key,Ie=(0,m.useId)(),Ke=ue&&Se&&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":ye,"aria-controls":Ie,disabled:C,onClick:r(()=>v(ye?ue:Se),"onClick"),children:ye?"Use Paperclip instead":`Use your own ${QDe(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)(mm,{ariaLabel:`How to connect ${s.name}`,className:"mt-2",value:b,onValueChange:r(De=>{const Qe=q.find(mt=>mt.key===De);Qe&&v(Qe)},"onValueChange"),options:q.map(De=>({value:De.key,title:De.label??(De.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,rt=Q.length>0||ge||be,dt=ye||!me,de=rt?(0,t.jsxs)("div",{className:"space-y-6",children:[le,Ke,Q.map(De=>(0,t.jsx)(Jte,{field:De,value:j[De.key],onChange:r(Qe=>N({...j,[De.key]:Qe}),"onChange")},De.key)),ge?(0,t.jsx)(Zq,{entry:s,method:D,callbackUrl:Z,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!1}):null]}):null,ze=I?.(de,dt)??null;if(zC(s,D)){const De=eq(w),Qe=e&&!ie&&!!oe&&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:[le,oe?(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:oe,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:oe}),(0,t.jsx)(RSe,{value:oe,ariaLabel:"Copy sharing email"})]}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below."})]}):(0,t.jsx)("div",{className:"rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground",children:"Google Sheets is not available on this instance yet."}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:"Paste links to the sheets you shared"}),(0,t.jsx)(Tn,{value:w,onChange:r(mt=>S(mt.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:De.ids.length>0?`${De.ids.length} ${De.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})]})]}),ze,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:T,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:R,disabled:C||!Qe,children:[C&&(0,t.jsx)(nt,{className:"mr-2 h-4 w-4 animate-spin"}),C?"Checking…":"Connect"]})]})]})}const gt=D?.connectorProfile==="asana.mcp",bt=gt?null:D?.consoleLinks?.docs??s.docsUrl;return(0,t.jsxs)("div",{className:"mx-auto max-w-xl",children:[bt?(0,t.jsx)("div",{className:"mb-4 flex justify-end",children:(0,t.jsxs)("a",{href:bt,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:[gt?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Sign in with Asana to choose your workspace and connect it to Paperclip."}):null,D?.capabilityProfile&&(0,t.jsxs)("p",{className:"text-sm text-muted-foreground",children:[D.capabilityProfile.label,": ",D.capabilityProfile.description]}),K&&F&&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)(pt,{id:"vercel-connect-connector",value:p,onChange:r(De=>f(De.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)(da,{tone:"danger",children:n})}):null,H.map(De=>(0,t.jsx)(Jte,{field:De,value:j[De.key],onChange:r(Qe=>N({...j,[De.key]:Qe}),"onChange")},De.key)),!K&&D?.auth==="oauth"&&ee?(0,t.jsx)("div",{id:Ie,role:"region","aria-label":"Your OAuth app",children:(0,t.jsx)(Zq,{entry:s,method:D,callbackUrl:Z,clientId:o,onClientIdChange:l,clientSecret:c,onClientSecretChange:u,required:!0})}):null,K||!D||U.length===0?null:U.map(De=>(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:Dte(s.name,De.label,U.length)}),(0,t.jsx)(pt,{type:De.type==="text"&&De.secret===!1?"text":"password","aria-label":Dte(s.name,De.label,U.length),autoComplete:"off",value:a[De.configPath]??"",onChange:r(Qe=>i({...a,[De.configPath]:Qe.target.value}),"onChange"),placeholder:De.type==="text"&&De.secret===!1?De.placeholder:"••••••••••••••••",className:"mt-2 h-11 font-mono"}),De.helperMd&&(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:De.helperMd}),De.helpUrl&&(0,t.jsxs)("a",{href:De.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"})]})]},De.configPath))]}),ze,(0,t.jsxs)("div",{className:"mt-8 flex items-center justify-between",children:[(0,t.jsx)(L,{variant:"ghost",onClick:T,disabled:C,children:"Back"}),(0,t.jsxs)(L,{onClick:R,disabled:C||!e||!me||!G||!ne||!he||!Y||!ae,children:[C&&(0,t.jsx)(nt,{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(eit,"KeyStep");function RSe({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)(vs,{className:"mr-2 h-4 w-4"}):(0,t.jsx)(Ar,{className:"mr-2 h-4 w-4"}),n?"Copied":a?"Copy failed":"Copy"]})}r(RSe,"CopyValueButton");function Zq({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)(RSe,{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)(pt,{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)(pt,{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(Zq,"OAuthClientFields");function Jte({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)(ui,{checked:s===!0,onCheckedChange:n})]}):(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"text-sm font-medium text-foreground",children:e.label}),e.type==="textarea"?(0,t.jsx)(Tn,{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),placeholder:e.placeholder,className:"mt-2 min-h-24"}):e.type==="select"?(0,t.jsxs)("select",{value:typeof s=="string"?s:"",onChange:r(a=>n(a.target.value),"onChange"),className:"mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",children:[(0,t.jsx)("option",{value:"",disabled:!0,children:"Select an option"}),(e.options??[]).map(a=>(0,t.jsx)("option",{value:a.value,children:a.label},a.value))]}):(0,t.jsx)(pt,{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(Jte,"MethodConfigField");function tit({companyId:e,...s}){const n=X({queryKey:P.agents.list(e),queryFn:r(()=>Lt.list(e),"queryFn")});return(0,t.jsx)(CW,{...s,agents:(n.data??[]).filter(a=>a.status!=="terminated"),agentsLoading:n.isLoading})}r(tit,"AccessStep");function CW({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,T=I?e.filter(U=>I.includes(U.id)):e,R=p?.canSetCompanyInstall??!0,A=p?.canCreateOrganizationGrant??!0,D=n!=="none",M=a??["user","organization"],$=(!D||i==="user"||i==="agent"||A)&&(j?!0:h?d.has(h):i==="agent"?l==="specific"&&d.size===1:l==="all"?R:d.size>0),E=h?e.find(U=>U.id===h)?.name??"the requesting agent":null,B=f?"Connect GitHub as":"Which humans can use this credential?",z=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?z:"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:B}),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)(gn,{className:"h-20 w-full rounded-md"}),(0,t.jsx)(gn,{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)(Th,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):M[0]==="agent"?(0,t.jsx)(Ji,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):(0,t.jsx)(sk,{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)(mm,{ariaLabel:f?B:"Which humans can use this credential?",className:"mt-4 sm:grid-cols-2",value:i,onValueChange:r(U=>{const F=U;o(F),F==="agent"&&(c("specific"),d.size>1&&u(new Set([[...d][0]])))},"onValueChange"),options:[{value:"user",title:f?"My GitHub account":"Just me",description:f?"Agents use it only for runs where you are the responsible person.":void 0,icon:(0,t.jsx)(Th,{className:"h-4 w-4","aria-hidden":"true"})},{value:"agent",title:"A dedicated account for an agent",description:f?"That agent always uses this account, regardless of who starts the run.":void 0,icon:(0,t.jsx)(Ji,{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)(sk,{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:z}),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)(sk,{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)(mm,{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)(Ji,{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)(sit,{}),accessibleLabel:R?"Any agent":`Any agent. Unavailable: ${p?.companyInstallReason??"Only someone who can configure this connection can choose this."}`,tooltip:R?void 0:p?.companyInstallReason??"Only someone who can configure this connection can choose this.",disabled:!R}]}),!j&&!h&&l==="specific"?(0,t.jsx)("div",{className:"mt-3",children:(0,t.jsx)(Yy,{agents:T,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:!$||v||N,children:[N?(0,t.jsx)(nt,{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(CW,"AccessStepContent");function e6(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(e6,"connectionDefaultSummarySentence");function ESe({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)(sl,{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)(Hl,{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)(nl,{children:(0,t.jsxs)("div",{className:"mt-3 space-y-6",children:[i,s?(0,t.jsx)(CW,{...c,agents:s,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")}):(0,t.jsx)(tit,{...c,companyId:e,bare:!0,hideFooter:!0,submitLabel:"",onBack:r(()=>{},"onBack"),onContinue:r(()=>{},"onContinue")})]})})]})}r(ESe,"ConnectionAccessDefaults");function sit(){return(0,t.jsxs)("span",{className:"relative block h-4 w-5","aria-hidden":"true",children:[(0,t.jsx)(Ji,{className:"absolute left-0 top-0 h-3.5 w-3.5"}),(0,t.jsx)(Ji,{className:"absolute bottom-0 right-0 h-3.5 w-3.5"})]})}r(sit,"BotGroupIcon");function nit(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(nit,"accessSummaryLines");function rit({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)(vs,{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)(Vo,{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(rit,"ConnectionSetupCompletionScreen");function PSe(){const{newProjectOpen:e,closeNewProject:s}=AI(),{selectedCompanyId:n}=gs();return n&&e?(0,t.jsx)(ait,{companyId:n,onClose:s},n):null}r(PSe,"NewProjectDialog");function ait({companyId:e,onClose:s}){const n=Mt(),[a,i]=(0,m.useState)(""),[o]=(0,m.useState)(()=>u3[Math.floor(Math.random()*u3.length)]),[l,c]=(0,m.useState)([]),[d,u]=(0,m.useState)(!1),h=(0,m.useRef)(null),p=je({mutationFn:r(()=>ma.create(e,{name:a.trim(),color:o,status:"planned",repositoryIds:l.map(f=>f.id)}),"mutationFn"),onSuccess:r(f=>{H0(f.id,e),n.invalidateQueries({queryKey:P.projects.all(e)}),s()},"onSuccess")});return(0,t.jsx)(Vs,{open:!0,onOpenChange:r(f=>{!f&&!p.isPending&&s()},"onOpenChange"),children:(0,t.jsx)(Qs,{showCloseButton:!1,"aria-describedby":void 0,className:"flex max-h-(--sz-calc-18) flex-col gap-0 overflow-hidden p-0 shadow-sm sm:max-w-lg",onOpenAutoFocus:r(f=>{f.preventDefault(),h.current?.focus()},"onOpenAutoFocus"),children:d?(0,t.jsxs)("div",{className:"min-h-0 overflow-y-auto p-5",children:[(0,t.jsx)(Js,{className:"sr-only",children:"Connect GitHub"}),(0,t.jsx)(e4,{host:"dialog",serviceSlug:"github",forceNewConnection:!0,onCancel:r(()=>u(!1),"onCancel"),onComplete:r(()=>{n.invalidateQueries({queryKey:w9(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)(Js,{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)(Vn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-input px-3 focus-within:border-ring focus-within:ring-1 focus-within:ring-ring",children:[(0,t.jsx)(wm,{color:o,size:"sm"}),(0,t.jsx)("input",{ref:h,"aria-label":"Project name",value:a,disabled:p.isPending,onChange:r(f=>i(f.target.value),"onChange"),placeholder:"Project name",required:!0,className:"h-10 w-full min-w-0 border-0 bg-transparent text-base outline-none placeholder:text-muted-foreground md:text-sm"})]})]}),(0,t.jsx)("div",{role:"region","aria-label":"Source repositories",tabIndex:0,className:"min-h-0 overflow-y-auto overscroll-contain px-5 pb-1 outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",children:(0,t.jsx)(Kje,{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(ait,"NewProjectForm");var sg={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 MSe(e){return{"--sc":`var(${e})`}}r(MSe,"scStyle");function iit(e){const s=e.replace(/_/g," ");return s.charAt(0).toUpperCase()+s.slice(1)}r(iit,"sentenceCaseStatus");function Za({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",xz[e]??"bg-muted text-muted-foreground"),children:s??e.replace(/[_-]/g," ")})}r(Za,"StatusBadge$5");function DSe({status:e}){const s=mFe[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:MSe(s),children:n.replace(/_/g," ")})}r(DSe,"AgentStatusBadge");function Zh({status:e,externalConversationState:s}){const n=e==="in_review"&&s==="waiting"?"idle":e,a=oFe[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:MSe(a),children:[(0,t.jsx)(II,{status:n,size:"sm"}),iit(n)]})}r(Zh,"IssueStatusBadge");var Xte={company:"Organization",team:"Team",agent:"Agent",task:"Task"};function LSe(){const{newGoalOpen:e,newGoalDefaults:s,closeNewGoal:n}=AI(),{selectedCompanyId:a,selectedCompany:i}=gs(),o=Mt(),[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,T]=(0,m.useState)(!1),R=(0,m.useRef)(null),A=b||s.parentId||"",{data:D}=X({queryKey:P.goals.list(a),queryFn:r(()=>sg.list(a),"queryFn"),enabled:!!a&&e}),M=je({mutationFn:r(U=>sg.create(a,U),"mutationFn"),onSuccess:r(()=>{o.invalidateQueries({queryKey:P.goals.list(a)}),E(),n()},"onSuccess")}),$=je({mutationFn:r(async U=>{if(!a)throw new Error("No organization selected");return fb.uploadImage(a,U,"goals/drafts")},"mutationFn")});function E(){c(""),u(""),p("planned"),x("task"),v(""),N(!1)}r(E,"reset");function B(){!a||!l.trim()||M.mutate({title:l.trim(),description:d.trim()||void 0,status:h,level:f,...A?{parentId:A}:{}})}r(B,"handleSubmit");function z(U){U.key==="Enter"&&(U.metaKey||U.ctrlKey)&&(U.preventDefault(),B())}r(z,"handleKeyDown");const q=(D??[]).find(U=>U.id===A);return(0,t.jsx)(Vs,{open:e,onOpenChange:r(U=>{U||(E(),n())},"onOpenChange"),children:(0,t.jsxs)(Qs,{showCloseButton:!1,className:W("p-0 gap-0",j?"sm:max-w-2xl":"sm:max-w-lg"),onKeyDown:z,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)(O0e,{className:"h-3.5 w-3.5"}):(0,t.jsx)(Hy,{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(),R.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)(ud,{ref:R,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 $.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)(yr,{open:w,onOpenChange:k,children:[(0,t.jsx)(Ir,{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)(Za,{status:h})})}),(0,t.jsx)(lr,{className:"w-40 p-1",align:"start",children:Spe.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)(yr,{open:S,onOpenChange:C,children:[(0,t.jsx)(Ir,{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)(Tl,{className:"h-3 w-3 text-muted-foreground"}),Xte[f]??f]})}),(0,t.jsx)(lr,{className:"w-40 p-1",align:"start",children:_pe.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:Xte[U]??U},U))})]}),(0,t.jsxs)(yr,{open:I,onOpenChange:T,children:[(0,t.jsx)(Ir,{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)(bp,{className:"h-3 w-3 text-muted-foreground"}),q?q.title:"Parent goal"]})}),(0,t.jsxs)(lr,{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(""),T(!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),T(!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:B,children:M.isPending?"Creating…":s.parentId?"Create sub-goal":"Create goal"})})]})})}r(LSe,"NewGoalDialog");function oit(e){const s=lit(e),n=cit(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(oit,"buildAgentOnboardingPrompt");function lit(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(lit,"buildCandidateOnboardingUrls");function cit(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(cit,"buildResolutionTestUrl");var t6=[{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 Zte({ref:e,hidden:s}){return(0,t.jsx)("span",{ref:e,className:"agent-setup-logos","data-hidden":s,"aria-hidden":"true",children:t6.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(Zte,"AgentLogos");function U$(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(U$,"readLogoPositions");function Jy({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=Xfe(),[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),T=(0,m.useRef)(!1),R=(0,m.useRef)(!1),A=(0,m.useRef)(null);(0,m.useEffect)(()=>(v("idle"),R.current=!1,T.current=!1,()=>{I.current+=1}),[e]),(0,m.useEffect)(()=>{T.current||v(d)},[e,d]),(0,m.useEffect)(()=>{if(b!=="copied")return;const $=x5("--agent-setup-copied-hold");if($<=0)return;const E=window.setTimeout(()=>v("idle"),$);return()=>window.clearTimeout(E)},[b]),(0,m.useLayoutEffect)(()=>{if(!j)return;if(p||typeof Element.prototype.animate!="function"){N(null);return}let $,E=!1,B=[];const z=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()){$=requestAnimationFrame(q);return}const F=U$(U),K=S.current?.querySelectorAll(".agent-setup-logo"),G=getComputedStyle(document.documentElement).getPropertyValue("--motion-ease-out-expo").trim();B=Array.from(K??[]).map((se,ee)=>se.animate([j.origins[ee],F[ee]].map(({left:ne,top:he,transform:Z})=>({left:`${ne}px`,top:`${he}px`,transform:Z})),{duration:x5("--agent-setup-flight-duration"),easing:G,fill:"both"})),Promise.all(B.map(se=>se.finished)).then(z,()=>{})},"start");return $=requestAnimationFrame(q),window.addEventListener("resize",z),document.addEventListener("scroll",z,!0),()=>{E=!0,cancelAnimationFrame($),B.forEach(U=>U.cancel()),window.removeEventListener("resize",z),document.removeEventListener("scroll",z,!0)}},[j,p]);function D($){const E=C.current??U$(S.current??(f?k.current:w.current));C.current=null,N(!p&&E.length===t6.length?{origins:E,toPreview:$}:null),x($)}r(D,"changeOpen");async function M(){if(R.current||!e.trim())return;T.current=!0,R.current=!0;const $=++I.current;v("copying");try{await ha(e),$===I.current&&(v("copied"),u?.())}catch{$===I.current&&v("failed")}finally{$===I.current&&(R.current=!1)}}return r(M,"copyPrompt"),(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(yr,{open:f,onOpenChange:D,children:[(0,t.jsx)(Ir,{asChild:!0,children:(0,t.jsxs)(L,{type:"button",variant:i,"aria-label":a,"data-copied":b==="copied",onClick:r($=>{f?$.preventDefault():C.current=U$(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)(vs,{className:"agent-setup-check size-4"}):(0,t.jsx)(dg,{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)(Zte,{ref:w,hidden:f||!!j})})]})}),(0,t.jsxs)(lr,{side:o,align:l,collisionPadding:ym("--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($=>{$.preventDefault(),A.current?.focus()},"onOpenAutoFocus"),onFocusOutside:r($=>{R.current&&$.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)(Vn,{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)(Zte,{ref:k,hidden:!!j})}),b==="failed"?(0,t.jsx)(Tn,{"aria-label":"Setup prompt",readOnly:!0,value:e,onFocus:r($=>$.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)(vs,{className:"agent-setup-check size-4"}):(0,t.jsx)(Ar,{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,up.createPortal)((0,t.jsx)("span",{ref:S,className:"agent-setup-flight-layer","aria-hidden":"true",children:t6.map(($,E)=>(0,t.jsx)("span",{className:"agent-setup-logo agent-setup-flying-logo",style:j.origins[E],children:(0,t.jsx)("img",{src:$.src,alt:"",className:W("size-5",$.className),draggable:!1})},$.name))}),document.body)]})}r(Jy,"AgentSetupPrompt");function dit({companyId:e,onClose:s,onBack:n}){const a=Mt(),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 hr.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 hr.getInviteOnboarding(p.token).catch(()=>null);return oit({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 ha(p)}catch{f="failed"}i.current&&d(x=>x?.copyStatus==="idle"?{...x,copyStatus:f}:x)},"onSuccess")});return(0,t.jsx)(Vs,{open:!0,onOpenChange:r(p=>{p||s()},"onOpenChange"),children:(0,t.jsxs)(Qs,{className:"max-h-(--sz-calc-16) overflow-y-auto sm:max-w-2xl",children:[(0,t.jsx)(Js,{children:u?"Agent onboarding prompt":"Invite an external agent"}),(0,t.jsx)(yn,{children:u?"Send this one-time prompt to the agent that should join your organization.":"Generate a one-time onboarding prompt for an external agent. An organization admin must approve its join request before it can claim an API key."}),u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Tn,{"aria-label":"Agent onboarding prompt",readOnly:!0,value:u,className:"min-h-64 font-mono text-xs"}),c?.copyStatus==="failed"&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-muted-foreground",children:"Clipboard unavailable. Copy the prompt manually from the field above, or use the button below to try again."}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[(0,t.jsx)(L,{variant:"ghost",onClick:s,children:"Done"}),(0,t.jsx)(Jy,{prompt:u,label:"Copy onboarding prompt",title:"Invite your agent",description:"Paste this into your external agent to request access to your organization.",initialCopyStatus:c?.copyStatus,onCopied:r(()=>d(p=>p&&{...p,copyStatus:"copied"}),"onCopied")})]})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{children:"Optional message for the agent"}),(0,t.jsx)(Tn,{value:o,onChange:r(p=>l(p.target.value),"onChange"),maxLength:4e3,className:"min-h-24"})]}),h.error&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:h.error.message}),(0,t.jsxs)("div",{className:"flex justify-between gap-4",children:[(0,t.jsx)(L,{variant:"ghost",onClick:n,children:"Back"}),(0,t.jsx)(L,{disabled:h.isPending,onClick:r(()=>h.mutate(),"onClick"),children:h.isPending?"Generating…":"Generate onboarding prompt"})]})]})]})})}r(dit,"ExternalAgentInviteDialog");function $Se(){const{newAgentOpen:e,closeNewAgent:s}=AI(),{selectedCompanyId:n}=gs();return e?(0,t.jsx)(uit,{companyId:n,onClose:s},n):null}r($Se,"NewAgentDialog");function uit({companyId:e,onClose:s}){const n=Ln(),[a,i]=(0,m.useState)(!1);return a&&e?(0,t.jsx)(dit,{companyId:e,onClose:s,onBack:r(()=>i(!1),"onBack")}):(0,t.jsx)(bSe,{open:!0,onClose:s,onInvite:e?()=>i(!0):void 0,onContinue:r(o=>{s(),n(`/agents/new?${new URLSearchParams(o)}`)},"onContinue")})}r(uit,"NewAgentDialogContent");var mit=[{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 ese({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(ese,"KeyCap");function hit(){return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("div",{className:"divide-y divide-border border-t border-border",children:mit.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)(ese,{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)(ese,{children:"Esc"})," to close · Shortcuts are disabled in text fields"]})})]})}r(hit,"KeyboardShortcutsCheatsheetContent");function OSe({open:e,onOpenChange:s}){return(0,t.jsx)(Vs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Qs,{className:"sm:max-w-md gap-0 p-0 overflow-hidden",showCloseButton:!1,children:[(0,t.jsx)(xn,{className:"px-5 pt-5 pb-3",children:(0,t.jsx)(Js,{className:"text-base",children:"Keyboard shortcuts"})}),(0,t.jsx)(hit,{})]})})}r(OSe,"KeyboardShortcutsCheatsheet");var pit={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"},fit={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 xit({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",pit[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",fit[e.tone])}),(0,t.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,t.jsx)("p",{className:"text-sm font-semibold leading-5",children:e.title}),e.body&&(0,t.jsx)("p",{className:"mt-1 text-xs leading-4 opacity-70",children:e.body}),e.action&&(e.action.onClick?(0,t.jsx)("button",{type:"button",onClick:r(()=>{e.action?.onClick?.(),s(e.id)},"onClick"),className:"mt-2 inline-flex text-xs font-medium underline underline-offset-4 hover:opacity-90",children:e.action.label}):e.action.href?(0,t.jsx)(We,{to:e.action.href,onClick:r(()=>s(e.id),"onClick"),className:"mt-2 inline-flex text-xs font-medium underline underline-offset-4 hover:opacity-90",children:e.action.label}):null)]}),(0,t.jsx)("button",{type:"button","aria-label":"Dismiss notification",onClick:r(()=>s(e.id),"onClick"),className:"mt-0.5 shrink-0 rounded p-1 opacity-50 hover:bg-black/10 hover:opacity-100 dark:hover:bg-white/10",children:(0,t.jsx)(Vn,{className:"h-3.5 w-3.5"})})]})})}r(xit,"AnimatedToast");function FSe(){const e=Bve(),{dismissToast:s}=pa();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)(xit,{toast:n,onDismiss:s},n.id))})})}r(FSe,"ToastViewport");async function tse(e,s){const n=await fetch(`/api/announcements/${e}`,{credentials:"same-origin",cache:"no-store",...s});if(!n.ok)throw new un("Announcement request failed",n.status,null);return n}r(tse,"request");var sse={async current(e){const s=await(await tse("current",{signal:e})).json();return s===null?null:kLe.parse(s)},async dismiss(e,s,n){await tse(`${encodeURIComponent(e)}/dismiss`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({companyId:s})})}},s6=new Map;function _W(e){return`paperclip.announcement-dismissals.v1:${encodeURIComponent(e)}:`}r(_W,"announcementStoragePrefix");function F2(e){const s=_W(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);Npe.safeParse(o).success&&(l==="pending"||l==="synced")&&s6.set(i,l==="pending")}}catch{}for(const[a,i]of s6)a.startsWith(s)&&n.set(a.slice(s.length),i);return n}r(F2,"readAnnouncementDismissals");function K$(e,s,n){const a=`${_W(e)}${s}`;s6.set(a,n);try{return localStorage.setItem(a,n?"pending":"synced"),!0}catch{return!1}}r(K$,"saveAnnouncementDismissal");var git=3e3;function bit(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=_W(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 $=setTimeout(()=>M.abort(),1e4);try{await sse.dismiss(A,a.current.companyId,M.signal),j()&&K$(s,A,!1)}catch{j()&&!x.has(A)&&(x.add(A),a.current.onSaveFailure(D))}finally{clearTimeout($),f.delete(A)}}r(N,"sync");async function w(){for(const[A,D]of F2(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 $=!1,E=!1,B=null;const z=r(()=>{!M()||!$||!E||B&&!F2(s).has(B.id)&&(!B.expiresAt||Date.parse(B.expiresAt)>Date.now())&&o({userId:s,announcement:B})},"show");p=setTimeout(()=>{$=!0,z()},git),w(),sse.current(D.signal).then(q=>{B=q,E=!0,z()}).catch(()=>{})}r(S,"resume");function C(){const A=F2(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 T(){document.visibilityState==="hidden"?k():S()}r(T,"onVisibility");function R(){w()}return r(R,"onOnline"),v&&(v.onmessage=A=>{const D=Npe.safeParse(A.data);D.success&&(F2(s).has(D.data)||K$(s,D.data,!0),C())}),l.current=A=>{if(!j())return;const D=K$(s,A,!0);o(null),u++,h?.abort();try{v?.postMessage(A)}catch{}N(A,D)},document.addEventListener("visibilitychange",T),window.addEventListener("online",R),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",T),window.removeEventListener("online",R),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(bit,"useAnnouncement");function vit(e,s){const n=Xfe(),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="${VLe}">${p}`})}catch{}finally{clearTimeout(u)}})(),()=>{d.abort(),clearTimeout(u)}},[c,i,a]),c&&o?.key===i?o.document:null}r(vit,"useAnnouncementAnimation");function nse({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)(We,{to:e.path,onClick:n,onAuxClick:i,children:a})})}r(nse,"Action");function dE({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=vit(e,a),p=!!h;return(0,t.jsxs)(sn,{role:"region","aria-labelledby":o,className:W("relative w-full max-w-(--announcement-width) gap-0 overflow-hidden rounded-xl p-0 shadow-sm",i),onKeyDown:r(f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),s())},"onKeyDown"),children:[(u||h)&&(0,t.jsxs)("div",{className:"relative h-(--announcement-image-mobile-height) w-full shrink-0 overflow-hidden bg-muted md:h-(--announcement-image-height)",children:[u&&(0,t.jsx)("img",{src:d,alt:p?"":e.image.alt,referrerPolicy:"no-referrer",onError:r(()=>c(d),"onError"),className:"h-full w-full object-cover"}),p&&(0,t.jsx)("div",{role:"img","aria-label":e.animation.alt,className:"pointer-events-none absolute inset-0",children:(0,t.jsx)("iframe",{title:e.animation.alt,"aria-hidden":"true",tabIndex:-1,sandbox:"",referrerPolicy:"no-referrer",srcDoc:h,className:"h-full w-full border-0"})})]}),(0,t.jsx)(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)(Vn,{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)(nse,{action:e.secondaryLink,onClick:s}),(0,t.jsx)("div",{className:"ml-auto min-w-0 max-w-full",children:(0,t.jsx)(nse,{action:e.primaryAction,primary:!0,onClick:s})})]})]})}r(dE,"AnnouncementCard");var yit='[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [aria-modal="true"]:not([data-state="closed"]), dialog[open]';function jit(e){const[s,n]=(0,m.useState)(!1);return(0,m.useEffect)(()=>{if(!e)return;const a=r(()=>n(!!document.querySelector(yit)),"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(jit,"useModalOpen");function wit({health:e}){const{userId:s,settled:n}=Qf(),{selectedCompanyId:a,loading:i}=gs(),{onboardingOpen:o}=mM(),l=Gc(),c=LUe(),d=e?.deploymentMode==="local_trusted"?"local-board":n?s:null,{announcement:u,dismiss:h}=bit({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=jit(!!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)(dE,{announcement:u,onDismiss:r(()=>h(u.id),"onDismiss")},u.id)})}r(wit,"AnnouncementWell");function t4(e){const s=e.split("/").filter(Boolean);return s.length===1?s[0]?.toLowerCase()==="onboarding":s.length===2?s[1]?.toLowerCase()==="onboarding":!1}r(t4,"isOnboardingPath");function kit(e){const s=e.split("/").filter(Boolean);if(s.length===2&&s[1]?.toLowerCase()==="onboarding")return s[0]}r(kit,"companyPrefixFromOnboardingPath");function N5(){return 3}r(N5,"onboardingStepForCompany");function Nit(e){const{pathname:s,companyPrefix:n,companies:a,cloudManaged:i}=e;if(!t4(s))return null;const o=r(()=>a.length===1?{initialStep:N5(),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:N5(),companyId:l.id}:i?o():{initialStep:1}}r(Nit,"resolveRouteOnboardingOptions");function Sit(e){return!e.agentsLoaded||e.agentsRefreshing||e.agentCount>0?!1:!t4(e.pathname)}r(Sit,"shouldRouteAgentlessCompanyToOnboarding");function Cit(e){return e.currentStep>1&&e.currentStep>e.entryStep}r(Cit,"canGoBackFromOnboardingStep");function rse(e){return e.targetStep<e.currentStep&&e.targetStep>=e.entryStep}r(rse,"canJumpToOnboardingStep");function IW(e){return!e.hasCompanies&&!t4(e.pathname)}r(IW,"shouldRedirectCompanylessRouteToOnboarding");function _it(e){return e.onboardingOpen||!e.routeDismissed}r(_it,"isOnboardingWizardActive");function Iit({context:e}){const{slots:s,errorMessage:n}=hd({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)(Lu,{slot:a,context:e,className:"plugin-app-shell-overlay"},`${a.pluginId}:${a.pluginVersion}:${a.id}`))})}r(Iit,"AppShellEntries");function BSe({localTrusted:e=!1}){const{userId:s,settled:n}=Qf(),{selectedCompanyId:a,selectedCompany:i,loading:o}=gs(),{onboardingOpen:l,onboardingRouteDismissed:c}=mM(),{pathname:d}=ra(),u=n?s??(e?"local-board":null):null,h=l||!c&&t4(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)(Iit,{context:p},JSON.stringify([u,a]))}r(BSe,"PluginAppShellOverlays");function zSe({visible:e}){const s=ra(),{selectedCompanyId:n}=gs(),{openNewIssue:a}=Do(),i=IM(n),{enabled:o}=Qy(),{enabled:l}=VI(),c=(0,m.useMemo)(()=>!o&&!l?[{type:"link",to:"/dashboard",label:"Home",icon:_z},{type:"link",to:"/issues",label:"Tasks",icon:la},{type:"action",label:"New Task",icon:a_,onClick:r(()=>a(),"onClick")},{type:"link",to:"/agents/all",label:"Agents",icon:Eo},{type:"link",to:"/inbox",label:"Inbox",icon:cd,badge:i.inbox}]:[{type:"link",to:"/dashboard",label:"Home",icon:_z},...o?[{type:"link",to:"/chats",label:"Chat",icon:r_}]:[],{type:"action",label:"New Task",icon:a_,onClick:r(()=>a(),"onClick")},{type:"link",to:"/issues",label:"Tasks",icon:la,badge:l?i.inbox:void 0},{type:"link",to:"/agents/all",label:"Agents",icon:Eo},...l?[]:[{type:"link",to:"/inbox",label:"Inbox",icon:cd,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)(cb,{to:d.to,state:Jf,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)(lt,{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(zSe,"MobileBottomNav");function zw(e){if(typeof document>"u")return null;const s=document.querySelector(`meta[name="${e}"]`)?.getAttribute("content")?.trim();return s||null}r(zw,"readMetaContent");function n6(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(n6,"normalizeHexColor");function Ait(e){const s=n6(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(Ait,"hexToRgb");function W$(e){const s=e/255;return s<=.03928?s/12.92:((s+.055)/1.055)**2.4}r(W$,"relativeLuminanceChannel");function Tit(e){const{r:s,g:n,b:a}=Ait(e),i=.2126*W$(s)+.7152*W$(n)+.0722*W$(a);return 1.05/(i+.05)>=(i+.05)/.05?POe:TOe}r(Tit,"pickReadableTextColor");function Rit(){return zw("paperclip-worktree-enabled")==="true"}r(Rit,"isWorktreeRuntime");function Eit(){return zw("paperclip-instance-id")}r(Eit,"getWorktreeInstanceId");function Pit(){if(zw("paperclip-worktree-enabled")!=="true")return null;const e=zw("paperclip-worktree-name"),s=n6(zw("paperclip-worktree-color"));return!e||!s?null:{enabled:!0,name:e,color:s,textColor:n6(zw("paperclip-worktree-text-color"))??Tit(s)}}r(Pit,"getWorktreeUiBranding");function qSe(){const e=Pit(),{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(qSe,"WorktreeBanner");var Mit=3e4;function Dit(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(Dit,"formatRelativeTimestamp");function Lit(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(Lit,"describeReason");function USe({devServer:e}){const[s,n]=(0,m.useState)(!1);if((0,m.useEffect)(()=>{if(!s)return;const d=window.setTimeout(()=>{n(!1)},Mit);return()=>window.clearTimeout(d)},[s]),!e?.enabled||!e.restartRequired)return null;const a=e,i=Dit(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 su.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)(Ds,{className:"h-3.5 w-3.5 shrink-0"}),(0,t.jsx)("span",{children:"Restart Required"}),e.autoRestartEnabled?(0,t.jsx)(lt,{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:[Lit(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)(Uze,{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)(Ni,{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)(Ni,{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)(Ni,{className:"h-3.5 w-3.5"}),(0,t.jsx)("span",{children:s?"Restart requested":"Restart now"})]})]})]})})}r(USe,"DevRestartBanner");var KSe=["standalone","fullscreen","window-controls-overlay"];function $it(e){return`(display-mode: ${e})`}r($it,"displayModeQuery");function Oit(){if(!(typeof window>"u"||typeof window.matchMedia!="function"))return window.matchMedia.bind(window)}r(Oit,"defaultMatchMedia");function r6(e=Oit(),s=typeof navigator>"u"?void 0:navigator.standalone){return s===!0?!0:e?KSe.some(n=>e($it(n)).matches):!1}r(r6,"isChromelessDisplayMode");function B2({label:e,children:s,onClick:n}){return(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{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)(Wn,{children:e})]})}r(B2,"ControlButton");function Fit(e=typeof window>"u"?null:window.history.state){const s=e?.idx;return typeof s=="number"&&s>0}r(Fit,"hasInAppHistory");function Bit(){const[e,s]=(0,m.useState)(()=>typeof window<"u"?r6():!1);return(0,m.useEffect)(()=>{if(typeof window>"u")return;const n=r(()=>s(r6()),"update");if(n(),typeof window.matchMedia!="function")return;const a=KSe.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(Bit,"useChromeless");function a6({mobile:e,onNavigateHome:s}){const n=Bit(),a=Gc(),i=(0,m.useCallback)(()=>{if(Fit()){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 ha(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)(B2,{label:"Back",onClick:i,children:(0,t.jsx)(gl,{className:"h-4 w-4"})}),(0,t.jsx)("div",{className:"flex-1"}),(0,t.jsx)(B2,{label:"Refresh",onClick:o,children:(0,t.jsx)(Si,{className:"h-4 w-4"})}),(0,t.jsx)(B2,{label:"Share",onClick:l,children:(0,t.jsx)(N7,{className:"h-4 w-4"})}),(0,t.jsx)(B2,{label:"Open in Browser",onClick:c,children:(0,t.jsx)(qn,{className:"h-4 w-4"})})]}):null}r(a6,"StandaloneBrowserControls");var zit=16384,qit=40;function Uit(e){if(!e)return;const s=[];for(const n of e.slice(0,zit).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===qit)break}return s.length?`
|
|
354
354
|
${s.join(`
|
|
355
|
-
`)}`:void 0}r(Uit,"sanitizeComponentStack");function WSe(){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(WSe,"readBrowserErrorState");function Kit(e){const s=Uit(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:WSe()}}}r(Kit,"buildBrowserErrorContext");var ase=Promise.resolve();function AW(e){const s=ase.then(e);return ase=s.catch(()=>{}),s}r(AW,"enqueue");var aN=null;function Wit(e,s){return AW(async()=>{if(!aN)try{const n=await Wc(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(Hit(e,s)),aN=n}catch{}})}r(Wit,"initBrowserErrorMonitoring");function Vit(){return AW(async()=>{const e=aN;if(aN=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(Vit,"teardownBrowserErrorMonitoring");function VSe(e,s){let n;try{s&&(n=Kit(s))}catch{}AW(async()=>{try{n?aN?.captureException(e,n):aN?.captureException(e)}catch{}})}r(VSe,"captureBrowserException");function Hit(e,s){return{dsn:e,environment:s??void 0,release:"35128673e0278648abcbddfa8d4e2680e4a89fca",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??WSe()},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(Hit,"buildBrowserSentryInitOptions");var Git=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){VSe(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 HSe({children:e}){const s=ra(),n=Ln(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(Git,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(HSe,"RouteErrorBoundary");var ise={bot:Ji,cpu:dm,brain:Yx,zap:f3,rocket:r$e,code:Hfe,terminal:dg,shield:jI,eye:Ed,search:Gr,wrench:Df,hammer:tM,lightbulb:yI,sparkles:Np,star:vp,heart:RC,flame:T$e,bug:zv,cog:Upe,database:wI,globe:Ap,lock:dd,mail:H8,"message-square":Qx,"file-code":Nl,"git-branch":to,package:Ih,puzzle:Jx,target:bp,wand:_7,atom:N$e,"circuit-board":oze,radar:s$e,swords:zze,telescope:d$e,microscope:Sze,crown:qpe,gem:Gfe,hexagon:Ad,pentagon:Aze,fingerprint:Cz},Qit="bot";function Yit(e){return e&&OLe.includes(e)?ise[e]:ise[Qit]}r(Yit,"getAgentIcon");function S5({icon:e,className:s}){const n=Yit(e);return(0,t.jsx)(n,{className:s})}r(S5,"AgentIcon");function GSe({open:e,onOpenChange:s,...n}){return(0,t.jsx)(Vs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Qs,{"aria-describedby":void 0,className:"gap-0 overflow-hidden p-0 sm:max-w-md",children:[(0,t.jsxs)("div",{className:"px-4 pt-4 pb-3",children:[(0,t.jsx)(Js,{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)(Jit,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(GSe,"AgentChatPicker");function Jit({agents:e,onSelect:s,onComplete:n,loading:a,error:i,onRetry:o,existingChatAgentIds:l,renderAgentIcon:c}){const d=(0,m.useRef)(!1),u=(0,m.useRef)(null);(0,m.useEffect)(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null),[b,v]=(0,m.useState)(null);async function j(N){if(f)return;x(N.id),v(null);const w=new AbortController;u.current=w;try{await s(N,w.signal),d.current&&n()}catch(k){v(k instanceof Error?k.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(j,"selectAgent"),(0,t.jsxs)(_I,{children:[(0,t.jsx)(LN,{"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)($N,{children:[(0,t.jsx)(ON,{children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4",children:[(0,t.jsx)("span",{children:e.length?`No agents match “${h}”`:"No agents yet."}),e.length?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Try another name or role."}),(0,t.jsx)(L,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(ju,{children:e.map(N=>(0,t.jsxs)(To,{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)(S5,{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(Jit,"AgentChatPickerResults");function uE({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=Ln(),[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(),T=e.filter(A=>`${A.name} ${A.title??""} ${A.role}`.toLocaleLowerCase().includes(I));function R(){k(""),S.current?.focus()}return r(R,"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)(bn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(Gr,{"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)(pt,{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:R,children:(0,t.jsx)(Vn,{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":`${T.length} ${T.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))}):T.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:T.map(A=>(0,t.jsxs)(We,{to:`/chats/${encodeURIComponent(A.status==="terminated"?A.id:Wl(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)(_r,{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:R,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)(Eo,{className:"size-4"}),"Browse all agents"]}):(0,t.jsxs)(We,{to:"/agents/all",children:[(0,t.jsx)(Eo,{className:"size-4"}),"Browse all agents"]})})}),(0,t.jsx)(GSe,{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)(_r,{agent:A,size:32}),"renderAgentIcon"),onSelect:r(async(A,D)=>{p?await p(A,D):u?await u(A,D):v(`/chats/${encodeURIComponent(Wl(A))}`),D?.aborted||k("")},"onSelect")})]})}r(uE,"AgentConversationSidebar");var C5={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 QSe(){const{selectedCompanyId:e}=gs(),{enabled:s,loaded:n}=Qy(),a=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:X({queryKey:P.agents.list(e),queryFn:r(()=>Lt.list(e),"queryFn"),enabled:s&&!!e}),chats:X({queryKey:P.agentChats.list(e,i),queryFn:r(()=>C5.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(QSe,"useAgentChatNavigation");function YSe(e,s){const n=Mt(),a=Ln(),{isMobile:i,setSidebarOpen:o}=Fa(),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 C5.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(Wl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(YSe,"useOpenAgentChat");function Xit(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=QSe(),o=YSe(e,s),l=Ln(),c=Xf(e),{isMobile:d,setSidebarOpen:u}=Fa(),{pathname:h}=ra(),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=yp({queries:x.map(C=>({queryKey:P.agents.detail(C),queryFn:r(()=>Lt.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(Wl(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||Bf(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)(uE,{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:Wl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(Xit,"AgentConversationsSidebar");var z2=240,i6=208,o6=420,ose=16;function _5(e){return Math.min(o6,Math.max(i6,e))}r(_5,"clampSidebarWidth$1");function lse(e){if(typeof window>"u")return z2;try{const s=window.localStorage.getItem(e);if(!s)return z2;const n=Number.parseInt(s,10);return Number.isFinite(n)?_5(n):z2}catch{return z2}}r(lse,"readStoredSidebarWidth$1");function cse(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(_5(s)))}catch{}}r(cse,"writeStoredSidebarWidth$1");function Zit({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)(()=>lse(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=lse(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]),T=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),R=(0,m.useCallback)(E=>{const B=_5(E);v.current=B,f(B),cse(o,B)},[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 B=_5(j.current.startWidth+E.clientX-j.current.startX);v.current=B,f(B)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),cse(o,v.current))},[o]),$=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),R(p-ose)):E.key==="ArrowRight"?(E.preventDefault(),R(p+ose)):E.key==="Home"?(E.preventDefault(),R(i6)):E.key==="End"&&(E.preventDefault(),R(o6)))},[C,R,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:T,"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":i6,"aria-valuemax":o6,"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:$,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(Zit,"SidebarShell$1");function q2({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)(Ove,{children:e})})}r(q2,"SecondarySidebar$1");var JSe={listStacks:r(()=>Te.get("/cloud/stacks"),"listStacks")};function s4(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(s4,"cloudAppUrl");function XSe(e){return s4(e,"/stacks/new")}r(XSe,"cloudStackCreateUrl");function ZSe(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(ZSe,"tenantSignInReturnPath");function eot(e,s,n){const a=s?.trim();if(!a)return null;const i=s4(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",ZSe(n)),o.toString()}r(eot,"cloudStackEntryUrl");function eCe(e,s){const n=s?.trim();return n?s4(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(eCe,"cloudStackInviteUrl");function tot(e){return s4(e,"/orgs?manage=1")}r(tot,"cloudPortfolioManageUrl");function tCe(){const e=Ac(),s=!!e,n=X({queryKey:P.cloud.stacks,queryFn:r(()=>JSe.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:eCe(e.cloudBaseUrl,a.stackSlug)}r(tCe,"useCloudInviteUrl");function sot(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(sot,"canInviteCompanyMembers");function sCe(e=!0){const s=rLe(),n=X({queryKey:P.access.currentBoardAccess,queryFn:r(()=>hr.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&sot(s?.selectedCompanyId,n.data)}r(sCe,"useCanInviteCompanyMembers");function nCe(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=X({queryKey:P.stagingCommit,queryFn:r(()=>su.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(nCe,"useStagingCommit");function not(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(not,"slugifyUserPart");function rCe(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=not(n);if(a)return`/u/${a}`}return"/u/me"}r(rCe,"userProfilePath");var rot="Toggle the app appearance.";function hk({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=SFe(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?Kbe:U0e;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:rot})]})]}):(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(hk,"ThemeToggle");var P_=null,aCe=!1,l6=!1,c6=new Set;function I5(){for(const e of c6)e()}r(I5,"emit");function aot(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(aot,"isIosSafariLike");function iot(e=window){const s=r(a=>{a.preventDefault(),P_=a,I5()},"onPrompt"),n=r(()=>{P_=null,aCe=!0,I5()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(iot,"captureInstallPrompt");function oot(){return aCe||r6()?"installed":P_?"prompt":aot()?"ios-manual":"unavailable"}r(oot,"installAvailability");async function lot(){const e=P_;if(!e)return"unavailable";P_=null,I5(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(lot,"promptInstall");function d6(e){l6!==e&&(l6=e,I5())}r(d6,"setIosInstallHelpOpen");function cot(){return l6}r(cot,"iosInstallHelpOpen");function dot(){return(0,m.useSyncExternalStore)(iCe,cot,()=>!1)}r(dot,"useIosInstallHelpOpen");function iCe(e){return c6.add(e),()=>{c6.delete(e)}}r(iCe,"subscribe$1");function uot(){return(0,m.useSyncExternalStore)(iCe,oot,()=>"unavailable")}r(uot,"useInstallAvailability");var dse="Install app",mot="Add Paperclip to your home screen or dock.";function oCe({variant:e,onAfterAction:s}){const n=uot();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?d6(!0):lot(),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)(oo,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:dse})]}):(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)(oo,{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:dse}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:mot})]})]})}r(oCe,"InstallAppMenuAction");function hot(){const e=dot();return(0,t.jsx)(Vs,{open:e,onOpenChange:d6,children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Install Paperclip"}),(0,t.jsx)(yn,{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)(V$,{index:1,icon:(0,t.jsx)(Oze,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(V$,{index:2,icon:(0,t.jsx)(Bze,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(V$,{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)(mr,{children:(0,t.jsx)(L,{type:"button",onClick:r(()=>d6(!1),"onClick"),children:"Done"})})]})})}r(hot,"IosInstallHelpDialog");function V$({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(V$,"InstallStep");function pot(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(pot,"formatTimestamp$2");function fot(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(fot,"isValidTimestamp");function xot(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(xot,"restartTimestamp");function got(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(got,"commitLabel");function bot(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(bot,"localChangesLabel");function H$({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(H$,"ServerInfoRow");function lCe(){const e=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=X({queryKey:P.health,queryFn:r(()=>su.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=xot(n),l=fot(o),c=i?"Health unavailable":a?"Loading...":pot(o),d=i?"Health unavailable":a?"Loading...":got(n),u=i?"Health unavailable":a?"Loading...":bot(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)(H$,{icon:Jd,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(H$,{icon:f7,label:"Running commit",value:d}),(0,t.jsx)(H$,{icon:hze,label:"Checkout state",value:u})]})}r(lCe,"SidebarServerInfo");var vot="/company/settings/members?tab=invites",yot="https://docs.paperclip.ing/",jot="https://paperclip.ing/feedback";function wot(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(wot,"deriveInitials$2");function G$({label:e,icon:s,onClick:n,href:a,external:i=!1,topLevel:o=!1}){const l="flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",c=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(s,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e})]});return a?i?(0,t.jsx)("a",{href:a,target:"_blank",rel:"noreferrer",className:l,onClick:n,children:c}):o?(0,t.jsx)("a",{href:a,className:l,onClick:n,children:c}):(0,t.jsx)(We,{to:a,className:l,onClick:n,children:c}):(0,t.jsx)("button",{type:"button",className:l,onClick:n,children:c})}r(G$,"MenuAction$1");function use({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!Ac(),{hidden:l,loaded:c}=tu(),d=tCe(),u=sCe(!o),h=o?d:u?vot:null,p=c&&h!==null&&!lg(l,"company.members")&&!lg(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:b,setSidebarOpen:v,collapsed:j,peeking:N}=Fa(),w=j&&!N&&!a,k=s??f,S=nCe(k),C=n??x,{data:I}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),T=HN({onSignedOut:$}),R=I?.user.name?.trim()||"Board",A=I?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),D=wot(R),M=rCe(I?.user);function $(){C(!1),b&&v(!1)}r($,"closeNavigationChrome");function E(){T.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)(yr,{open:k,onOpenChange:C,children:[(0,t.jsx)(Ir,{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)(So,{size:"sm",children:[I?.user.image?(0,t.jsx)(md,{src:I.user.image,alt:R}):null,(0,t.jsx)(Co,{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:R})]})}),(0,t.jsxs)(lr,{side:"top",align:"start",sideOffset:10,className:"min-h-(--profile-popover-min-height) w-(--profile-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"relative flex h-(--profile-popover-header-height) shrink-0 items-center gap-2.5 px-3.5",children:[(0,t.jsx)(We,{to:M,"aria-label":"View profile",onClick:$,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)(So,{className:"pointer-events-none relative size-9",children:[I?.user.image?(0,t.jsx)(md,{src:I.user.image,alt:R}):null,(0,t.jsx)(Co,{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:R}),(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)(G$,{label:"Settings",icon:Xd,href:"/company/settings",onClick:$}),p&&h?(0,t.jsx)(G$,{label:"Invite",icon:Yf,href:h,topLevel:o,onClick:$}):null,(0,t.jsx)(G$,{label:"Documentation",icon:zN,href:yot,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(hk,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(oCe,{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",T.isPending&&"cursor-not-allowed opacity-60"),onClick:E,disabled:T.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:T.isPending?"Signing out...":"Sign out"})]}):null,(0,t.jsx)(lCe,{})]})]})]}),!w&&!o?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("a",{href:jot,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)(wg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Wn,{side:"top",children:"Share feedback"})]}):null]})})}r(use,"SidebarAccountMenu$1");function cCe({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=gfe({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(!SI(b.target)&&!wp()){if(b.key==="/"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),vOe()||s?.();return}if(b.key==="?"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),i?.();return}b.key==="c"&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&(b.preventDefault(),e?.()),b.key==="["&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),n?.()),b.key==="]"&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(b=>{b.target instanceof HTMLElement&&b.target!==document.body&&u()},"handleFocusIn");return document.addEventListener("pointerdown",f,!0),document.addEventListener("focusin",x,!0),document.addEventListener("keydown",p),()=>{u(),document.removeEventListener("pointerdown",f,!0),document.removeEventListener("focusin",x,!0),document.removeEventListener("keydown",p)}},[e,s,n,a,i,o])}r(cCe,"useKeyboardShortcuts");var kot=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function dCe(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!kot.has(n)}r(dCe,"isRememberableCompanyPath");function Not(e){const s=iy(e.companyPrefix);return e.companies.find(n=>iy(n.issuePrefix)===s)??null}r(Not,"findCompanyByPrefix");function Sot(e){const s=G8(e.pathname);return s?Not({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(Sot,"getRememberedPathOwnerCompanyId");function Cot(e){const s=e.path?nM(e.path):"/dashboard";if(!dCe(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&&iy(i[1]??"")!==iy(e.companyPrefix))return"/dashboard"}return s}r(Cot,"sanitizeRememberedPathForCompany");var uCe="paperclip.companyPaths";function mCe(){try{const e=localStorage.getItem(uCe);if(e)return JSON.parse(e)}catch{}return{}}r(mCe,"getCompanyPaths");function _ot(e,s){const n=mCe();n[e]=s,localStorage.setItem(uCe,JSON.stringify(n))}r(_ot,"saveCompanyPath");function hCe(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=gs(),i=ra(),o=Ln(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>Sot({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=nM(d);u&&dCe(h)&&_ot(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=mCe(),h=Cot({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(hCe,"useCompanyPageMemory");var Iot=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 pCe(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 Iot({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(pCe,"useMobileNavVisibility");function fCe(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(fCe,"resolveArchivedCompanyBounce");function Aot(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(Aot,"resolveCompanyArchiveDeparture");function xCe(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(xCe,"shouldSyncCompanySelectionFromRoute");function Tot(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(Tot,"shouldFocusMainContentAfterNavigation");function gCe(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{Tot(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(gCe,"scheduleMainContentFocus");function bCe(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(bCe,"pinDocumentScrollToZero");function Eu({scope:e="global",requestedPrefix:s}){const n=ra(),{setBreadcrumbs:a}=Fn(),{companies:i,selectedCompany:o}=gs();(0,m.useEffect)(()=>{a([{label:"Not Found"}])},[a]);const l=o??i[0]??null,c=l?`/${l.issuePrefix}/dashboard`:"/",d=`${n.pathname}${n.search}${n.hash}`,u=s?.toUpperCase(),h=e==="invalid_company_prefix"?"Organization not found":"Page not found",p=e==="invalid_company_prefix"?`No organization matches prefix "${u??"unknown"}".`:"This route does not exist.";return(0,t.jsx)("div",{className:"mx-auto max-w-2xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Ds,{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)(We,{to:c,children:[(0,t.jsx)(h3,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)(L,{variant:"outline",asChild:!0,children:(0,t.jsx)(We,{to:"/",children:"Go home"})})]})]})})}r(Eu,"NotFoundPage");function Rot(e,s){return Wye(e,s)[0]?.toLowerCase()??null}r(Rot,"getCompanyRouteSegment$1");var Eot=new Set(["browse","connections","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function Pot({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=Fa(),{openNewIssue:u,openOnboarding:h}=Do(),{togglePanelVisible:p}=Zf(),f=Gc()?.pushToast??null,{companies:x,loading:b,selectedCompany:v,selectedCompanyId:j,selectionSource:N,setSelectedCompanyId:w}=gs(),{companyPrefix:k,pluginRoutePath:S,agentId:C,routineId:I}=ga(),T=Ln(),R=ra(),A=sM(),{enabled:D}=fc(),M=Vye(R.pathname,k),$=M.builtInContextualSurface==="settings",E=M.companySegments,B=M.isTaskDetail,{enabled:z}=Qy(),q=z&&E[0]?.toLowerCase()==="chats",U=D&&(B||q),F=E[0]?.toLowerCase()==="tools",K=E[0]?.toLowerCase()==="apps",G=K&&E[1]&&!Eot.has(E[1].toLowerCase())?E[1]:null,se=K&&E[1]?.toLowerCase()==="app"&&E[2]?E[2]:null,ee=(0,m.useRef)(!1),ne=(0,m.useRef)(null),he=(0,m.useRef)(null),Z=(0,m.useRef)(new Dve),re=(0,m.useRef)(R.key),ce=pCe(c&&!B,R.pathname),[H,Q]=(0,m.useState)(!1),Y=(0,m.useMemo)(()=>{if(!k)return null;const ot=k.toUpperCase();return x.find(Ee=>Ee.issuePrefix.toUpperCase()===ot)??null},[x,k]),te=!!k&&!b&&x.length>0&&!Y,ae=(0,m.useMemo)(()=>S?.toLowerCase()??Rot(R.pathname,k),[k,R.pathname,S]),me=Y?.id??null,oe=Y?.issuePrefix??null,{slots:ie}=hd({slotTypes:["page","routeSidebar"],companyId:me,enabled:!!(me&&ae)}),ge=(0,m.useMemo)(()=>q7(ie,ae),[ae,ie]),be=(0,m.useMemo)(()=>({companyId:me,companyPrefix:oe}),[me,oe]),le=$?(0,t.jsx)(z7e,{}):!D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(WX,{}):G?(0,t.jsx)(UX,{kind:"connection",connectionId:G}):se?(0,t.jsx)(UX,{kind:"application",applicationId:se}):K||F?(0,t.jsx)(Q7e,{}):ge?D?(0,t.jsx)(KI,{surface:`plugin:${ge.id}`,title:ge.displayName,children:(0,t.jsx)(Lu,{slot:ge,context:be,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(Lu,{slot:ge,context:be,className:"h-full w-full",missingBehavior:"placeholder"}):null,ue=q?(0,t.jsx)(Xit,{}):M.builtInContextualSurface==="agent"&&C?(0,t.jsx)(c9e,{agentRef:C}):D&&M.builtInContextualSurface==="routine"&&I?(0,t.jsx)(kUe,{children:(0,t.jsx)(m9e,{routineId:I})}):D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(WX,{}):le,Se=ue!=null,ye=D&&Se&&(q||M.builtInContextualSurface==="skills"||M.builtInContextualSurface==="agent"||M.builtInContextualSurface==="routine"||K||F),Ie=D&&Se&&!ye,Ke=Se&&(!D||ye),rt=!D||!Se?null:ge&&!M.builtInContextualSurface?`plugin:${ge.id}`:M.builtInContextualSurface,dt=(0,m.useRef)(null),{data:de}=X({queryKey:P.health,queryFn:r(()=>su.get(),"queryFn"),retry:!1,refetchInterval:r(ot=>ot.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!D&&Se),()=>d(!1)),[Se,d,D]),(0,m.useEffect)(()=>{const ot=dt.current;rt&&k&&ot&&ot.surface!==rt&&ot.pathname!==R.pathname&&O7e({surface:rt,companyPrefix:k,previousPathname:ot.pathname}),dt.current={pathname:R.pathname,surface:rt}},[k,rt,R.pathname]),(0,m.useEffect)(()=>{b||ee.current||de?.deploymentMode!=="authenticated"&&(de?.cloud||x.length===0&&(ee.current=!0,h()))},[x,b,h,de?.cloud,de?.deploymentMode]),(0,m.useEffect)(()=>{if(!k||b||x.length===0)return;if(!Y){const Ee=(j?x.find(Je=>Je.id===j):null)??x[0]??null;Ee&&j!==Ee.id&&w(Ee.id,{source:"route_sync"});return}if(k!==Y.issuePrefix){const Ee=R.pathname.replace(/^\/[^/]+/,"");T(`/${Y.issuePrefix}${Ee}${R.search}`,{replace:!0});return}const ot=fCe({matchedCompany:Y,selectedCompanyId:j,companies:x});if(ot){f?.({title:`${Y.name} is archived`,body:`Switched to ${ot.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Y.id}`}),w(ot.id,{source:"route_sync"}),T(`/${ot.issuePrefix}/dashboard`,{replace:!0});return}xCe({selectionSource:N,selectedCompanyId:j,routeCompanyId:Y.id})&&w(Y.id,{source:"route_sync"})},[k,x,b,Y,R.pathname,R.search,T,f,N,j,w]);const ze=p,gt=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),bt=(0,m.useRef)(null),De=(0,m.useRef)(!1),Qe=(0,m.useRef)(!1),mt=(0,m.useCallback)(()=>{bt.current!==null&&(window.clearTimeout(bt.current),bt.current=null)},[]),Ye=(0,m.useCallback)(()=>{mt(),bt.current=window.setTimeout(()=>l(!0),50)},[mt,l]),it=(0,m.useCallback)(()=>{mt(),l(!0)},[mt,l]),Nt=(0,m.useCallback)(()=>{mt(),bt.current=window.setTimeout(()=>l(!1),120)},[mt,l]),Ze=(0,m.useCallback)(()=>{De.current=!0,i&&!Qe.current&&Ye()},[i,Ye]),Pe=(0,m.useCallback)(()=>{De.current=!1,Qe.current=!1,Nt()},[Nt]),Ce=(0,m.useCallback)(()=>{Qe.current||it()},[it]),Ve=(0,m.useCallback)(()=>{De.current||Nt()},[Nt]);(0,m.useEffect)(()=>mt,[mt]);const Ge=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Ge.current&&(i?(mt(),l(!1),Qe.current=De.current):Qe.current=!1,Ge.current=i)},[i,mt,l]),(0,m.useEffect)(()=>{if(!o)return;const ot=r(Ee=>{Ee.key==="Escape"&&(mt(),l(!1))},"onKeyDown");return window.addEventListener("keydown",ot),()=>window.removeEventListener("keydown",ot)},[o,mt,l]),hCe(),cCe({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:gt,onToggleSidebar:a,onTogglePanel:ze,onShowShortcuts:r(()=>Q(!0),"onShowShortcuts"),onGoToInbox:r(()=>T("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const ot=30,Ee=50,Je=75;let _e=0,He=0;const ns=r(ct=>{const Ue=ct.touches[0];_e=Ue.clientX,He=Ue.clientY},"onTouchStart"),fe=r(ct=>{const Ue=ct.changedTouches[0],Et=Ue.clientX-_e;if(!(Math.abs(Ue.clientY-He)>Je)){if(!s&&_e<ot&&Et>Ee){n(!0);return}s&&Et<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",ns,{passive:!0}),document.addEventListener("touchend",fe,{passive:!0}),()=>{document.removeEventListener("touchstart",ns),document.removeEventListener("touchend",fe)}},[c,s,n]),(0,m.useEffect)(()=>{const ot=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=ot}},[c]),(0,m.useEffect)(()=>{if(!c)return bCe()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const ot=he.current;return gCe(ot)},[R.pathname]),(0,m.useEffect)(()=>{const ot=he.current;if(!ot)return;const Ee=r(()=>{Z.current.remember(re.current,ot.scrollTop)},"recordScroll");return ot.addEventListener("scroll",Ee,{passive:!0}),()=>ot.removeEventListener("scroll",Ee)},[]),(0,m.useLayoutEffect)(()=>{const ot=he.current,Ee=Mve({previousPathname:ne.current,pathname:R.pathname,navigationType:A,state:R.state});ne.current=R.pathname;const Je=A==="POP",_e=Je?Z.current.recall(R.key):0;if(re.current=R.key,Je){M3(ot,_e);const He=requestAnimationFrame(()=>M3(ot,_e));return()=>cancelAnimationFrame(He)}Ee&&Lve(ot)},[R.key,R.pathname,R.state,A]),(0,t.jsx)(Pve,{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)(qSe,{}),(0,t.jsx)(USe,{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:Se?(0,t.jsx)(q2,{children:ue}):(0,t.jsx)(FX,{children:e})})}),(0,t.jsx)(use,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}):(0,t.jsxs)(Zit,{open:s,collapsed:Ie?!1:i,peeking:Ie?!1:o,resizable:!0,onPanelMouseEnter:Ie?void 0:Ze,onPanelMouseLeave:Ie?void 0:Pe,onPanelFocusCapture:!Ie&&i?Ce:void 0,onPanelBlurCapture:!Ie&&i?Ve:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Ie?(0,t.jsx)(q2,{children:ue}):(0,t.jsx)(FX,{children:e})}),(0,t.jsx)(use,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}),!c&&Ke&&!ye?(0,t.jsx)(q2,{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",{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)(a6,{mobile:c,onNavigateHome:r(()=>T("/dashboard"),"onNavigateHome")}),(0,t.jsx)(HX,{}),c&&$?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(Qye,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&U&&"streamlined-task-detail-surface"),children:[!c&&ye?(0,t.jsx)(q2,{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)(a6,{mobile:!1,onNavigateHome:r(()=>T("/dashboard"),"onNavigateHome")}),(0,t.jsx)(HX,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:he,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)(Eu,{scope:"invalid_company_prefix",requestedPrefix:k??v?.issuePrefix}):(0,t.jsx)(HSe,{children:(0,t.jsx)(lb,{})})})]}),(0,t.jsx)(oje,{taskDetailLayout:!c&&U})]})]})]}),c&&(0,t.jsx)(zSe,{visible:ce}),(0,t.jsx)(dje,{}),(0,t.jsx)(Uje,{}),(0,t.jsx)(PSe,{}),(0,t.jsx)(LSe,{}),(0,t.jsx)($Se,{}),(0,t.jsx)(OSe,{open:H,onOpenChange:Q}),(0,t.jsx)(FSe,{}),(0,t.jsx)(wit,{health:de}),(0,t.jsx)(BSe,{localTrusted:de?.deploymentMode==="local_trusted"})]})})}r(Pot,"Layout$1");var vCe=(0,m.createContext)(!1);function Mot({children:e}){return(0,t.jsx)(vCe.Provider,{value:!0,children:e})}r(Mot,"SidebarNavExpandedProvider");function Dot(){return(0,m.useContext)(vCe)}r(Dot,"useSidebarNavExpanded");function Ja({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}=Fa(),I=Dot(),T=S&&!C&&!I,R=c!=null&&c>0,A=x!=null&&x>0,D=A?`${x} live`:R?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,M=!T||!D&&!j?void 0:`${s}${D?`, ${D}`:""}${j?`, ${j}`:""}`,$=(0,t.jsxs)(cb,{to:e,state:Jf,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"}),T&&!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)"})]}),T&&!f&&!A&&R&&(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:T?Fy:W("min-w-0 flex-1 truncate",l),children:s}),!T&&v,!T&&h&&(0,t.jsx)(lt,{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}),!T&&(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"]})]})]}),!T&&R&&(0,t.jsx)(lt,{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 T?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("div",{children:$})}),(0,t.jsx)(Wn,{side:"right",children:s})]}):$}r(Ja,"SidebarNavItem");var Lot=3,mse=12e4,$ot=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Kj(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Kj,"agentTimestamp");function hse(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=Kj(i,"lastHeartbeatAt")-Kj(a,"lastHeartbeatAt");if(o!==0)return o;const l=Kj(i,"updatedAt")-Kj(a,"updatedAt");if(l!==0)return l;const c=Kj(i,"createdAt")-Kj(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r(hse,"sortAgents");var Oot="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function Fot({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=Wl(n),j=s?`${xm(n)}/${s}`:xm(n),N=`${xm(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",T=a||n.status==="pending_approval"||S||k&&C,R=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)(Ja,{to:j,label:n.name,iconNode:(0,t.jsx)(_r,{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)(rk,{status:p,compact:!0}):null,C?(0,t.jsx)(Ds,{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)(zI,{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)(pb,{size:"row",quiet:!0,starred:!0,pending:b,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:Oot})}):null,(0,t.jsxs)(ta,{children:[(0,t.jsx)(ea,{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)(Ai,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(sa,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(cs,{onClick:r(()=>{b||x(n,!f)},"onClick"),disabled:b,children:[b?(0,t.jsx)(nt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(vp,{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)(Xa,{})]}):null,(0,t.jsx)(cs,{asChild:!0,children:(0,t.jsxs)(We,{to:N,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(mc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(Xa,{}),(0,t.jsxs)(cs,{onClick:r(()=>{T||c(n,k?"resume":"pause")},"onClick"),disabled:T,title:S?"Agent was paused by budget limits":void 0,children:[k?(0,t.jsx)(LI,{className:"size-4"}):(0,t.jsx)(Td,{className:"size-4"}),(0,t.jsx)("span",{children:R})]}),(0,t.jsx)(Xa,{}),(0,t.jsxs)(cs,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(nt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(Fot,"SidebarAgentItem");function Bot({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=Mt(),{selectedCompanyId:u}=gs(),{openNewAgent:h}=Do(),{isMobile:p,setSidebarOpen:f,collapsed:x,peeking:b}=Fa(),v=x&&!b,{pushToast:j}=pa(),N=ra(),{data:w}=X({queryKey:P.agents.list(u),queryFn:r(()=>Lt.list(u),"queryFn"),enabled:!!u}),{data:k}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn"),enabled:!!u}),S=k?.enableBuiltInAgents===!0,{data:C}=X({queryKey:P.builtInAgents.list(u),queryFn:r(()=>Yh.list(u),"queryFn"),enabled:!!u&&S}),I=(0,m.useMemo)(()=>{const ye=new Map;if(!S)return ye;for(const Ie of C??[])Ie.agentId&&ye.set(Ie.agentId,Ie.status);return ye},[C,S]),{data:T}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn")}),R=Xf(u),A=Sg(u),D=P.liveRuns(u),M=bo({companyId:u,resourceKey:"live-runs",queryKey:D,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:$,dataUpdatedAt:E}=X({queryKey:D,queryFn:r(()=>Zr.liveRunsForCompany(u),"queryFn"),enabled:M.enabled,refetchInterval:M.refetchInterval});vo(M,$,E);const B=(0,m.useMemo)(()=>{const ye=new Map;for(const Ie of $??[])ye.set(Ie.agentId,(ye.get(Ie.agentId)??0)+1);return ye},[$]),z=(0,m.useMemo)(()=>{const ye=new Set;for(const[Ie,Ke]of B)Ke>0&&ye.add(Ie);return ye},[B]),q=(0,m.useMemo)(()=>(w??[]).filter(ye=>ye.status!=="terminated"&&(!R.isSuccess||Bf(R.data,"agent",ye.id)!=="left")),[w,R.data,R.isSuccess]),U=T?.user?.id??T?.session?.userId??null,F=(0,m.useMemo)(()=>u?Wve(u,U):null,[U,u]),[K,G]=(0,m.useState)(()=>F?ak(F):"top"),{orderedAgents:se}=Gve({agents:q,companyId:u,userId:U}),ee=(0,m.useMemo)(()=>hse(se,K),[se,K]),ne=(0,m.useMemo)(()=>new Set(ee.map(ye=>ye.id)),[ee]);(0,m.useEffect)(()=>{const ye=Date.now();for(const Ie of z)c.current.set(Ie,ye);for(const Ie of c.current.keys())ne.has(Ie)||c.current.delete(Ie)},[z,ne]);const he=(0,m.useMemo)(()=>{const ye=Date.now(),Ie=c.current;return ee.filter(Ke=>{if((B.get(Ke.id)??0)>0)return!0;const rt=Ie.get(Ke.id);return rt!==void 0&&ye-rt<=mse})},[B,o,ee]),Z=he.length>0,re=e?Z?he:ee.slice(0,Lot):ee,ce=e&&ee.length>0,H=N.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Q=H?.[1]??null,Y=H?.[2]??null;(0,m.useEffect)(()=>{if(!F){G("top");return}G(ak(F))},[F]),(0,m.useEffect)(()=>{if(!F)return;const ye=r(Ke=>{Ke.key===F&&G(ak(F))},"onStorage"),Ie=r(Ke=>{const rt=Ke.detail;!rt||rt.storageKey!==F||G(rt.sortMode)},"onCustomEvent");return window.addEventListener("storage",ye),window.addEventListener(l_,Ie),()=>{window.removeEventListener("storage",ye),window.removeEventListener(l_,Ie)}},[F]),(0,m.useEffect)(()=>{if(!e)return;const ye=Date.now();let Ie=null;for(const rt of ee){if((B.get(rt.id)??0)>0)continue;const dt=c.current.get(rt.id);if(dt===void 0)continue;const de=dt+mse;de<ye||(Ie=Ie===null?de:Math.min(Ie,de))}if(Ie===null)return;const Ke=window.setTimeout(()=>{l(rt=>rt+1)},Math.max(0,Ie-ye+1));return()=>{window.clearTimeout(Ke)}},[e,ee,B,o]);const te=(0,m.useCallback)(ye=>{const Ie=ye==="alphabetical"||ye==="recent"?ye:"top";G(Ie),F&&Hve(F,Ie)},[F]),ae=je({mutationFn:r(({agent:ye,action:Ie})=>Ie==="pause"?Lt.pause(ye.id,u??void 0):Lt.resume(ye.id,u??void 0),"mutationFn"),onMutate:r(({agent:ye})=>{i(Ie=>{const Ke=new Set(Ie);return Ke.add(ye.id),Ke})},"onMutate"),onSuccess:r(async(ye,{agent:Ie,action:Ke})=>{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(Wl(Ie))})]),j({title:Ke==="pause"?"Agent paused":"Agent resumed",body:Ie.name,tone:"success"})},"onSuccess"),onError:r((ye,{agent:Ie,action:Ke})=>{j({title:Ke==="pause"?"Could not pause agent":"Could not resume agent",body:ye instanceof Error?ye.message:Ie.name,tone:"error"})},"onError"),onSettled:r((ye,Ie,{agent:Ke})=>{i(rt=>{const dt=new Set(rt);return dt.delete(Ke.id),dt})},"onSettled")}),me=(0,m.useCallback)(ye=>A.mutate({resourceType:"agent",resourceId:ye.id,resourceName:ye.name,state:"left"}),[A]),oe=(0,m.useCallback)(ye=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===ye.id,[A.isPending,A.variables]),ie=(0,m.useCallback)((ye,Ie)=>A.mutate({resourceType:"agent",resourceId:ye.id,resourceName:ye.name,starred:Ie}),[A]),ge=(0,m.useCallback)(ye=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===ye.id&&A.variables.starred!==void 0,[A.isPending,A.variables]),be=(0,m.useMemo)(()=>new Set(NM(R.data,"agent")),[R.data]),le=(0,m.useMemo)(()=>hse(q.filter(ye=>be.has(ye.id)),"alphabetical"),[q,be]),ue=(0,m.useMemo)(()=>re.filter(ye=>!be.has(ye.id)),[re,be]),Se=r((ye,Ie)=>(0,t.jsx)(Fot,{activeAgentId:Q,activeTab:Y,agent:ye,disabled:a.has(ye.id),isMobile:p,leaving:oe(ye),onLeaveAgent:me,onPauseResume:r((Ke,rt)=>ae.mutate({agent:Ke,action:rt}),"onPauseResume"),rail:v,runCount:B.get(ye.id)??0,setSidebarOpen:f,builtInStatus:I.get(ye.id),starred:Ie||hb(R.data,"agent",ye.id),onToggleStar:ie,starPending:ge(ye)},ye.id),"renderAgentRow");return(0,t.jsxs)(Zx,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:bn,onClick:h},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Eo,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:$ot,radioValue:K,onRadioValueChange:te},children:[le.map(ye=>Se(ye,!0)),ue.map(ye=>Se(ye,!1)),ce&&(()=>{const ye=(0,t.jsxs)(We,{to:"/agents/all",state:Jf,"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)(Eo,{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)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:ye}),(0,t.jsx)(Wn,{side:"right",children:"See all agents"})]}):ye})()]})}r(Bot,"SidebarAgents");var zot="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function qot(){const{selectedCompanyId:e}=gs(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=Fa(),o=a&&!i,l=ra(),{data:c}=X({queryKey:P.projects.list(e),queryFn:r(()=>ma.list(e),"queryFn"),enabled:!!e}),d=Xf(e),u=Sg(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(NM(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=og(v),N=h===j||h===v.id,w=b(v),k=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=hb(d.data,"project",v.id),I=(0,t.jsxs)(cb,{to:`/projects/${j}/issues`,state:Jf,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)(wm,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?Fy:"flex-1 truncate",children:v.name}),!o&&v.pauseReason==="budget"?(0,t.jsx)(zI,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:I})}),(0,t.jsx)(Wn,{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)(pb,{size:"row",quiet:!0,starred:C,pending:k,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:zot})}):null,!o&&s?(0,t.jsxs)(ta,{children:[(0,t.jsx)(ea,{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)(Ai,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(sa,{align:"end",className:"w-48",children:[(0,t.jsxs)(cs,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[k?(0,t.jsx)(nt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(vp,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(Xa,{}),(0,t.jsxs)(cs,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(nt,{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(qot,"SidebarStarredProjects");var Uot="size-5 shrink-0 rounded-md text-(length:--text-micro)",Kot="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",Wot="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",Q$="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)(GN,{companyName:e.name,logoUrl:e.logoUrl,className:s?Kot:Uot})}r(yCe,"WorkspaceIcon");function Vot({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=DN({id:e.id,disabled:!s});return(0,t.jsxs)(cs,{ref:c,style:{transform:PN.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(Wot,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)(gM,{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)(vs,{className:"size-4 text-foreground"}):null})]})}r(Vot,"SortableCompanyItem");function Hot(e={}){return(0,t.jsx)(qye,{...e,children:(0,t.jsx)(Got,{...e})})}r(Hot,"SidebarCompanyMenu");function Got({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}=gs(),{openOnboarding:p}=Do(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=Fa(),j=b&&!v,N=ra(),w=Ln(),k=e??n,S=s??a,C=MN(Lf(X8,{activationConstraint:{distance:8}}),Lf(vfe,{activationConstraint:{delay:180,tolerance:6}})),I=(0,m.useMemo)(()=>l.filter(ne=>ne.status!=="archived"),[l]),{data:T}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),R=T?.user?.id??T?.session?.userId??null,{orderedCompanies:A,persistOrder:D}=zye({companies:I,userId:R}),{hidden:M,loaded:$}=tu(),E=$&&!lg(M,"company.members")&&!lg(M,"company.invites"),B="company",z=c?.name??null,q=!!Ac(),U=HN({onSignedOut:K});function F(ne){ne||o(!1),S(ne)}r(F,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function G(ne){const he=N.pathname.split("/")[1]?.toUpperCase(),Z=I.some(ce=>ce.issuePrefix.toUpperCase()===he),re=ne.id!==c?.id&&(N.pathname.startsWith("/instance/")||Z);d(ne.id),S(!1),f&&x(!1),re&&w(`/${ne.issuePrefix}/dashboard`)}r(G,"selectCompany");function se(){q||(S(!1),f&&x(!1),p({initialStep:1}))}r(se,"addCompany");const ee=(0,m.useCallback)(ne=>{const{active:he,over:Z}=ne;if(!Z||he.id===Z.id)return;const re=A.map(Q=>Q.id),ce=re.indexOf(he.id),H=re.indexOf(Z.id);ce===-1||H===-1||D(rM(re,ce,H))},[A,D]);return(0,t.jsxs)(ta,{open:k,onOpenChange:F,children:[(0,t.jsx)(ea,{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":z?`Open ${z} ${B} switcher`:`Open ${B} 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:z??void 0,children:z??`Select ${B}`})]}),!j&&(0,t.jsx)(dM,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(sa,{align:"start",sideOffset:8,className:"ml-2 w-(--organization-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"flex h-(--organization-popover-header-height) items-center justify-between gap-2 px-3.5",children:[(0,t.jsx)(db,{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(he=>!he)},"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)(EN,{sensors:C,collisionDetection:CI,onDragEnd:ee,children:(0,t.jsx)(RN,{items:A.map(ne=>ne.id),strategy:kI,children:A.map(ne=>(0,t.jsx)(Vot,{company:ne,isEditing:i,isSelected:ne.id===c?.id,onSelect:G},ne.id))})}),A.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(cs,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(cs,{onSelect:r(ne=>{ne.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(Si,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(cs,{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)(cs,{onClick:se,className:Q$,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(bn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),E?(0,t.jsx)(cs,{asChild:!0,disabled:i,className:Q$,children:(0,t.jsxs)(We,{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)(Yf,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:z?`Invite people to ${z}`:"Invite people"})]})}):null,T?.session?(0,t.jsxs)(cs,{className:Q$,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(Got,"BuiltinCompanyMenu");function pse(){const{openNewIssue:e}=Do(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=gs(),{collapsed:c,peeking:d}=Fa(),u=c&&!d,h=IM(o),{data:p,isFetched:f}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn")}),x=P.liveRuns(o),b=bo({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:j}=X({queryKey:x,queryFn:r(()=>Zr.liveRunsForCompany(o),"queryFn"),enabled:b.enabled,refetchInterval:b.refetchInterval});vo(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,T=p?.enableGoalsSidebarLink===!0,R=p?.enableDecisions===!0,{data:A}=X({queryKey:P.attention(o),queryFn:r(()=>KN.list(o),"queryFn"),enabled:!!o&&R,refetchInterval:6e4}),D=gye(A),M=p?.enableCases===!0,$=!0,E=p?.enableConferenceRoomChat===!0,B={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)(Hot,{})}),(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 z=(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)(a_,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?Fy:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:z}),(0,t.jsx)(Wn,{side:"right",children:"New Task"})]}):z})(),(0,t.jsx)(Ja,{to:"/search",label:"Search",icon:Gr}),(0,t.jsx)(Ja,{to:"/dashboard",label:"Dashboard",icon:Xx,liveCount:N}),(0,t.jsx)(Ja,{to:"/inbox",label:"Inbox",icon:cd,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),R?(0,t.jsx)(Ja,{to:"/decisions",label:"Decisions",icon:Vy,badge:D,badgeLabel:"decisions"}):null,C?(0,t.jsx)(Ja,{to:"/status",label:"Status",icon:qN,textBadge:"beta"}):null,E?(0,t.jsx)(Ja,{to:"/board-chat",label:"Conference Room",icon:D0e}):null]}),(0,t.jsxs)(Zx,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(Ja,{to:"/issues",label:"Tasks",icon:Cu}),M?(0,t.jsx)(Ja,{to:"/cases",label:"Cases",icon:Tl,textBadge:"beta"}):null,(0,t.jsx)(Ja,{to:"/routines",label:"Routines",icon:Tu}),S?(0,t.jsx)(Ja,{to:"/pipelines",label:"Pipelines",icon:to}):null,T?(0,t.jsx)(Ja,{to:"/goals",label:"Goals",icon:bp}):I?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(Ja,{to:"/artifacts",label:"Artifacts",icon:Ih}),(0,t.jsx)(Ja,{to:"/skills",label:"Skills",icon:uc}),w?(0,t.jsx)(Ja,{to:"/workspaces",label:"Workspaces",icon:to}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ja,{to:"/projects",label:"Projects",icon:Po}),(0,t.jsx)(qot,{})]}),(0,t.jsx)(Sp,{slotTypes:["sidebar"],context:B,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(VN,{placementZones:["sidebar"],context:B,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(Bot,{streamlined:$}),(0,t.jsxs)(Zx,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(Ja,{to:"/org",label:"Org",icon:my}),k?(0,t.jsx)(Ja,{to:"/apps",label:"Connectors",icon:E3}):null,(0,t.jsx)(Ja,{to:"/timeline",label:"Timeline",icon:x0}),(0,t.jsx)(Ja,{to:"/costs",label:"Costs",icon:dp}),(0,t.jsx)(Ja,{to:"/activity",label:"Activity",icon:Vl}),(0,t.jsx)(Ja,{to:"/company/settings",label:"Settings",icon:Xd})]}),(0,t.jsx)(Sp,{slotTypes:["sidebarPanel"],context:B,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(pse,"Sidebar");function Qot(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Qot,"isSandboxProviderOnly");function Yot(){const{selectedCompany:e,selectedCompanyId:s}=gs(),{isMobile:n,setSidebarOpen:a}=Fa(),{hidden:i}=tu(),o=r(f=>!i.has(f),"showPage"),l=o("instance.plugins"),c=!!Ac(),{slots:d}=hd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:u}=X({queryKey:s?P.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await Kye.get(s)}catch(f){if(f instanceof un&&(f.status===401||f.status===403))return null;throw f}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:h}=X({queryKey:P.plugins.all,queryFn:r(()=>xl.list(),"queryFn"),enabled:l}),p=(h??[]).filter(f=>!Qot(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)(We,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Mu,{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)(Ja,{to:"/company/settings",label:"General",icon:Du,end:!0}),o("instance.profile")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/profile",label:"Profile",icon:yM,end:!0}),o("company.members")&&(0,t.jsx)(Ja,{to:"/company/settings/members",label:"Members",icon:Eo,badge:u?.joinRequests??0,end:!0}),d.filter(f=>f.routePath).map(f=>(0,t.jsx)(Ja,{to:`/company/settings/${f.routePath}`,label:f.displayName,icon:Jx,end:!0},`${f.pluginKey}:${f.id}`)),o("company.invites")&&(0,t.jsx)(Ja,{to:"/company/settings/invites",label:"Invites",icon:kze,end:!0}),o("company.secrets")&&(0,t.jsx)(Ja,{to:"/company/settings/secrets",label:"Secrets",icon:ki,end:!0}),o("instance.environments")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/environments",label:"Environments",icon:B0e,end:!0}),o("instance.access")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/access",label:"Access",icon:jI,end:!0}),o("instance.heartbeats")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:Jd,end:!0}),o("company.export")&&(0,t.jsx)(Ja,{to:"/company/export",label:"Export",icon:oo}),!c&&o("company.import")&&(0,t.jsx)(Ja,{to:"/company/import",label:"Import",icon:hy,end:!0}),o("instance.experimental")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Pm}),l&&(0,t.jsx)(Ja,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Jx}),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)(cb,{to:`${Jh}/plugins/${f.id}`,state:Jf,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)(Ja,{to:"/company/settings/instance/adapters",label:"Adapters",icon:dm})]})})]})}r(Yot,"CompanySettingsSidebar");function Jot(){const{pathname:e}=ra(),{selectedCompany:s}=gs(),{isMobile:n,setSidebarOpen:a}=Fa(),i=Xye(),{enabled:o}=AM(),l=X7.filter(d=>!Jye(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(R7,{});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|reviews|conversations|activity|approvals|audit))?\/?$/);return c?(0,t.jsx)(Yye,{endpointId:c[1],NavItem:Ja}):(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:[(0,t.jsxs)(We,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Mu,{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)(zJ,{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)(Ja,{to:"/apps",label:"Browse",icon:i_,end:!0}),(0,t.jsx)(Ja,{to:"/apps/review",label:"Review",icon:UN,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)(Ja,{to:"/apps/connections",label:"Connections",icon:zJ,end:!0}),l.map(d=>(0,t.jsx)(Ja,{to:L0(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(Jot,"AppsSidebar");function fse(e){const{selectedCompanyId:s}=gs(),{isMobile:n,setSidebarOpen:a}=Fa(),i=X({queryKey:P.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>es.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=X({queryKey:P.tools.applications(s??"__none__"),queryFn:r(()=>es.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=X({queryKey:P.tools.connections(s??"__none__"),queryFn:r(()=>es.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=X({queryKey:P.apps.gallery(s??"__none__"),queryFn:r(()=>es.listGallery(s),"queryFn"),enabled:!!s}),d=X({queryKey:P.apps.attention(s??"__none__"),queryFn:r(()=>es.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(N=>N.id===e.applicationId):null,p=elt(e.kind==="application"?(l.data?.connections??[]).filter(N=>N.applicationId===e.applicationId):[]),f=u?Ff(u):h?.name??"App",x=Zot(c.data?.apps??[],u,h??void 0),b=u?.id??p?.id??null,v=b?d.data?.apps.find(N=>N.connection.id===b):null,j=(v?.pendingActionRequestCount??0)+((v?.quarantinedCatalogEntryCount??0)>0?1:0);return(0,t.jsxs)("aside",{className:"flex h-full min-h-0 w-full flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 px-3 py-3",children:[(0,t.jsxs)(We,{to:"/apps/connections",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Mu,{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)(Vo,{name:f,logoUrl:WI(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:TM.map(N=>(0,t.jsx)(Ja,{to:Xot(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(fse,"AppDetailSidebar");function Xot(e,s){return e.kind==="connection"?cm(e.connectionId,s):x1(e.applicationId,s)}r(Xot,"tabHref");function Zot(e,s,n){if(n?.applicationKey){const i=e.find(o=>oc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>eg(i).toLowerCase()===a)??e.find(i=>oc(i)===a)??null:null}r(Zot,"galleryEntryFor$1");function elt(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(elt,"latestArchivedConnection$1");function Y$({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(Y$,"CrumbIdentifier");function tlt({context:e}){const{slots:s}=hd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=Q7({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)(VN,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(tlt,"GlobalToolbar");function slt(){const{breadcrumbs:e,mobileToolbar:s}=Fn(),{toggleSidebar:n,isMobile:a}=Fa(),{selectedCompanyId:i,selectedCompany:o}=gs(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(tlt,{context:l});if(a&&s)return(0,t.jsx)("div",{className:"border-b border-border px-2 h-12 shrink-0 flex items-center",children:s});if(e.length===0)return(0,t.jsx)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:c});const d=a&&(0,t.jsx)(L,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(C0e,{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)(Y$,{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)(Z7,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(e9,{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)(U3,{}),(0,t.jsx)(g1,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(h_,{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)(Y$,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(h_,{className:"truncate",children:u.label}):(0,t.jsx)(q3,{asChild:!0,children:u.leading||u.identifier?(0,t.jsxs)(We,{to:u.href,onClick:u.onClick,className:"flex items-center gap-1.5",children:[u.leading&&(0,t.jsx)("span",{className:"flex shrink-0 items-center",children:u.leading}),(0,t.jsx)(Y$,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(We,{to:u.href,onClick:u.onClick,children:u.label})})})]},h)})})})}),c]})}r(slt,"BreadcrumbBar");var U2=240,u6=208,m6=420,xse=16;function A5(e){return Math.min(m6,Math.max(u6,e))}r(A5,"clampSidebarWidth");function gse(e){if(typeof window>"u")return U2;try{const s=window.localStorage.getItem(e);if(!s)return U2;const n=Number.parseInt(s,10);return Number.isFinite(n)?A5(n):U2}catch{return U2}}r(gse,"readStoredSidebarWidth");function bse(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(A5(s)))}catch{}}r(bse,"writeStoredSidebarWidth");function nlt({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)(()=>gse(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=gse(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]),T=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),R=(0,m.useCallback)(E=>{const B=A5(E);v.current=B,f(B),bse(o,B)},[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 B=A5(j.current.startWidth+E.clientX-j.current.startX);v.current=B,f(B)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),bse(o,v.current))},[o]),$=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),R(p-xse)):E.key==="ArrowRight"?(E.preventDefault(),R(p+xse)):E.key==="Home"?(E.preventDefault(),R(u6)):E.key==="End"&&(E.preventDefault(),R(m6)))},[C,R,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:T,"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":u6,"aria-valuemax":m6,"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:$}):null]})})}r(nlt,"SidebarShell");function rlt({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)(Mot,{children:e})})}r(rlt,"SecondarySidebar");var alt="/company/settings/members?tab=invites",ilt="https://docs.paperclip.ing/",olt="https://paperclip.ing/feedback";function llt(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(llt,"deriveInitials$1");function vse({label:e,description:s,icon:n,onClick:a,href:i,external:o=!1,topLevel:l=!1}){const c="flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",d=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(n,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:e}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:s})]})]});return i?o?(0,t.jsx)("a",{href:i,target:"_blank",rel:"noreferrer",className:c,onClick:a,children:d}):l?(0,t.jsx)("a",{href:i,className:c,onClick:a,children:d}):(0,t.jsx)(We,{to:i,className:c,onClick:a,children:d}):(0,t.jsx)("button",{type:"button",className:c,onClick:a,children:d})}r(vse,"MenuAction");function yse({deploymentMode:e,open:s,onOpenChange:n}){const i=!!Ac(),{hidden:o,loaded:l}=tu(),c=tCe(),d=sCe(!i),u=i?c:d?alt:null,h=l&&u!==null&&!lg(o,"company.members")&&!lg(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:b,collapsed:v,peeking:j}=Fa(),N=v&&!j,w=s??p,k=nCe(w),S=n??f,{data:C}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),I=HN({onSignedOut:M}),T=C?.user.name?.trim()||"Board",R=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),A=llt(T),D=rCe(C?.user);function M(){S(!1),x&&b(!1)}r(M,"closeNavigationChrome");function $(){I.mutate()}return r($,"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)(yr,{open:w,onOpenChange:S,children:[(0,t.jsx)(Ir,{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)(So,{size:"sm",children:[C?.user.image?(0,t.jsx)(md,{src:C.user.image,alt:T}):null,(0,t.jsx)(Co,{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:T})]})}),(0,t.jsxs)(lr,{side:"top",align:"start",sideOffset:10,className:"w-(--sz-277px) max-w-(--sz-calc-24) overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl",children:[(0,t.jsx)("div",{className:"h-24 bg-(image:--gradient-extract-25)"}),(0,t.jsxs)("div",{className:"-mt-8 px-4 pb-4",children:[(0,t.jsxs)("div",{className:"relative flex items-start gap-3",children:[(0,t.jsx)(We,{to: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)(So,{size:"lg",children:[C?.user.image?(0,t.jsx)(md,{src:C.user.image,alt:T}):null,(0,t.jsx)(Co,{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:T}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:R}),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)(vse,{label:"Invite",description:"Invite people to your organization.",icon:Yf,href:u,topLevel:i,onClick:M}):null,(0,t.jsx)(vse,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:zN,href:ilt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(hk,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(oCe,{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:$,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)(lCe,{})]})]})]})]}),!N&&!i?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("a",{href:olt,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)(wg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Wn,{side:"top",children:"Share feedback"})]}):null]})})}r(yse,"SidebarAccountMenu");function clt(e,s){return jCe(e,s)[0]?.toLowerCase()??null}r(clt,"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 dlt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function ult(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(ult,"isSkillsStoreRoute");function mlt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=Fa(),{openNewIssue:d,openOnboarding:u}=Do(),{togglePanelVisible:h}=Zf(),p=Gc()?.pushToast??null,{companies:f,loading:x,selectedCompany:b,selectedCompanyId:v,selectionSource:j,setSelectedCompanyId:N}=gs(),{companyPrefix:w,pluginRoutePath:k}=ga(),S=Ln(),C=ra(),I=sM(),T=Vye(C.pathname,w).isTaskDetail,R=["/company/settings","/company/export","/company/import"].some(bt=>C.pathname.includes(bt)),A=jCe(C.pathname,w),D=A[0]?.toLowerCase()==="tools",M=A[0]?.toLowerCase()==="apps",$=M&&A[1]&&!dlt.has(A[1].toLowerCase())?A[1]:null,E=M&&A[1]?.toLowerCase()==="app"&&A[2]?A[2]:null,B=ult(C.pathname,w),z=(0,m.useRef)(!1),q=(0,m.useRef)(null),U=(0,m.useRef)(null),F=(0,m.useRef)(new Dve),K=(0,m.useRef)(C.key),G=pCe(l&&!T,C.pathname),[se,ee]=(0,m.useState)(!1),ne=(0,m.useMemo)(()=>{if(!w)return null;const bt=w.toUpperCase();return f.find(De=>De.issuePrefix.toUpperCase()===bt)??null},[f,w]),he=!!w&&!x&&f.length>0&&!ne,Z=(0,m.useMemo)(()=>k?.toLowerCase()??clt(C.pathname,w),[w,C.pathname,k]),re=ne?.id??null,ce=ne?.issuePrefix??null,{slots:H}=hd({slotTypes:["page","routeSidebar"],companyId:re,enabled:!!(re&&Z)}),Q=(0,m.useMemo)(()=>q7(H,Z),[Z,H]),Y=(0,m.useMemo)(()=>({companyId:re,companyPrefix:ce}),[re,ce]),te=R?(0,t.jsx)(Yot,{}):$?(0,t.jsx)(fse,{kind:"connection",connectionId:$}):E?(0,t.jsx)(fse,{kind:"application",applicationId:E}):M||D?(0,t.jsx)(Jot,{}):Q?(0,t.jsx)(Lu,{slot:Q,context:Y,className:"h-full w-full",missingBehavior:"placeholder"}):null,ae=te!=null,{data:me}=X({queryKey:P.health,queryFn:r(()=>su.get(),"queryFn"),retry:!1,refetchInterval:r(bt=>bt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),oe=ae||B;(0,m.useLayoutEffect)(()=>(c(oe),()=>c(!1)),[oe,c]),(0,m.useEffect)(()=>{x||z.current||me?.deploymentMode!=="authenticated"&&(me?.cloud||f.length===0&&(z.current=!0,u()))},[f,x,u,me?.cloud,me?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!ne){const De=(v?f.find(Qe=>Qe.id===v):null)??f[0]??null;De&&v!==De.id&&N(De.id,{source:"route_sync"});return}if(w!==ne.issuePrefix){const De=C.pathname.replace(/^\/[^/]+/,"");S(`/${ne.issuePrefix}${De}${C.search}`,{replace:!0});return}const bt=fCe({matchedCompany:ne,selectedCompanyId:v,companies:f});if(bt){p?.({title:`${ne.name} is archived`,body:`Switched to ${bt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${ne.id}`}),N(bt.id,{source:"route_sync"}),S(`/${bt.issuePrefix}/dashboard`,{replace:!0});return}xCe({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 ie=h,ge=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),be=(0,m.useRef)(null),le=(0,m.useRef)(!1),ue=(0,m.useRef)(!1),Se=(0,m.useCallback)(()=>{be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),ye=(0,m.useCallback)(()=>{Se(),be.current=window.setTimeout(()=>o(!0),50)},[Se,o]),Ie=(0,m.useCallback)(()=>{Se(),o(!0)},[Se,o]),Ke=(0,m.useCallback)(()=>{Se(),be.current=window.setTimeout(()=>o(!1),120)},[Se,o]),rt=(0,m.useCallback)(()=>{le.current=!0,a&&!ue.current&&ye()},[a,ye]),dt=(0,m.useCallback)(()=>{le.current=!1,ue.current=!1,Ke()},[Ke]),de=(0,m.useCallback)(()=>{ue.current||Ie()},[Ie]),ze=(0,m.useCallback)(()=>{le.current||Ke()},[Ke]);(0,m.useEffect)(()=>Se,[Se]);const gt=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==gt.current&&(a?(Se(),o(!1),ue.current=le.current):ue.current=!1,gt.current=a)},[a,Se,o]),(0,m.useEffect)(()=>{if(!i)return;const bt=r(De=>{De.key==="Escape"&&(Se(),o(!1))},"onKeyDown");return window.addEventListener("keydown",bt),()=>window.removeEventListener("keydown",bt)},[i,Se,o]),hCe(),cCe({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ge,onToggleSidebar:n,onTogglePanel:ie,onShowShortcuts:r(()=>ee(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const bt=30,De=50,Qe=75;let mt=0,Ye=0;const it=r(Ze=>{const Pe=Ze.touches[0];mt=Pe.clientX,Ye=Pe.clientY},"onTouchStart"),Nt=r(Ze=>{const Pe=Ze.changedTouches[0],Ce=Pe.clientX-mt;if(!(Math.abs(Pe.clientY-Ye)>Qe)){if(!e&&mt<bt&&Ce>De){s(!0);return}e&&Ce<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",it,{passive:!0}),document.addEventListener("touchend",Nt,{passive:!0}),()=>{document.removeEventListener("touchstart",it),document.removeEventListener("touchend",Nt)}},[l,e,s]),(0,m.useEffect)(()=>{const bt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=bt}},[l]),(0,m.useEffect)(()=>{if(!l)return bCe()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const bt=U.current;return gCe(bt)},[C.pathname]),(0,m.useEffect)(()=>{const bt=U.current;if(!bt)return;const De=r(()=>{F.current.remember(K.current,bt.scrollTop)},"recordScroll");return bt.addEventListener("scroll",De,{passive:!0}),()=>bt.removeEventListener("scroll",De)},[]),(0,m.useLayoutEffect)(()=>{const bt=U.current,De=Mve({previousPathname:q.current,pathname:C.pathname,navigationType:I,state:C.state});q.current=C.pathname;const Qe=I==="POP",mt=Qe?F.current.recall(C.key):0;if(K.current=C.key,Qe){M3(bt,mt);const Ye=requestAnimationFrame(()=>M3(bt,mt));return()=>cancelAnimationFrame(Ye)}De&&Lve(bt)},[C.key,C.pathname,C.state,I]),(0,t.jsx)(Pve,{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)(qSe,{}),(0,t.jsx)(USe,{devServer:me?.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)(pse,{})})}),(0,t.jsx)(yse,{deploymentMode:me?.deploymentMode})]}):(0,t.jsxs)(nlt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:rt,onPanelMouseLeave:dt,onPanelFocusCapture:a?de:void 0,onPanelBlurCapture:a?ze:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(pse,{})}),(0,t.jsx)(yse,{deploymentMode:me?.deploymentMode})]}),!l&&ae?(0,t.jsx)(rlt,{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)(a6,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(slt,{}),l&&R?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(Qye,{})}):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:he?(0,t.jsx)(Eu,{scope:"invalid_company_prefix",requestedPrefix:w??b?.issuePrefix}):(0,t.jsx)(HSe,{children:(0,t.jsx)(lb,{})})}),(0,t.jsx)(oje,{})]})]})]}),l&&(0,t.jsx)(zSe,{visible:G}),(0,t.jsx)(dje,{}),(0,t.jsx)(Uje,{}),(0,t.jsx)(PSe,{}),(0,t.jsx)(LSe,{}),(0,t.jsx)($Se,{}),(0,t.jsx)(OSe,{open:se,onOpenChange:ee}),(0,t.jsx)(FSe,{}),(0,t.jsx)(BSe,{localTrusted:me?.deploymentMode==="local_trusted"})]})})}r(mlt,"Layout");var jse=null;function hlt(){return jse??=new IN,jse}r(hlt,"getDetachedClient");function plt(){const e=(0,m.useContext)(fI),{data:s,isFetched:n}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn"),enabled:e!=null},e??hlt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(plt,"useConferenceRoomChatEnabled");function flt(){const{enabled:e,loaded:s}=plt();return s?e?(0,t.jsx)(lb,{}):(0,t.jsx)(Nn,{to:"/dashboard",replace:!0}):null}r(flt,"ConferenceRoomChatGate");var xlt=["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"],glt={"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 }"}},Nos=xlt.map(e=>glt[e]);function wCe({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(wCe,"TaskBrowserActivity");function kCe({item:e}){return(0,t.jsx)("article",{className:"rounded-lg border border-border bg-card p-3","aria-label":`Project created: ${e.name}`,children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(xze,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Project created"}),(0,t.jsx)(We,{to:`/projects/${e.projectId}`,className:"break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description&&(0,t.jsx)("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:e.description}),e.repositories.length>0&&(0,t.jsx)("ul",{className:"space-y-1 pt-1",children:e.repositories.map(s=>(0,t.jsxs)("li",{className:"flex min-w-0 items-center gap-2 text-xs text-muted-foreground",children:[(0,t.jsx)(to,{className:"size-3 shrink-0","aria-hidden":!0}),(0,t.jsx)("a",{className:"truncate hover:underline focus-visible:underline",href:s.url,target:"_blank",rel:"noreferrer",children:s.name})]},s.id))})]})]})})}r(kCe,"TaskChatProjectCreatedCard");function blt({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)(Df,{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(blt,"TaskChatSkillCreatedCard");function vlt(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(vlt,"McpIcon");var ylt=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||ylt.has(s)}r(Gd,"isGenericToolName");function TW(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(TW,"mcpToolIdentity");function RW(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(RW,"identifierWords");function NCe(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(NCe,"sentenceCase");function pk(e){const s=(e??"").trim();return Gd(s)?"Unnamed tool":NCe(RW(TW(s)?.name??s))}r(pk,"humanizeToolName");var Nd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),jlt={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"}},wlt={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:[]},klt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function Nlt(e){return RW(e).join("_")}r(Nlt,"normalizedKey");function Slt(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(wlt))if(a.includes(s))return n;return null}r(Slt,"inferredAction");function Clt(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(Clt,"actionFamily");var _lt={terminal:dg,grep:Dze,search:Gr,read:zN,edit:fM,web:rze,plan:Vy,question:Vc,agent:my,safety:Li,image:OI,wait:Jd,mcp:vlt,other:Df};function Ilt(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(Ilt,"actionCopy");function Alt(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(Alt,"defaultSummaryGroup");function Tlt(e){return e==="read"||e==="list"?Nd("paperclip_read","Paperclip read","Paperclip reads"):Nd("task_operation","task operation","task operations")}r(Tlt,"paperclipSummaryGroup");function jy(e){const s=(e.name??"").trim(),n=TW(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=RW(o),c=Nlt(o),d=jlt[c],u=klt[(e.operation??"").trim().toLowerCase()],h=Slt(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":Gd(o)?"unnamed":"fallback",x=Gd(o)?"Unnamed tool":pk(o),b=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&b&&l.length>1?l.slice(1):[],j=v.length?NCe(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}`}:Ilt(p,d?void 0:j),w=d?.family??Clt(p),k=i==="mcp"?"mcp":w,S=a?pk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?Tlt(p):d?.group??Alt(p);return{icon:_lt[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(jy,"toolActivityPresentation");function n4(e){const s=jy({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(n4,"toolTaxonomy");function Rlt(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?Yx:s==="responding"||s.startsWith("responding (")?Nze:null}r(Rlt,"statusLabelIcon");var J$=["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"],X$=["Brewing","Tinkering","Distilling","Deliberating"],wse=(()=>{const e=[],s=Math.max(J$.length,X$.length);for(let n=0;n<s;n++)n<J$.length&&e.push(J$[n]),n<X$.length&&e.push(X$[n]);return e})(),Elt=1e4;function Plt(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(Plt,"isGenericStatusLabel");function Mlt(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(Mlt,"fnv1a");function Dlt(e,s=0){const n=Math.floor(Math.max(0,s)/Elt);return wse[(Mlt(e)+n)%wse.length]}r(Dlt,"whimsyWord");var Llt=[{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}],Sos=Array.from(new Set(Llt.map(e=>e.group)));function SCe(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(SCe,"parseCssTimeMs");function $lt(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($lt,"elapsedLabel");function Olt(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(Olt,"liveElapsedLabel");function Flt(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(Flt,"useLiveElapsedMs");function Blt(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(Blt,"lineScrollOffset");function mE(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=SCe(s);return Number.isFinite(n)?n:0}r(mE,"motionTokenMs");function zlt({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(Blt(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),mE("--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(zlt,"LiveSelfTalkLine");function qlt(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)},mE("--motion-line-scroll")))},mE("--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=mE("--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(qlt,"useHeldSelfTalk");var Ult={running:{Icon:nt,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:nt,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:UN,spin:!1,tone:"text-primary"},interrupted:{Icon:y7,spin:!1,tone:"text-destructive"},refused:{Icon:um,spin:!1,tone:"text-destructive"},truncated:{Icon:Mze,spin:!1,tone:"text-(--status-agent-paused)"}};function CCe({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=Ult[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=Flt(e.startedAtMs,d),h=qlt(d?e.selfTalk:void 0,d),p=$lt(e.elapsedMs);if(d){const f=Olt(u??e.elapsedMs),x=e.selfTalk!=null,b=e.toolName?n4(e.toolName).icon:x?null:Rlt(e.label),v=x||Plt(e.label)?Dlt(e.id,u??e.elapsedMs??0):e.label,j=(0,t.jsxs)("div",{className:"tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground",children:[n!==void 0?(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-caret-slot",children:(0,t.jsx)(Pn,{className: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)(zlt,{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(CCe,"TaskChatStatusPill");var Cg=(0,m.createContext)(null);function Xy(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(Xy,"formatBytes$4");var T5=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),Klt=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],Wlt=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],Vlt=new Set(["application/wasm"]),Hlt=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),_Ce=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),Glt=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"]),Qlt=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function rA(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(rA,"normalizeOutputContentType");function Ylt(e){const s=(e??"").trim().toLowerCase();return s?Qlt.some(n=>s.endsWith(n)):!1}r(Ylt,"hasDocumentLikeFilename");function ICe(e){return Hlt.has(e)||e.endsWith("+zip")}r(ICe,"isZipContentType");function Jlt(e){return e?!!(e.startsWith("text/")||_Ce.has(e)||Glt.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Jlt,"isDocumentLikeOutputContentType");function Xlt(e,s){const n=rA(e);return!n||Jlt(n)||T5.has(n)&&Ylt(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||Vlt.has(n)||ICe(n)||T5.has(n)}r(Xlt,"isOutputEligibleContentType");function Zlt(e){const s=rA(e);if(s.startsWith("video/")){const n=s.slice(6);return n==="quicktime"?{label:"MOV",tone:"video"}:{label:(n||"vid").toUpperCase().slice(0,4),tone:"video"}}return s==="application/pdf"?{label:"PDF",tone:"pdf"}:ICe(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:_Ce.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(Zlt,"getOutputFileGlyph");function $u(e,s){const n=rA(e);if(n.startsWith("video/"))return!0;if(!T5.has(n))return!1;const a=(s??"").trim().toLowerCase();return Klt.some(i=>a.endsWith(i))}r($u,"isVideoLikeOutput");function wy(e){const s=rA(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(wy,"isImageContentType");function r4(e,s){const n=rA(e);if(wy(n))return!0;if(n&&!T5.has(n))return!1;const a=(s??"").trim().toLowerCase();return Wlt.some(i=>a.endsWith(i))}r(r4,"isImageLikeOutput");function kse(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(kse,"toTime");function a4(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=RLe.safeParse(n.metadata);return a.success&&!Xlt(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:kse(a.createdAt)-kse(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(a4,"getIssueOutputs");function EW(e){return e.metadata?.originalFilename||e.title||"output"}r(EW,"outputFilename");function ACe(e){return new Set(a4(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(ACe,"getPromotedOutputAttachmentIds");function ect(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(ect,"normalizedContentType");function sb(e){return e.originalFilename??e.id}r(sb,"attachmentFilename");function i4(e){return e.openPath??e.contentPath}r(i4,"attachmentOpenPath");function nS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(nS,"attachmentDownloadPath");function TCe(e){const s=ect(e);return r4(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(TCe,"isImageAttachment$1");function RCe(e){return $u(e.contentType,e.originalFilename)}r(RCe,"isVideoAttachment");function ECe(e){return wpe(e)}r(ECe,"isMarkdownAttachment");function Zy(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return wpe(e)||s.startsWith("text/")||/^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(s)||["","application/octet-stream"].includes(s)&&/\.(txt|log|csv|json|yaml|yml|toml|ini|sh|ts|tsx|js|jsx|py|css|html)$/i.test(e.originalFilename??"")}r(Zy,"isTextAttachment");function PCe(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(PCe,"downloadBlob$1");function tct(e,s,n){PCe(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(tct,"downloadTextFile");var Z$="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 MCe({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,T)=>{c(I),p(null);try{await T(),u(I)}catch(R){u(null),p(R instanceof Error?R.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),N=(0,m.useCallback)(async()=>i??(await At.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:Z$,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)(vs,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(Ar,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:Z$,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 T=$Fe(a);tct(LJ(n,T),await N(),T==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(oo,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:Z$,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()=>{PCe(LJ(n,"pdf"),await At.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(pze,{"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(MCe,"DocumentExportActions");function M_({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(M_,"PreviewFrame");function R5({label:e}){return(0,t.jsx)(M_,{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)(Hc,{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(R5,"PlaceholderPreview");function sct({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(R5,{label:"Image"}):(0,t.jsx)(M_,{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(sct,"ImagePreview");function nct({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)(M_,{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)(so,{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)(M_,{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)(so,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(nct,"VideoPreview");function rct({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(M_,{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)(R5,{label:e.source==="document"?"Document":"Text"})}r(rct,"TextPreview");function aA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(sct,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(nct,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(rct,{artifact:e});case"file":return(0,t.jsx)(R5,{label:"File"});default:return(0,t.jsx)(R5,{})}}r(aA,"ArtifactPreview");function Nse({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(Nse,"SecondaryAction");function act({artifact:e}){return(0,t.jsxs)(We,{to:e.href,disableIssueQuicklook:!0,"data-testid":"artifact-card","data-media-kind":e.mediaKind,className:"group flex flex-col overflow-hidden rounded-lg border border-border bg-card cursor-pointer transition-colors hover:border-foreground/20 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,t.jsx)(aA,{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)(MCe,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Nse,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)(qn,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Nse,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(oo,{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(act,"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 DCe(e,s){return X({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(DCe,"useEmailThread");var LCe=(0,m.createContext)(null);function ict({companyId:e,issueId:s,children:n}){const a=DCe(e,s);return(0,t.jsx)(LCe.Provider,{value:a.data??null,children:n})}r(ict,"EmailThreadProvider");function $Ce(e){const s=(0,m.useContext)(LCe),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(OCe,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r($Ce,"useEmailComment");function OCe({message:e,publication:s,issueId:n}){const a=X({queryKey:["email-attachments",n],queryFn:r(()=>At.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)(H8,{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)(Hc,{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(OCe,"EmailMessageCard");var Qv=(0,m.createContext)(null);function ej({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=sb(p),x=$u(p.contentType,p.originalFilename);return(0,t.jsx)(FOe,{open:n,onOpenChange:a,children:(0,t.jsxs)($Oe,{children:[(0,t.jsx)(OOe,{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)(UOe,{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:nS(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)(oo,{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)(Vn,{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)(Mu,{className:"h-7 w-7"})})}),(0,t.jsx)("div",{className:"flex-1 flex items-center justify-center min-w-0 min-h-0 h-full px-2",children:x?(0,t.jsx)("video",{ref:c,src:p.contentPath,className:"max-w-full max-h-full rounded-lg",controls:!0,playsInline:!0}):(0,t.jsx)("img",{ref:c,src:p.contentPath,alt:f,className:"max-w-full max-h-full object-contain select-none rounded-lg",draggable:!1})}),(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:d,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Next",children:(0,t.jsx)(Pn,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(ej,"ImageGalleryModal");var PW=(0,m.createContext)(null);function oct({value:e,children:s}){return(0,t.jsx)(PW.Provider,{value:e,children:s})}r(oct,"DispositionRecoveryProvider");function lct(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(lct,"readDispositionRecoverySnapshot");function FCe(e){return lct(e,(0,m.useContext)(PW)?.issue.activeRecoveryAction)}r(FCe,"useDispositionRecoverySnapshot");function cct(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(cct,"dispositionRetryUnavailableReason");function dct(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(dct,"descriptionFor");function MW({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(PW),[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=cct(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?vs:Ds;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}.`:dct(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)(nt,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ni,{"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:Zi(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(MW,"DispositionRecoveryNotice");var BCe={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:$f,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:$f,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:la,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:Ds,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:Bk,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 uct(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(uct,"formatTimestamp$1");function mct({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(mct,"MetadataRow$1");function zCe({sections:e,tone:s="neutral"}){const n=BCe[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)(mct,{row:o,tone:n},l))})]},i))})}r(zCe,"SystemNoticeMetadataSections");function DW({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=BCe[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:uct(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)(zCe,{sections:i,tone:e})}):null]})}r(DW,"SystemNotice");var hct="System update",pct=80;function fct(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(fct,"retryFailureCode");function xct(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(xct,"recoveryOwnerName");function gct(e){const s=e.split(`
|
|
355
|
+
`)}`:void 0}r(Uit,"sanitizeComponentStack");function WSe(){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(WSe,"readBrowserErrorState");function Kit(e){const s=Uit(e.componentStack);return{tags:{react_error_boundary:e.boundary},contexts:{react:s?{componentStack:s}:{},browser_state:WSe()}}}r(Kit,"buildBrowserErrorContext");var ase=Promise.resolve();function AW(e){const s=ase.then(e);return ase=s.catch(()=>{}),s}r(AW,"enqueue");var aN=null;function Wit(e,s){return AW(async()=>{if(!aN)try{const n=await Wc(()=>import("./prod-COP_vZWu.js"),__vite__mapDeps([4,5]));n.init(Hit(e,s)),aN=n}catch{}})}r(Wit,"initBrowserErrorMonitoring");function Vit(){return AW(async()=>{const e=aN;if(aN=null,!e)return;const s=e.getClient();try{e.getCurrentScope().setClient(void 0)}catch{}try{await s?.close(2e3)}catch{}})}r(Vit,"teardownBrowserErrorMonitoring");function VSe(e,s){let n;try{s&&(n=Kit(s))}catch{}AW(async()=>{try{n?aN?.captureException(e,n):aN?.captureException(e)}catch{}})}r(VSe,"captureBrowserException");function Hit(e,s){return{dsn:e,environment:s??void 0,release:"db8b3c1c49bb1049755d4f96ba6b166784bee8a9",tracesSampleRate:0,sendDefaultPii:!1,beforeSend:r((n,a)=>{try{if(n.contexts={...n.contexts,browser_state:n.contexts?.browser_state??WSe()},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(Hit,"buildBrowserSentryInitOptions");var Git=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){VSe(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 HSe({children:e}){const s=ra(),n=Ln(),a=`${s.pathname}${s.search}`;return(0,t.jsx)(Git,{resetKey:a,onReset:r(()=>n(-1),"onReset"),children:e})}r(HSe,"RouteErrorBoundary");var ise={bot:Ji,cpu:dm,brain:Yx,zap:f3,rocket:r$e,code:Hfe,terminal:dg,shield:jI,eye:Ed,search:Gr,wrench:Df,hammer:tM,lightbulb:yI,sparkles:Np,star:vp,heart:RC,flame:T$e,bug:zv,cog:Upe,database:wI,globe:Ap,lock:dd,mail:H8,"message-square":Qx,"file-code":Nl,"git-branch":to,package:Ih,puzzle:Jx,target:bp,wand:_7,atom:N$e,"circuit-board":oze,radar:s$e,swords:zze,telescope:d$e,microscope:Sze,crown:qpe,gem:Gfe,hexagon:Ad,pentagon:Aze,fingerprint:Cz},Qit="bot";function Yit(e){return e&&OLe.includes(e)?ise[e]:ise[Qit]}r(Yit,"getAgentIcon");function S5({icon:e,className:s}){const n=Yit(e);return(0,t.jsx)(n,{className:s})}r(S5,"AgentIcon");function GSe({open:e,onOpenChange:s,...n}){return(0,t.jsx)(Vs,{open:e,onOpenChange:s,children:(0,t.jsxs)(Qs,{"aria-describedby":void 0,className:"gap-0 overflow-hidden p-0 sm:max-w-md",children:[(0,t.jsxs)("div",{className:"px-4 pt-4 pb-3",children:[(0,t.jsx)(Js,{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)(Jit,{...n,onComplete:r(()=>s(!1),"onComplete")},String(e))]})})}r(GSe,"AgentChatPicker");function Jit({agents:e,onSelect:s,onComplete:n,loading:a,error:i,onRetry:o,existingChatAgentIds:l,renderAgentIcon:c}){const d=(0,m.useRef)(!1),u=(0,m.useRef)(null);(0,m.useEffect)(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(null),[b,v]=(0,m.useState)(null);async function j(N){if(f)return;x(N.id),v(null);const w=new AbortController;u.current=w;try{await s(N,w.signal),d.current&&n()}catch(k){v(k instanceof Error?k.message:"Couldn’t open chat. Try again.")}finally{x(null)}}return r(j,"selectAgent"),(0,t.jsxs)(_I,{children:[(0,t.jsx)(LN,{"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)($N,{children:[(0,t.jsx)(ON,{children:(0,t.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4",children:[(0,t.jsx)("span",{children:e.length?`No agents match “${h}”`:"No agents yet."}),e.length?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Try another name or role."}),(0,t.jsx)(L,{variant:"ghost",size:"sm",onClick:r(()=>p(""),"onClick"),children:"Clear search"})]}):(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:"Create an agent from the Agents page to start chatting."})]})}),(0,t.jsx)(ju,{children:e.map(N=>(0,t.jsxs)(To,{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)(S5,{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(Jit,"AgentChatPickerResults");function uE({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=Ln(),[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(),T=e.filter(A=>`${A.name} ${A.title??""} ${A.role}`.toLocaleLowerCase().includes(I));function R(){k(""),S.current?.focus()}return r(R,"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)(bn,{className:"size-4"})})]}),(0,t.jsxs)("div",{className:"relative",children:[(0,t.jsx)(Gr,{"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)(pt,{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:R,children:(0,t.jsx)(Vn,{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":`${T.length} ${T.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))}):T.length?(0,t.jsx)("nav",{"aria-label":"Agent conversations",className:"flex flex-col gap-1",children:T.map(A=>(0,t.jsxs)(We,{to:`/chats/${encodeURIComponent(A.status==="terminated"?A.id:Wl(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)(_r,{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:R,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)(Eo,{className:"size-4"}),"Browse all agents"]}):(0,t.jsxs)(We,{to:"/agents/all",children:[(0,t.jsx)(Eo,{className:"size-4"}),"Browse all agents"]})})}),(0,t.jsx)(GSe,{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)(_r,{agent:A,size:32}),"renderAgentIcon"),onSelect:r(async(A,D)=>{p?await p(A,D):u?await u(A,D):v(`/chats/${encodeURIComponent(Wl(A))}`),D?.aborted||k("")},"onSelect")})]})}r(uE,"AgentConversationSidebar");var C5={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 QSe(){const{selectedCompanyId:e}=gs(),{enabled:s,loaded:n}=Qy(),a=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn")}),i=a.data?.user?.id??a.data?.session?.userId??null;return{companyId:e,userId:i,enabled:s,loaded:n,agents:X({queryKey:P.agents.list(e),queryFn:r(()=>Lt.list(e),"queryFn"),enabled:s&&!!e}),chats:X({queryKey:P.agentChats.list(e,i),queryFn:r(()=>C5.list(e),"queryFn"),enabled:s&&!!e&&a.isSuccess}),session:a}}r(QSe,"useAgentChatNavigation");function YSe(e,s){const n=Mt(),a=Ln(),{isMobile:i,setSidebarOpen:o}=Fa(),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 C5.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(Wl(c))}`),i&&o(!1))},[n,e,s,a,i,o])}r(YSe,"useOpenAgentChat");function Xit(){const{companyId:e,userId:s,agents:n,chats:a,session:i}=QSe(),o=YSe(e,s),l=Ln(),c=Xf(e),{isMobile:d,setSidebarOpen:u}=Fa(),{pathname:h}=ra(),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=yp({queries:x.map(C=>({queryKey:P.agents.detail(C),queryFn:r(()=>Lt.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(Wl(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||Bf(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)(uE,{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:Wl(C))}`),d&&u(!1)},"onSelect")},`${e}:${s}`)}r(Xit,"AgentConversationsSidebar");var z2=240,i6=208,o6=420,ose=16;function _5(e){return Math.min(o6,Math.max(i6,e))}r(_5,"clampSidebarWidth$1");function lse(e){if(typeof window>"u")return z2;try{const s=window.localStorage.getItem(e);if(!s)return z2;const n=Number.parseInt(s,10);return Number.isFinite(n)?_5(n):z2}catch{return z2}}r(lse,"readStoredSidebarWidth$1");function cse(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(_5(s)))}catch{}}r(cse,"writeStoredSidebarWidth$1");function Zit({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)(()=>lse(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=lse(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]),T=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),R=(0,m.useCallback)(E=>{const B=_5(E);v.current=B,f(B),cse(o,B)},[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 B=_5(j.current.startWidth+E.clientX-j.current.startX);v.current=B,f(B)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),cse(o,v.current))},[o]),$=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),R(p-ose)):E.key==="ArrowRight"?(E.preventDefault(),R(p+ose)):E.key==="Home"?(E.preventDefault(),R(i6)):E.key==="End"&&(E.preventDefault(),R(o6)))},[C,R,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:T,"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":i6,"aria-valuemax":o6,"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:$,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(Zit,"SidebarShell$1");function q2({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)(Ove,{children:e})})}r(q2,"SecondarySidebar$1");var JSe={listStacks:r(()=>Te.get("/cloud/stacks"),"listStacks")};function s4(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(s4,"cloudAppUrl");function XSe(e){return s4(e,"/stacks/new")}r(XSe,"cloudStackCreateUrl");function ZSe(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(ZSe,"tenantSignInReturnPath");function eot(e,s,n){const a=s?.trim();if(!a)return null;const i=s4(e,`/v1/stacks/${encodeURIComponent(a)}/entry-redirect`);if(!i)return null;const o=new URL(i);return o.searchParams.set("returnTo",ZSe(n)),o.toString()}r(eot,"cloudStackEntryUrl");function eCe(e,s){const n=s?.trim();return n?s4(e,`/workspaces/${encodeURIComponent(n)}/settings?section=people`):null}r(eCe,"cloudStackInviteUrl");function tot(e){return s4(e,"/orgs?manage=1")}r(tot,"cloudPortfolioManageUrl");function tCe(){const e=Ac(),s=!!e,n=X({queryKey:P.cloud.stacks,queryFn:r(()=>JSe.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:eCe(e.cloudBaseUrl,a.stackSlug)}r(tCe,"useCloudInviteUrl");function sot(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(sot,"canInviteCompanyMembers");function sCe(e=!0){const s=rLe(),n=X({queryKey:P.access.currentBoardAccess,queryFn:r(()=>hr.getCurrentBoardAccess(),"queryFn"),enabled:e,retry:!1,staleTime:3e4});return e&&sot(s?.selectedCompanyId,n.data)}r(sCe,"useCanInviteCompanyMembers");function nCe(e){const s=window.location.hostname.endsWith(".staging.paperclip.app"),{data:n,isError:a}=X({queryKey:P.stagingCommit,queryFn:r(()=>su.get(),"queryFn"),enabled:s&&e,staleTime:0,retry:!1});return s&&!a?n?.commit??null:null}r(nCe,"useStagingCommit");function not(e){return e?.trim().toLowerCase().replace(/['"]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}r(not,"slugifyUserPart");function rCe(e){const s=[e?.id,e?.name,e?.email?.split("@")[0],e?.email];for(const n of s){const a=not(n);if(a)return`/u/${a}`}return"/u/me"}r(rCe,"userProfilePath");var rot="Toggle the app appearance.";function hk({className:e,variant:s="icon",onAfterToggle:n}){const{theme:a,toggleTheme:i}=SFe(),o=a==="dark",l=o?"Switch to light mode":"Switch to dark mode",c=o?Kbe:U0e;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:rot})]})]}):(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(hk,"ThemeToggle");var P_=null,aCe=!1,l6=!1,c6=new Set;function I5(){for(const e of c6)e()}r(I5,"emit");function aot(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(aot,"isIosSafariLike");function iot(e=window){const s=r(a=>{a.preventDefault(),P_=a,I5()},"onPrompt"),n=r(()=>{P_=null,aCe=!0,I5()},"onInstalled");return e.addEventListener("beforeinstallprompt",s),e.addEventListener("appinstalled",n),()=>{e.removeEventListener("beforeinstallprompt",s),e.removeEventListener("appinstalled",n)}}r(iot,"captureInstallPrompt");function oot(){return aCe||r6()?"installed":P_?"prompt":aot()?"ios-manual":"unavailable"}r(oot,"installAvailability");async function lot(){const e=P_;if(!e)return"unavailable";P_=null,I5(),await e.prompt();const{outcome:s}=await e.userChoice;return s}r(lot,"promptInstall");function d6(e){l6!==e&&(l6=e,I5())}r(d6,"setIosInstallHelpOpen");function cot(){return l6}r(cot,"iosInstallHelpOpen");function dot(){return(0,m.useSyncExternalStore)(iCe,cot,()=>!1)}r(dot,"useIosInstallHelpOpen");function iCe(e){return c6.add(e),()=>{c6.delete(e)}}r(iCe,"subscribe$1");function uot(){return(0,m.useSyncExternalStore)(iCe,oot,()=>"unavailable")}r(uot,"useInstallAvailability");var dse="Install app",mot="Add Paperclip to your home screen or dock.";function oCe({variant:e,onAfterAction:s}){const n=uot();if(n==="installed"||n==="unavailable")return null;const a=r(()=>{n==="ios-manual"?d6(!0):lot(),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)(oo,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:dse})]}):(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)(oo,{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:dse}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:mot})]})]})}r(oCe,"InstallAppMenuAction");function hot(){const e=dot();return(0,t.jsx)(Vs,{open:e,onOpenChange:d6,children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Install Paperclip"}),(0,t.jsx)(yn,{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)(V$,{index:1,icon:(0,t.jsx)(Oze,{className:"size-4"}),children:["Tap ",(0,t.jsx)("strong",{children:"Share"})," in the Safari toolbar."]}),(0,t.jsxs)(V$,{index:2,icon:(0,t.jsx)(Bze,{className:"size-4"}),children:["Choose ",(0,t.jsx)("strong",{children:"Add to Home Screen"}),"."]}),(0,t.jsxs)(V$,{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)(mr,{children:(0,t.jsx)(L,{type:"button",onClick:r(()=>d6(!1),"onClick"),children:"Done"})})]})})}r(hot,"IosInstallHelpDialog");function V$({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(V$,"InstallStep");function pot(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(pot,"formatTimestamp$2");function fot(e){return!!e&&!Number.isNaN(new Date(e).getTime())}r(fot,"isValidTimestamp");function xot(e){return e?.devServer?.lastRestartAt??e?.serverInfo?.processStartedAt??null}r(xot,"restartTimestamp");function got(e){const s=e?.serverInfo?.git;return s?.available?`${s.shortSha} · ${s.subject}`:"Commit unavailable"}r(got,"commitLabel");function bot(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(bot,"localChangesLabel");function H$({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(H$,"ServerInfoRow");function lCe(){const e=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn")}).data?.enableServerInfoDebugView===!0,s=X({queryKey:P.health,queryFn:r(()=>su.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=xot(n),l=fot(o),c=i?"Health unavailable":a?"Loading...":pot(o),d=i?"Health unavailable":a?"Loading...":got(n),u=i?"Health unavailable":a?"Loading...":bot(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)(H$,{icon:Jd,label:"Last restarted",value:c,dateTime:!i&&!a&&l?o:null}),(0,t.jsx)(H$,{icon:f7,label:"Running commit",value:d}),(0,t.jsx)(H$,{icon:hze,label:"Checkout state",value:u})]})}r(lCe,"SidebarServerInfo");var vot="/company/settings/members?tab=invites",yot="https://docs.paperclip.ing/",jot="https://paperclip.ing/feedback";function wot(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(wot,"deriveInitials$2");function G$({label:e,icon:s,onClick:n,href:a,external:i=!1,topLevel:o=!1}){const l="flex h-(--profile-popover-row-height) w-full items-center gap-(--profile-popover-row-gap) rounded-lg px-2.5 text-left text-(length:--text-compact) font-medium leading-(--profile-popover-label-line-height) text-foreground transition-colors hover:bg-accent",c=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(s,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e})]});return a?i?(0,t.jsx)("a",{href:a,target:"_blank",rel:"noreferrer",className:l,onClick:n,children:c}):o?(0,t.jsx)("a",{href:a,className:l,onClick:n,children:c}):(0,t.jsx)(We,{to:a,className:l,onClick:n,children:c}):(0,t.jsx)("button",{type:"button",className:l,onClick:n,children:c})}r(G$,"MenuAction$1");function use({deploymentMode:e,open:s,onOpenChange:n,forceExpanded:a=!1}){const o=!!Ac(),{hidden:l,loaded:c}=tu(),d=tCe(),u=sCe(!o),h=o?d:u?vot:null,p=c&&h!==null&&!lg(l,"company.members")&&!lg(l,"company.invites"),[f,x]=(0,m.useState)(!1),{isMobile:b,setSidebarOpen:v,collapsed:j,peeking:N}=Fa(),w=j&&!N&&!a,k=s??f,S=nCe(k),C=n??x,{data:I}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),T=HN({onSignedOut:$}),R=I?.user.name?.trim()||"Board",A=I?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),D=wot(R),M=rCe(I?.user);function $(){C(!1),b&&v(!1)}r($,"closeNavigationChrome");function E(){T.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)(yr,{open:k,onOpenChange:C,children:[(0,t.jsx)(Ir,{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)(So,{size:"sm",children:[I?.user.image?(0,t.jsx)(md,{src:I.user.image,alt:R}):null,(0,t.jsx)(Co,{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:R})]})}),(0,t.jsxs)(lr,{side:"top",align:"start",sideOffset:10,className:"min-h-(--profile-popover-min-height) w-(--profile-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"relative flex h-(--profile-popover-header-height) shrink-0 items-center gap-2.5 px-3.5",children:[(0,t.jsx)(We,{to:M,"aria-label":"View profile",onClick:$,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)(So,{className:"pointer-events-none relative size-9",children:[I?.user.image?(0,t.jsx)(md,{src:I.user.image,alt:R}):null,(0,t.jsx)(Co,{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:R}),(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)(G$,{label:"Settings",icon:Xd,href:"/company/settings",onClick:$}),p&&h?(0,t.jsx)(G$,{label:"Invite",icon:Yf,href:h,topLevel:o,onClick:$}):null,(0,t.jsx)(G$,{label:"Documentation",icon:zN,href:yot,external:!0,onClick:r(()=>C(!1),"onClick")}),(0,t.jsx)(hk,{variant:"compact-menu-action",onAfterToggle:r(()=>C(!1),"onAfterToggle")}),(0,t.jsx)(oCe,{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",T.isPending&&"cursor-not-allowed opacity-60"),onClick:E,disabled:T.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:T.isPending?"Signing out...":"Sign out"})]}):null,(0,t.jsx)(lCe,{})]})]})]}),!w&&!o?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("a",{href:jot,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)(wg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Wn,{side:"top",children:"Share feedback"})]}):null]})})}r(use,"SidebarAccountMenu$1");function cCe({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=gfe({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(!SI(b.target)&&!wp()){if(b.key==="/"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),vOe()||s?.();return}if(b.key==="?"&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault(),i?.();return}b.key==="c"&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&(b.preventDefault(),e?.()),b.key==="["&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),n?.()),b.key==="]"&&!b.metaKey&&!b.ctrlKey&&(b.preventDefault(),a?.())}}r(p,"handleKeyDown");const f=r(()=>u(),"handlePointerDown"),x=r(b=>{b.target instanceof HTMLElement&&b.target!==document.body&&u()},"handleFocusIn");return document.addEventListener("pointerdown",f,!0),document.addEventListener("focusin",x,!0),document.addEventListener("keydown",p),()=>{u(),document.removeEventListener("pointerdown",f,!0),document.removeEventListener("focusin",x,!0),document.removeEventListener("keydown",p)}},[e,s,n,a,i,o])}r(cCe,"useKeyboardShortcuts");var kot=new Set(["auth","invite","board-claim","cli-auth","docs","s"]);function dCe(e){const s=(e.split("?")[0]??"").split("/").filter(Boolean);if(s.length===0)return!0;const[n]=s;return!kot.has(n)}r(dCe,"isRememberableCompanyPath");function Not(e){const s=iy(e.companyPrefix);return e.companies.find(n=>iy(n.issuePrefix)===s)??null}r(Not,"findCompanyByPrefix");function Sot(e){const s=G8(e.pathname);return s?Not({companies:e.companies,companyPrefix:s})?.id??null:e.fallbackCompanyId}r(Sot,"getRememberedPathOwnerCompanyId");function Cot(e){const s=e.path?nM(e.path):"/dashboard";if(!dCe(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&&iy(i[1]??"")!==iy(e.companyPrefix))return"/dashboard"}return s}r(Cot,"sanitizeRememberedPathForCompany");var uCe="paperclip.companyPaths";function mCe(){try{const e=localStorage.getItem(uCe);if(e)return JSON.parse(e)}catch{}return{}}r(mCe,"getCompanyPaths");function _ot(e,s){const n=mCe();n[e]=s,localStorage.setItem(uCe,JSON.stringify(n))}r(_ot,"saveCompanyPath");function hCe(){const{companies:e,selectedCompanyId:s,selectedCompany:n,selectionSource:a}=gs(),i=ra(),o=Ln(),l=(0,m.useRef)(s),c=(0,m.useMemo)(()=>Sot({companies:e,pathname:i.pathname,fallbackCompanyId:l.current}),[e,i.pathname]),d=i.pathname+i.search;(0,m.useEffect)(()=>{const u=c,h=nM(d);u&&dCe(h)&&_ot(u,h)},[d,c]),(0,m.useEffect)(()=>{if(s){if(l.current!==null&&s!==l.current&&a!=="route_sync"&&n){const u=mCe(),h=Cot({path:u[s],companyPrefix:n.issuePrefix});o(`/${n.issuePrefix}${h}`,{replace:!0})}l.current=s}},[n,s,a,o])}r(hCe,"useCompanyPageMemory");var Iot=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 pCe(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 Iot({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(pCe,"useMobileNavVisibility");function fCe(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(fCe,"resolveArchivedCompanyBounce");function Aot(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(Aot,"resolveCompanyArchiveDeparture");function xCe(e){const{selectionSource:s,selectedCompanyId:n,routeCompanyId:a}=e;return!(n===a||s==="manual"&&n)}r(xCe,"shouldSyncCompanySelectionFromRoute");function Tot(e,s){return e instanceof HTMLElement?!(s instanceof HTMLElement)||!document.contains(s)||s===document.body||s===document.documentElement?!0:!e.contains(s):!1}r(Tot,"shouldFocusMainContentAfterNavigation");function gCe(e){if(!(e instanceof HTMLElement))return()=>{};const s=window.requestAnimationFrame(()=>{Tot(e,document.activeElement)&&e.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(s)}r(gCe,"scheduleMainContentFocus");function bCe(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(bCe,"pinDocumentScrollToZero");function Eu({scope:e="global",requestedPrefix:s}){const n=ra(),{setBreadcrumbs:a}=Fn(),{companies:i,selectedCompany:o}=gs();(0,m.useEffect)(()=>{a([{label:"Not Found"}])},[a]);const l=o??i[0]??null,c=l?`/${l.issuePrefix}/dashboard`:"/",d=`${n.pathname}${n.search}${n.hash}`,u=s?.toUpperCase(),h=e==="invalid_company_prefix"?"Organization not found":"Page not found",p=e==="invalid_company_prefix"?`No organization matches prefix "${u??"unknown"}".`:"This route does not exist.";return(0,t.jsx)("div",{className:"mx-auto max-w-2xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 p-2",children:(0,t.jsx)(Ds,{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)(We,{to:c,children:[(0,t.jsx)(h3,{className:"mr-1.5 h-4 w-4"}),"Open dashboard"]})}),(0,t.jsx)(L,{variant:"outline",asChild:!0,children:(0,t.jsx)(We,{to:"/",children:"Go home"})})]})]})})}r(Eu,"NotFoundPage");function Rot(e,s){return Wye(e,s)[0]?.toLowerCase()??null}r(Rot,"getCompanyRouteSegment$1");var Eot=new Set(["browse","connections","connect","chat","vercel-connect","review","attention","gateways","advanced","app"]);function Pot({sidebarSections:e}){const{sidebarOpen:s,setSidebarOpen:n,toggleSidebar:a,collapsed:i,peeking:o,setPeeking:l,isMobile:c,setForceCollapsed:d}=Fa(),{openNewIssue:u,openOnboarding:h}=Do(),{togglePanelVisible:p}=Zf(),f=Gc()?.pushToast??null,{companies:x,loading:b,selectedCompany:v,selectedCompanyId:j,selectionSource:N,setSelectedCompanyId:w}=gs(),{companyPrefix:k,pluginRoutePath:S,agentId:C,routineId:I}=ga(),T=Ln(),R=ra(),A=sM(),{enabled:D}=fc(),M=Vye(R.pathname,k),$=M.builtInContextualSurface==="settings",E=M.companySegments,B=M.isTaskDetail,{enabled:z}=Qy(),q=z&&E[0]?.toLowerCase()==="chats",U=D&&(B||q),F=E[0]?.toLowerCase()==="tools",K=E[0]?.toLowerCase()==="apps",G=K&&E[1]&&!Eot.has(E[1].toLowerCase())?E[1]:null,se=K&&E[1]?.toLowerCase()==="app"&&E[2]?E[2]:null,ee=(0,m.useRef)(!1),ne=(0,m.useRef)(null),he=(0,m.useRef)(null),Z=(0,m.useRef)(new Dve),re=(0,m.useRef)(R.key),ce=pCe(c&&!B,R.pathname),[H,Q]=(0,m.useState)(!1),Y=(0,m.useMemo)(()=>{if(!k)return null;const ot=k.toUpperCase();return x.find(Ee=>Ee.issuePrefix.toUpperCase()===ot)??null},[x,k]),te=!!k&&!b&&x.length>0&&!Y,ae=(0,m.useMemo)(()=>S?.toLowerCase()??Rot(R.pathname,k),[k,R.pathname,S]),me=Y?.id??null,oe=Y?.issuePrefix??null,{slots:ie}=hd({slotTypes:["page","routeSidebar"],companyId:me,enabled:!!(me&&ae)}),ge=(0,m.useMemo)(()=>q7(ie,ae),[ae,ie]),be=(0,m.useMemo)(()=>({companyId:me,companyPrefix:oe}),[me,oe]),le=$?(0,t.jsx)(z7e,{}):!D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(WX,{}):G?(0,t.jsx)(UX,{kind:"connection",connectionId:G}):se?(0,t.jsx)(UX,{kind:"application",applicationId:se}):K||F?(0,t.jsx)(Q7e,{}):ge?D?(0,t.jsx)(KI,{surface:`plugin:${ge.id}`,title:ge.displayName,children:(0,t.jsx)(Lu,{slot:ge,context:be,className:"min-h-0 flex-1",missingBehavior:"placeholder"})}):(0,t.jsx)(Lu,{slot:ge,context:be,className:"h-full w-full",missingBehavior:"placeholder"}):null,ue=q?(0,t.jsx)(Xit,{}):M.builtInContextualSurface==="agent"&&C?(0,t.jsx)(c9e,{agentRef:C}):D&&M.builtInContextualSurface==="routine"&&I?(0,t.jsx)(kUe,{children:(0,t.jsx)(m9e,{routineId:I})}):D&&M.builtInContextualSurface==="skills"?(0,t.jsx)(WX,{}):le,Se=ue!=null,ye=D&&Se&&(q||M.builtInContextualSurface==="skills"||M.builtInContextualSurface==="agent"||M.builtInContextualSurface==="routine"||K||F),Ie=D&&Se&&!ye,Ke=Se&&(!D||ye),rt=!D||!Se?null:ge&&!M.builtInContextualSurface?`plugin:${ge.id}`:M.builtInContextualSurface,dt=(0,m.useRef)(null),{data:de}=X({queryKey:P.health,queryFn:r(()=>su.get(),"queryFn"),retry:!1,refetchInterval:r(ot=>ot.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1});(0,m.useLayoutEffect)(()=>(d(!D&&Se),()=>d(!1)),[Se,d,D]),(0,m.useEffect)(()=>{const ot=dt.current;rt&&k&&ot&&ot.surface!==rt&&ot.pathname!==R.pathname&&O7e({surface:rt,companyPrefix:k,previousPathname:ot.pathname}),dt.current={pathname:R.pathname,surface:rt}},[k,rt,R.pathname]),(0,m.useEffect)(()=>{b||ee.current||de?.deploymentMode!=="authenticated"&&(de?.cloud||x.length===0&&(ee.current=!0,h()))},[x,b,h,de?.cloud,de?.deploymentMode]),(0,m.useEffect)(()=>{if(!k||b||x.length===0)return;if(!Y){const Ee=(j?x.find(Je=>Je.id===j):null)??x[0]??null;Ee&&j!==Ee.id&&w(Ee.id,{source:"route_sync"});return}if(k!==Y.issuePrefix){const Ee=R.pathname.replace(/^\/[^/]+/,"");T(`/${Y.issuePrefix}${Ee}${R.search}`,{replace:!0});return}const ot=fCe({matchedCompany:Y,selectedCompanyId:j,companies:x});if(ot){f?.({title:`${Y.name} is archived`,body:`Switched to ${ot.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${Y.id}`}),w(ot.id,{source:"route_sync"}),T(`/${ot.issuePrefix}/dashboard`,{replace:!0});return}xCe({selectionSource:N,selectedCompanyId:j,routeCompanyId:Y.id})&&w(Y.id,{source:"route_sync"})},[k,x,b,Y,R.pathname,R.search,T,f,N,j,w]);const ze=p,gt=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),bt=(0,m.useRef)(null),De=(0,m.useRef)(!1),Qe=(0,m.useRef)(!1),mt=(0,m.useCallback)(()=>{bt.current!==null&&(window.clearTimeout(bt.current),bt.current=null)},[]),Ye=(0,m.useCallback)(()=>{mt(),bt.current=window.setTimeout(()=>l(!0),50)},[mt,l]),it=(0,m.useCallback)(()=>{mt(),l(!0)},[mt,l]),Nt=(0,m.useCallback)(()=>{mt(),bt.current=window.setTimeout(()=>l(!1),120)},[mt,l]),Ze=(0,m.useCallback)(()=>{De.current=!0,i&&!Qe.current&&Ye()},[i,Ye]),Pe=(0,m.useCallback)(()=>{De.current=!1,Qe.current=!1,Nt()},[Nt]),Ce=(0,m.useCallback)(()=>{Qe.current||it()},[it]),Ve=(0,m.useCallback)(()=>{De.current||Nt()},[Nt]);(0,m.useEffect)(()=>mt,[mt]);const Ge=(0,m.useRef)(i);return(0,m.useEffect)(()=>{i!==Ge.current&&(i?(mt(),l(!1),Qe.current=De.current):Qe.current=!1,Ge.current=i)},[i,mt,l]),(0,m.useEffect)(()=>{if(!o)return;const ot=r(Ee=>{Ee.key==="Escape"&&(mt(),l(!1))},"onKeyDown");return window.addEventListener("keydown",ot),()=>window.removeEventListener("keydown",ot)},[o,mt,l]),hCe(),cCe({onNewIssue:r(()=>u(),"onNewIssue"),onSearch:gt,onToggleSidebar:a,onTogglePanel:ze,onShowShortcuts:r(()=>Q(!0),"onShowShortcuts"),onGoToInbox:r(()=>T("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!c)return;const ot=30,Ee=50,Je=75;let _e=0,He=0;const ns=r(ct=>{const Ue=ct.touches[0];_e=Ue.clientX,He=Ue.clientY},"onTouchStart"),fe=r(ct=>{const Ue=ct.changedTouches[0],Et=Ue.clientX-_e;if(!(Math.abs(Ue.clientY-He)>Je)){if(!s&&_e<ot&&Et>Ee){n(!0);return}s&&Et<-50&&n(!1)}},"onTouchEnd");return document.addEventListener("touchstart",ns,{passive:!0}),document.addEventListener("touchend",fe,{passive:!0}),()=>{document.removeEventListener("touchstart",ns),document.removeEventListener("touchend",fe)}},[c,s,n]),(0,m.useEffect)(()=>{const ot=document.body.style.overflow;return document.body.style.overflow=c?"visible":"clip",()=>{document.body.style.overflow=ot}},[c]),(0,m.useEffect)(()=>{if(!c)return bCe()},[c]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const ot=he.current;return gCe(ot)},[R.pathname]),(0,m.useEffect)(()=>{const ot=he.current;if(!ot)return;const Ee=r(()=>{Z.current.remember(re.current,ot.scrollTop)},"recordScroll");return ot.addEventListener("scroll",Ee,{passive:!0}),()=>ot.removeEventListener("scroll",Ee)},[]),(0,m.useLayoutEffect)(()=>{const ot=he.current,Ee=Mve({previousPathname:ne.current,pathname:R.pathname,navigationType:A,state:R.state});ne.current=R.pathname;const Je=A==="POP",_e=Je?Z.current.recall(R.key):0;if(re.current=R.key,Je){M3(ot,_e);const He=requestAnimationFrame(()=>M3(ot,_e));return()=>cancelAnimationFrame(He)}Ee&&Lve(ot)},[R.key,R.pathname,R.state,A]),(0,t.jsx)(Pve,{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)(qSe,{}),(0,t.jsx)(USe,{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:Se?(0,t.jsx)(q2,{children:ue}):(0,t.jsx)(FX,{children:e})})}),(0,t.jsx)(use,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}):(0,t.jsxs)(Zit,{open:s,collapsed:Ie?!1:i,peeking:Ie?!1:o,resizable:!0,onPanelMouseEnter:Ie?void 0:Ze,onPanelMouseLeave:Ie?void 0:Pe,onPanelFocusCapture:!Ie&&i?Ce:void 0,onPanelBlurCapture:!Ie&&i?Ve:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:Ie?(0,t.jsx)(q2,{children:ue}):(0,t.jsx)(FX,{children:e})}),(0,t.jsx)(use,{deploymentMode:de?.deploymentMode,forceExpanded:Ie})]}),!c&&Ke&&!ye?(0,t.jsx)(q2,{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",{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)(a6,{mobile:c,onNavigateHome:r(()=>T("/dashboard"),"onNavigateHome")}),(0,t.jsx)(HX,{}),c&&$?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(Qye,{})}):null]}),(0,t.jsxs)("div",{className:W(c?"block":"flex flex-1 min-h-0",!c&&U&&"streamlined-task-detail-surface"),children:[!c&&ye?(0,t.jsx)(q2,{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)(a6,{mobile:!1,onNavigateHome:r(()=>T("/dashboard"),"onNavigateHome")}),(0,t.jsx)(HX,{taskDetailLayout:!0})]}):null,(0,t.jsx)("main",{id:"main-content",ref:he,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)(Eu,{scope:"invalid_company_prefix",requestedPrefix:k??v?.issuePrefix}):(0,t.jsx)(HSe,{children:(0,t.jsx)(lb,{})})})]}),(0,t.jsx)(oje,{taskDetailLayout:!c&&U})]})]})]}),c&&(0,t.jsx)(zSe,{visible:ce}),(0,t.jsx)(dje,{}),(0,t.jsx)(Uje,{}),(0,t.jsx)(PSe,{}),(0,t.jsx)(LSe,{}),(0,t.jsx)($Se,{}),(0,t.jsx)(OSe,{open:H,onOpenChange:Q}),(0,t.jsx)(FSe,{}),(0,t.jsx)(wit,{health:de}),(0,t.jsx)(BSe,{localTrusted:de?.deploymentMode==="local_trusted"})]})})}r(Pot,"Layout$1");var vCe=(0,m.createContext)(!1);function Mot({children:e}){return(0,t.jsx)(vCe.Provider,{value:!0,children:e})}r(Mot,"SidebarNavExpandedProvider");function Dot(){return(0,m.useContext)(vCe)}r(Dot,"useSidebarNavExpanded");function Ja({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}=Fa(),I=Dot(),T=S&&!C&&!I,R=c!=null&&c>0,A=x!=null&&x>0,D=A?`${x} live`:R?`${c}${u?` ${u}`:""}`:f?"attention needed":void 0,M=!T||!D&&!j?void 0:`${s}${D?`, ${D}`:""}${j?`, ${j}`:""}`,$=(0,t.jsxs)(cb,{to:e,state:Jf,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"}),T&&!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)"})]}),T&&!f&&!A&&R&&(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:T?Fy:W("min-w-0 flex-1 truncate",l),children:s}),!T&&v,!T&&h&&(0,t.jsx)(lt,{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}),!T&&(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"]})]})]}),!T&&R&&(0,t.jsx)(lt,{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 T?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("div",{children:$})}),(0,t.jsx)(Wn,{side:"right",children:s})]}):$}r(Ja,"SidebarNavItem");var Lot=3,mse=12e4,$ot=[{value:"top",label:"Top"},{value:"alphabetical",label:"Alphabetical"},{value:"recent",label:"Recent"}];function Kj(e,s){const n=e[s];if(!n)return 0;const a=new Date(n).getTime();return Number.isFinite(a)?a:0}r(Kj,"agentTimestamp");function hse(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=Kj(i,"lastHeartbeatAt")-Kj(a,"lastHeartbeatAt");if(o!==0)return o;const l=Kj(i,"updatedAt")-Kj(a,"updatedAt");if(l!==0)return l;const c=Kj(i,"createdAt")-Kj(a,"createdAt");return c!==0?c:a.name.localeCompare(i.name,void 0,{sensitivity:"base"})}),n)}r(hse,"sortAgents");var Oot="opacity-0 transition-opacity group-hover/agent:opacity-100 group-focus-within/agent:opacity-100";function Fot({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=Wl(n),j=s?`${xm(n)}/${s}`:xm(n),N=`${xm(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",T=a||n.status==="pending_approval"||S||k&&C,R=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)(Ja,{to:j,label:n.name,iconNode:(0,t.jsx)(_r,{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)(rk,{status:p,compact:!0}):null,C?(0,t.jsx)(Ds,{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)(zI,{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)(pb,{size:"row",quiet:!0,starred:!0,pending:b,resourceName:n.name,onToggle:r(()=>x(n,!1),"onToggle"),revealClassName:Oot})}):null,(0,t.jsxs)(ta,{children:[(0,t.jsx)(ea,{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)(Ai,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(sa,{align:"end",className:"w-48",children:[x?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(cs,{onClick:r(()=>{b||x(n,!f)},"onClick"),disabled:b,children:[b?(0,t.jsx)(nt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(vp,{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)(Xa,{})]}):null,(0,t.jsx)(cs,{asChild:!0,children:(0,t.jsxs)(We,{to:N,onClick:r(()=>{i&&h(!1)},"onClick"),children:[(0,t.jsx)(mc,{className:"size-4"}),(0,t.jsx)("span",{children:"Edit agent"})]})}),(0,t.jsx)(Xa,{}),(0,t.jsxs)(cs,{onClick:r(()=>{T||c(n,k?"resume":"pause")},"onClick"),disabled:T,title:S?"Agent was paused by budget limits":void 0,children:[k?(0,t.jsx)(LI,{className:"size-4"}):(0,t.jsx)(Td,{className:"size-4"}),(0,t.jsx)("span",{children:R})]}),(0,t.jsx)(Xa,{}),(0,t.jsxs)(cs,{onClick:r(()=>{o||l(n)},"onClick"),disabled:o,children:[o?(0,t.jsx)(nt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(Tp,{className:"size-4"}),(0,t.jsx)("span",{children:o?"Leaving...":"Leave agent"})]})]})]})]})}r(Fot,"SidebarAgentItem");function Bot({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=Mt(),{selectedCompanyId:u}=gs(),{openNewAgent:h}=Do(),{isMobile:p,setSidebarOpen:f,collapsed:x,peeking:b}=Fa(),v=x&&!b,{pushToast:j}=pa(),N=ra(),{data:w}=X({queryKey:P.agents.list(u),queryFn:r(()=>Lt.list(u),"queryFn"),enabled:!!u}),{data:k}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn"),enabled:!!u}),S=k?.enableBuiltInAgents===!0,{data:C}=X({queryKey:P.builtInAgents.list(u),queryFn:r(()=>Yh.list(u),"queryFn"),enabled:!!u&&S}),I=(0,m.useMemo)(()=>{const ye=new Map;if(!S)return ye;for(const Ie of C??[])Ie.agentId&&ye.set(Ie.agentId,Ie.status);return ye},[C,S]),{data:T}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn")}),R=Xf(u),A=Sg(u),D=P.liveRuns(u),M=bo({companyId:u,resourceKey:"live-runs",queryKey:D,enabled:!!u,refetchInterval:!1,leaderOnly:!0}),{data:$,dataUpdatedAt:E}=X({queryKey:D,queryFn:r(()=>Zr.liveRunsForCompany(u),"queryFn"),enabled:M.enabled,refetchInterval:M.refetchInterval});vo(M,$,E);const B=(0,m.useMemo)(()=>{const ye=new Map;for(const Ie of $??[])ye.set(Ie.agentId,(ye.get(Ie.agentId)??0)+1);return ye},[$]),z=(0,m.useMemo)(()=>{const ye=new Set;for(const[Ie,Ke]of B)Ke>0&&ye.add(Ie);return ye},[B]),q=(0,m.useMemo)(()=>(w??[]).filter(ye=>ye.status!=="terminated"&&(!R.isSuccess||Bf(R.data,"agent",ye.id)!=="left")),[w,R.data,R.isSuccess]),U=T?.user?.id??T?.session?.userId??null,F=(0,m.useMemo)(()=>u?Wve(u,U):null,[U,u]),[K,G]=(0,m.useState)(()=>F?ak(F):"top"),{orderedAgents:se}=Gve({agents:q,companyId:u,userId:U}),ee=(0,m.useMemo)(()=>hse(se,K),[se,K]),ne=(0,m.useMemo)(()=>new Set(ee.map(ye=>ye.id)),[ee]);(0,m.useEffect)(()=>{const ye=Date.now();for(const Ie of z)c.current.set(Ie,ye);for(const Ie of c.current.keys())ne.has(Ie)||c.current.delete(Ie)},[z,ne]);const he=(0,m.useMemo)(()=>{const ye=Date.now(),Ie=c.current;return ee.filter(Ke=>{if((B.get(Ke.id)??0)>0)return!0;const rt=Ie.get(Ke.id);return rt!==void 0&&ye-rt<=mse})},[B,o,ee]),Z=he.length>0,re=e?Z?he:ee.slice(0,Lot):ee,ce=e&&ee.length>0,H=N.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),Q=H?.[1]??null,Y=H?.[2]??null;(0,m.useEffect)(()=>{if(!F){G("top");return}G(ak(F))},[F]),(0,m.useEffect)(()=>{if(!F)return;const ye=r(Ke=>{Ke.key===F&&G(ak(F))},"onStorage"),Ie=r(Ke=>{const rt=Ke.detail;!rt||rt.storageKey!==F||G(rt.sortMode)},"onCustomEvent");return window.addEventListener("storage",ye),window.addEventListener(l_,Ie),()=>{window.removeEventListener("storage",ye),window.removeEventListener(l_,Ie)}},[F]),(0,m.useEffect)(()=>{if(!e)return;const ye=Date.now();let Ie=null;for(const rt of ee){if((B.get(rt.id)??0)>0)continue;const dt=c.current.get(rt.id);if(dt===void 0)continue;const de=dt+mse;de<ye||(Ie=Ie===null?de:Math.min(Ie,de))}if(Ie===null)return;const Ke=window.setTimeout(()=>{l(rt=>rt+1)},Math.max(0,Ie-ye+1));return()=>{window.clearTimeout(Ke)}},[e,ee,B,o]);const te=(0,m.useCallback)(ye=>{const Ie=ye==="alphabetical"||ye==="recent"?ye:"top";G(Ie),F&&Hve(F,Ie)},[F]),ae=je({mutationFn:r(({agent:ye,action:Ie})=>Ie==="pause"?Lt.pause(ye.id,u??void 0):Lt.resume(ye.id,u??void 0),"mutationFn"),onMutate:r(({agent:ye})=>{i(Ie=>{const Ke=new Set(Ie);return Ke.add(ye.id),Ke})},"onMutate"),onSuccess:r(async(ye,{agent:Ie,action:Ke})=>{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(Wl(Ie))})]),j({title:Ke==="pause"?"Agent paused":"Agent resumed",body:Ie.name,tone:"success"})},"onSuccess"),onError:r((ye,{agent:Ie,action:Ke})=>{j({title:Ke==="pause"?"Could not pause agent":"Could not resume agent",body:ye instanceof Error?ye.message:Ie.name,tone:"error"})},"onError"),onSettled:r((ye,Ie,{agent:Ke})=>{i(rt=>{const dt=new Set(rt);return dt.delete(Ke.id),dt})},"onSettled")}),me=(0,m.useCallback)(ye=>A.mutate({resourceType:"agent",resourceId:ye.id,resourceName:ye.name,state:"left"}),[A]),oe=(0,m.useCallback)(ye=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===ye.id,[A.isPending,A.variables]),ie=(0,m.useCallback)((ye,Ie)=>A.mutate({resourceType:"agent",resourceId:ye.id,resourceName:ye.name,starred:Ie}),[A]),ge=(0,m.useCallback)(ye=>A.isPending&&A.variables?.resourceType==="agent"&&A.variables.resourceId===ye.id&&A.variables.starred!==void 0,[A.isPending,A.variables]),be=(0,m.useMemo)(()=>new Set(NM(R.data,"agent")),[R.data]),le=(0,m.useMemo)(()=>hse(q.filter(ye=>be.has(ye.id)),"alphabetical"),[q,be]),ue=(0,m.useMemo)(()=>re.filter(ye=>!be.has(ye.id)),[re,be]),Se=r((ye,Ie)=>(0,t.jsx)(Fot,{activeAgentId:Q,activeTab:Y,agent:ye,disabled:a.has(ye.id),isMobile:p,leaving:oe(ye),onLeaveAgent:me,onPauseResume:r((Ke,rt)=>ae.mutate({agent:Ke,action:rt}),"onPauseResume"),rail:v,runCount:B.get(ye.id)??0,setSidebarOpen:f,builtInStatus:I.get(ye.id),starred:Ie||hb(R.data,"agent",ye.id),onToggleStar:ie,starPending:ge(ye)},ye.id),"renderAgentRow");return(0,t.jsxs)(Zx,{label:"Agents",collapsible:{open:s,onOpenChange:n},headerAction:{ariaLabel:"New agent",icon:bn,onClick:h},menu:{ariaLabel:"Agents section actions",actions:[{type:"item",label:"Browse agents",icon:Eo,href:"/agents/all"},{type:"separator"}],radioLabel:"Agent sort",radioChoices:$ot,radioValue:K,onRadioValueChange:te},children:[le.map(ye=>Se(ye,!0)),ue.map(ye=>Se(ye,!1)),ce&&(()=>{const ye=(0,t.jsxs)(We,{to:"/agents/all",state:Jf,"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)(Eo,{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)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:ye}),(0,t.jsx)(Wn,{side:"right",children:"See all agents"})]}):ye})()]})}r(Bot,"SidebarAgents");var zot="opacity-0 transition-opacity group-hover/starred-project:opacity-100 group-focus-within/starred-project:opacity-100";function qot(){const{selectedCompanyId:e}=gs(),{isMobile:s,setSidebarOpen:n,collapsed:a,peeking:i}=Fa(),o=a&&!i,l=ra(),{data:c}=X({queryKey:P.projects.list(e),queryFn:r(()=>ma.list(e),"queryFn"),enabled:!!e}),d=Xf(e),u=Sg(e),h=l.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/)?.[1]??null,p=(0,m.useMemo)(()=>{if(!d.isSuccess)return[];const v=new Set(NM(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=og(v),N=h===j||h===v.id,w=b(v),k=w&&u.variables?.starred===!1,S=w&&u.variables?.state==="left",C=hb(d.data,"project",v.id),I=(0,t.jsxs)(cb,{to:`/projects/${j}/issues`,state:Jf,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)(wm,{color:v.color??null,icon:v.icon??null,size:"xs"}),(0,t.jsx)("span",{className:o?Fy:"flex-1 truncate",children:v.name}),!o&&v.pauseReason==="budget"?(0,t.jsx)(zI,{title:"Project paused by budget"}):null]});return(0,t.jsxs)("div",{className:"group/starred-project relative flex items-center",children:[o?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("div",{className:"min-w-0 flex-1",children:I})}),(0,t.jsx)(Wn,{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)(pb,{size:"row",quiet:!0,starred:C,pending:k,resourceName:v.name,onToggle:r(()=>f(v),"onToggle"),revealClassName:zot})}):null,!o&&s?(0,t.jsxs)(ta,{children:[(0,t.jsx)(ea,{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)(Ai,{className:"h-3.5 w-3.5"})})}),(0,t.jsxs)(sa,{align:"end",className:"w-48",children:[(0,t.jsxs)(cs,{onClick:r(()=>{w||f(v)},"onClick"),disabled:w,children:[k?(0,t.jsx)(nt,{className:"size-4 motion-safe:animate-spin"}):(0,t.jsx)(vp,{className:"size-4 fill-amber-500 text-amber-500"}),(0,t.jsx)("span",{children:"Remove from starred"})]}),(0,t.jsx)(Xa,{}),(0,t.jsxs)(cs,{onClick:r(()=>{w||x(v)},"onClick"),disabled:w,children:[S?(0,t.jsx)(nt,{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(qot,"SidebarStarredProjects");var Uot="size-5 shrink-0 rounded-md text-(length:--text-micro)",Kot="size-(--organization-popover-avatar-size) shrink-0 rounded-lg text-(length:--text-micro)",Wot="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",Q$="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)(GN,{companyName:e.name,logoUrl:e.logoUrl,className:s?Kot:Uot})}r(yCe,"WorkspaceIcon");function Vot({company:e,isEditing:s,isSelected:n,onSelect:a}){const{attributes:i,listeners:o,setActivatorNodeRef:l,setNodeRef:c,transform:d,transition:u,isDragging:h}=DN({id:e.id,disabled:!s});return(0,t.jsxs)(cs,{ref:c,style:{transform:PN.Transform.toString(d),transition:u,zIndex:h?10:void 0},onSelect:r(p=>{if(s){p.preventDefault();return}a(e)},"onSelect"),className:W(Wot,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)(gM,{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)(vs,{className:"size-4 text-foreground"}):null})]})}r(Vot,"SortableCompanyItem");function Hot(e={}){return(0,t.jsx)(qye,{...e,children:(0,t.jsx)(Got,{...e})})}r(Hot,"SidebarCompanyMenu");function Got({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}=gs(),{openOnboarding:p}=Do(),{isMobile:f,setSidebarOpen:x,collapsed:b,peeking:v}=Fa(),j=b&&!v,N=ra(),w=Ln(),k=e??n,S=s??a,C=MN(Lf(X8,{activationConstraint:{distance:8}}),Lf(vfe,{activationConstraint:{delay:180,tolerance:6}})),I=(0,m.useMemo)(()=>l.filter(ne=>ne.status!=="archived"),[l]),{data:T}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),R=T?.user?.id??T?.session?.userId??null,{orderedCompanies:A,persistOrder:D}=zye({companies:I,userId:R}),{hidden:M,loaded:$}=tu(),E=$&&!lg(M,"company.members")&&!lg(M,"company.invites"),B="company",z=c?.name??null,q=!!Ac(),U=HN({onSignedOut:K});function F(ne){ne||o(!1),S(ne)}r(F,"handleOpenChange");function K(){S(!1),o(!1),f&&x(!1)}r(K,"closeNavigationChrome");function G(ne){const he=N.pathname.split("/")[1]?.toUpperCase(),Z=I.some(ce=>ce.issuePrefix.toUpperCase()===he),re=ne.id!==c?.id&&(N.pathname.startsWith("/instance/")||Z);d(ne.id),S(!1),f&&x(!1),re&&w(`/${ne.issuePrefix}/dashboard`)}r(G,"selectCompany");function se(){q||(S(!1),f&&x(!1),p({initialStep:1}))}r(se,"addCompany");const ee=(0,m.useCallback)(ne=>{const{active:he,over:Z}=ne;if(!Z||he.id===Z.id)return;const re=A.map(Q=>Q.id),ce=re.indexOf(he.id),H=re.indexOf(Z.id);ce===-1||H===-1||D(rM(re,ce,H))},[A,D]);return(0,t.jsxs)(ta,{open:k,onOpenChange:F,children:[(0,t.jsx)(ea,{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":z?`Open ${z} ${B} switcher`:`Open ${B} 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:z??void 0,children:z??`Select ${B}`})]}),!j&&(0,t.jsx)(dM,{className:"size-3.5 shrink-0 text-muted-foreground"})]})}),(0,t.jsxs)(sa,{align:"start",sideOffset:8,className:"ml-2 w-(--organization-popover-width) max-w-(--sz-calc-24) overflow-hidden rounded-xl border-border bg-popover p-0 shadow-(--shadow-profile-popover)",children:[(0,t.jsxs)("div",{className:"flex h-(--organization-popover-header-height) items-center justify-between gap-2 px-3.5",children:[(0,t.jsx)(db,{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(he=>!he)},"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)(EN,{sensors:C,collisionDetection:CI,onDragEnd:ee,children:(0,t.jsx)(RN,{items:A.map(ne=>ne.id),strategy:kI,children:A.map(ne=>(0,t.jsx)(Vot,{company:ne,isEditing:i,isSelected:ne.id===c?.id,onSelect:G},ne.id))})}),A.length===0?u?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(cs,{disabled:!0,children:"Couldn't load companies"}),(0,t.jsxs)(cs,{onSelect:r(ne=>{ne.preventDefault(),h()},"onSelect"),children:[(0,t.jsx)(Si,{className:"h-4 w-4 mr-2"}),"Try again"]})]}):(0,t.jsx)(cs,{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)(cs,{onClick:se,className:Q$,disabled:i,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:(0,t.jsx)(bn,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Create organization"})]}),E?(0,t.jsx)(cs,{asChild:!0,disabled:i,className:Q$,children:(0,t.jsxs)(We,{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)(Yf,{className:"size-4"})}),(0,t.jsx)("span",{className:"min-w-0 flex-1 truncate",children:z?`Invite people to ${z}`:"Invite people"})]})}):null,T?.session?(0,t.jsxs)(cs,{className:Q$,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(Got,"BuiltinCompanyMenu");function pse(){const{openNewIssue:e}=Do(),[s,n]=(0,m.useState)(!0),[a,i]=(0,m.useState)(!0),{selectedCompanyId:o,selectedCompany:l}=gs(),{collapsed:c,peeking:d}=Fa(),u=c&&!d,h=IM(o),{data:p,isFetched:f}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn")}),x=P.liveRuns(o),b=bo({companyId:o,resourceKey:"live-runs",queryKey:x,enabled:!!o,refetchInterval:!1,leaderOnly:!0}),{data:v,dataUpdatedAt:j}=X({queryKey:x,queryFn:r(()=>Zr.liveRunsForCompany(o),"queryFn"),enabled:b.enabled,refetchInterval:b.refetchInterval});vo(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,T=p?.enableGoalsSidebarLink===!0,R=p?.enableDecisions===!0,{data:A}=X({queryKey:P.attention(o),queryFn:r(()=>KN.list(o),"queryFn"),enabled:!!o&&R,refetchInterval:6e4}),D=gye(A),M=p?.enableCases===!0,$=!0,E=p?.enableConferenceRoomChat===!0,B={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)(Hot,{})}),(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 z=(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)(a_,{className:"h-4 w-4 shrink-0"}),(0,t.jsx)("span",{className:u?Fy:"truncate",children:"New Task"})]});return u?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:z}),(0,t.jsx)(Wn,{side:"right",children:"New Task"})]}):z})(),(0,t.jsx)(Ja,{to:"/search",label:"Search",icon:Gr}),(0,t.jsx)(Ja,{to:"/dashboard",label:"Dashboard",icon:Xx,liveCount:N}),(0,t.jsx)(Ja,{to:"/inbox",label:"Inbox",icon:cd,badge:h.inbox,badgeLabel:"unread",badgeTone:h.failedRuns>0?"danger":"default",alert:h.failedRuns>0}),R?(0,t.jsx)(Ja,{to:"/decisions",label:"Decisions",icon:Vy,badge:D,badgeLabel:"decisions"}):null,C?(0,t.jsx)(Ja,{to:"/status",label:"Status",icon:qN,textBadge:"beta"}):null,E?(0,t.jsx)(Ja,{to:"/board-chat",label:"Conference Room",icon:D0e}):null]}),(0,t.jsxs)(Zx,{label:"Work",collapsible:{open:s,onOpenChange:n},children:[(0,t.jsx)(Ja,{to:"/issues",label:"Tasks",icon:Cu}),M?(0,t.jsx)(Ja,{to:"/cases",label:"Cases",icon:Tl,textBadge:"beta"}):null,(0,t.jsx)(Ja,{to:"/routines",label:"Routines",icon:Tu}),S?(0,t.jsx)(Ja,{to:"/pipelines",label:"Pipelines",icon:to}):null,T?(0,t.jsx)(Ja,{to:"/goals",label:"Goals",icon:bp}):I?(0,t.jsx)("div",{"data-testid":"sidebar-goals-placeholder",className:"h-8 pointer-coarse:h-7","aria-hidden":"true"}):null,(0,t.jsx)(Ja,{to:"/artifacts",label:"Artifacts",icon:Ih}),(0,t.jsx)(Ja,{to:"/skills",label:"Skills",icon:uc}),w?(0,t.jsx)(Ja,{to:"/workspaces",label:"Workspaces",icon:to}):null,(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ja,{to:"/projects",label:"Projects",icon:Po}),(0,t.jsx)(qot,{})]}),(0,t.jsx)(Sp,{slotTypes:["sidebar"],context:B,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium",missingBehavior:"placeholder"}),(0,t.jsx)(VN,{placementZones:["sidebar"],context:B,className:"flex flex-col gap-0.5",itemClassName:"text-(length:--text-compact) font-medium"})]}),null,(0,t.jsx)(Bot,{streamlined:$}),(0,t.jsxs)(Zx,{label:"Company",collapsible:{open:a,onOpenChange:i},children:[(0,t.jsx)(Ja,{to:"/org",label:"Org",icon:my}),k?(0,t.jsx)(Ja,{to:"/apps",label:"Connectors",icon:E3}):null,(0,t.jsx)(Ja,{to:"/timeline",label:"Timeline",icon:x0}),(0,t.jsx)(Ja,{to:"/costs",label:"Costs",icon:dp}),(0,t.jsx)(Ja,{to:"/activity",label:"Activity",icon:Vl}),(0,t.jsx)(Ja,{to:"/company/settings",label:"Settings",icon:Xd})]}),(0,t.jsx)(Sp,{slotTypes:["sidebarPanel"],context:B,className:"flex flex-col gap-3",itemClassName:"rounded-lg border border-border p-3",missingBehavior:"placeholder"})]})]})}r(pse,"Sidebar");function Qot(e){const s=e.manifestJson.environmentDrivers??[];return s.length===0?!1:s.every(n=>n.kind==="sandbox_provider")}r(Qot,"isSandboxProviderOnly");function Yot(){const{selectedCompany:e,selectedCompanyId:s}=gs(),{isMobile:n,setSidebarOpen:a}=Fa(),{hidden:i}=tu(),o=r(f=>!i.has(f),"showPage"),l=o("instance.plugins"),c=!!Ac(),{slots:d}=hd({slotTypes:["companySettingsPage"],companyId:s,enabled:!!s}),{data:u}=X({queryKey:s?P.sidebarBadges(s):["sidebar-badges","__disabled__"],queryFn:r(async()=>{try{return await Kye.get(s)}catch(f){if(f instanceof un&&(f.status===401||f.status===403))return null;throw f}},"queryFn"),enabled:!!s,retry:!1,refetchInterval:15e3}),{data:h}=X({queryKey:P.plugins.all,queryFn:r(()=>xl.list(),"queryFn"),enabled:l}),p=(h??[]).filter(f=>!Qot(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)(We,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Mu,{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)(Ja,{to:"/company/settings",label:"General",icon:Du,end:!0}),o("instance.profile")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/profile",label:"Profile",icon:yM,end:!0}),o("company.members")&&(0,t.jsx)(Ja,{to:"/company/settings/members",label:"Members",icon:Eo,badge:u?.joinRequests??0,end:!0}),d.filter(f=>f.routePath).map(f=>(0,t.jsx)(Ja,{to:`/company/settings/${f.routePath}`,label:f.displayName,icon:Jx,end:!0},`${f.pluginKey}:${f.id}`)),o("company.invites")&&(0,t.jsx)(Ja,{to:"/company/settings/invites",label:"Invites",icon:kze,end:!0}),o("company.secrets")&&(0,t.jsx)(Ja,{to:"/company/settings/secrets",label:"Secrets",icon:ki,end:!0}),o("instance.environments")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/environments",label:"Environments",icon:B0e,end:!0}),o("instance.access")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/access",label:"Access",icon:jI,end:!0}),o("instance.heartbeats")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/heartbeats",label:"Heartbeats",icon:Jd,end:!0}),o("company.export")&&(0,t.jsx)(Ja,{to:"/company/export",label:"Export",icon:oo}),!c&&o("company.import")&&(0,t.jsx)(Ja,{to:"/company/import",label:"Import",icon:hy,end:!0}),o("instance.experimental")&&(0,t.jsx)(Ja,{to:"/company/settings/instance/experimental",label:"Experimental",icon:Pm}),l&&(0,t.jsx)(Ja,{to:"/company/settings/instance/plugins",label:"Plugins",icon:Jx}),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)(cb,{to:`${Jh}/plugins/${f.id}`,state:Jf,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)(Ja,{to:"/company/settings/instance/adapters",label:"Adapters",icon:dm})]})})]})}r(Yot,"CompanySettingsSidebar");function Jot(){const{pathname:e}=ra(),{selectedCompany:s}=gs(),{isMobile:n,setSidebarOpen:a}=Fa(),i=Xye(),{enabled:o}=AM(),l=X7.filter(d=>!Jye(d.key)||o);if(e.endsWith("/apps/chat/connect"))return(0,t.jsx)(R7,{});const c=e.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|reviews|conversations|activity|approvals|audit))?\/?$/);return c?(0,t.jsx)(Yye,{endpointId:c[1],NavItem:Ja}):(0,t.jsxs)("aside",{className:"w-full h-full min-h-0 border-r border-border bg-background flex flex-col",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 px-3 py-3 shrink-0",children:[(0,t.jsxs)(We,{to:"/dashboard",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Mu,{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)(zJ,{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)(Ja,{to:"/apps",label:"Browse",icon:i_,end:!0}),(0,t.jsx)(Ja,{to:"/apps/review",label:"Review",icon:UN,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)(Ja,{to:"/apps/connections",label:"Connections",icon:zJ,end:!0}),l.map(d=>(0,t.jsx)(Ja,{to:L0(d.key),label:d.label,icon:d.icon,end:!0},d.key))]})]})]})}r(Jot,"AppsSidebar");function fse(e){const{selectedCompanyId:s}=gs(),{isMobile:n,setSidebarOpen:a}=Fa(),i=X({queryKey:P.tools.connection(e.kind==="connection"?e.connectionId:"__none__"),queryFn:r(()=>es.getConnection(e.kind==="connection"?e.connectionId:""),"queryFn"),enabled:e.kind==="connection"&&!!e.connectionId}),o=X({queryKey:P.tools.applications(s??"__none__"),queryFn:r(()=>es.listApplications(s),"queryFn"),enabled:e.kind==="application"&&!!s}),l=X({queryKey:P.tools.connections(s??"__none__"),queryFn:r(()=>es.listConnections(s),"queryFn"),enabled:e.kind==="application"&&!!s}),c=X({queryKey:P.apps.gallery(s??"__none__"),queryFn:r(()=>es.listGallery(s),"queryFn"),enabled:!!s}),d=X({queryKey:P.apps.attention(s??"__none__"),queryFn:r(()=>es.listAppsAttention(s),"queryFn"),enabled:!!s,refetchInterval:3e4}),u=i.data,h=e.kind==="application"?(o.data?.applications??[]).find(N=>N.id===e.applicationId):null,p=elt(e.kind==="application"?(l.data?.connections??[]).filter(N=>N.applicationId===e.applicationId):[]),f=u?Ff(u):h?.name??"App",x=Zot(c.data?.apps??[],u,h??void 0),b=u?.id??p?.id??null,v=b?d.data?.apps.find(N=>N.connection.id===b):null,j=(v?.pendingActionRequestCount??0)+((v?.quarantinedCatalogEntryCount??0)>0?1:0);return(0,t.jsxs)("aside",{className:"flex h-full min-h-0 w-full flex-col border-r border-border bg-background",children:[(0,t.jsxs)("div",{className:"flex shrink-0 flex-col gap-3 px-3 py-3",children:[(0,t.jsxs)(We,{to:"/apps/connections",onClick:r(()=>{n&&a(!1)},"onClick"),className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[(0,t.jsx)(Mu,{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)(Vo,{name:f,logoUrl:WI(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:TM.map(N=>(0,t.jsx)(Ja,{to:Xot(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(fse,"AppDetailSidebar");function Xot(e,s){return e.kind==="connection"?cm(e.connectionId,s):x1(e.applicationId,s)}r(Xot,"tabHref");function Zot(e,s,n){if(n?.applicationKey){const i=e.find(o=>oc(o)===n.applicationKey);if(i)return i}const a=(s?.name??n?.name)?.toLowerCase();return a?e.find(i=>eg(i).toLowerCase()===a)??e.find(i=>oc(i)===a)??null:null}r(Zot,"galleryEntryFor$1");function elt(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(elt,"latestArchivedConnection$1");function Y$({identifier:e}){return e?(0,t.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e}):null}r(Y$,"CrumbIdentifier");function tlt({context:e}){const{slots:s}=hd({slotTypes:["globalToolbarButton"],companyId:e.companyId}),{launchers:n}=Q7({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)(VN,{placementZones:["globalToolbarButton"],context:e,className:"flex items-center gap-1"}):null]})}r(tlt,"GlobalToolbar");function slt(){const{breadcrumbs:e,mobileToolbar:s}=Fn(),{toggleSidebar:n,isMobile:a}=Fa(),{selectedCompanyId:i,selectedCompany:o}=gs(),l=(0,m.useMemo)(()=>({companyId:i??null,companyPrefix:o?.issuePrefix??null}),[i,o?.issuePrefix]),c=(0,t.jsx)(tlt,{context:l});if(a&&s)return(0,t.jsx)("div",{className:"border-b border-border px-2 h-12 shrink-0 flex items-center",children:s});if(e.length===0)return(0,t.jsx)("div",{className:"border-b border-border px-4 md:px-6 h-12 shrink-0 flex items-center justify-end",children:c});const d=a&&(0,t.jsx)(L,{variant:"ghost",size:"icon-sm",className:"mr-2 shrink-0",onClick:n,"aria-label":"Open sidebar",children:(0,t.jsx)(C0e,{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)(Y$,{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)(Z7,{className:"min-w-0 overflow-hidden",children:(0,t.jsx)(e9,{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)(U3,{}),(0,t.jsx)(g1,{className:p?"min-w-0":"shrink-0",children:p||!u.href?u.leading||u.identifier?(0,t.jsxs)(h_,{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)(Y$,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(h_,{className:"truncate",children:u.label}):(0,t.jsx)(q3,{asChild:!0,children:u.leading||u.identifier?(0,t.jsxs)(We,{to:u.href,onClick:u.onClick,className:"flex items-center gap-1.5",children:[u.leading&&(0,t.jsx)("span",{className:"flex shrink-0 items-center",children:u.leading}),(0,t.jsx)(Y$,{identifier:u.identifier}),(0,t.jsx)("span",{className:"truncate",children:u.label})]}):(0,t.jsx)(We,{to:u.href,onClick:u.onClick,children:u.label})})})]},h)})})})}),c]})}r(slt,"BreadcrumbBar");var U2=240,u6=208,m6=420,xse=16;function A5(e){return Math.min(m6,Math.max(u6,e))}r(A5,"clampSidebarWidth");function gse(e){if(typeof window>"u")return U2;try{const s=window.localStorage.getItem(e);if(!s)return U2;const n=Number.parseInt(s,10);return Number.isFinite(n)?A5(n):U2}catch{return U2}}r(gse,"readStoredSidebarWidth");function bse(e,s){if(!(typeof window>"u"))try{window.localStorage.setItem(e,String(A5(s)))}catch{}}r(bse,"writeStoredSidebarWidth");function nlt({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)(()=>gse(o)),[x,b]=(0,m.useState)(!1),v=(0,m.useRef)(p),j=(0,m.useRef)(null);(0,m.useEffect)(()=>{const E=gse(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]),T=(0,m.useMemo)(()=>({width:`${k}px`}),[k]),R=(0,m.useCallback)(E=>{const B=A5(E);v.current=B,f(B),bse(o,B)},[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 B=A5(j.current.startWidth+E.clientX-j.current.startX);v.current=B,f(B)},[]),M=(0,m.useCallback)(()=>{j.current&&(j.current=null,b(!1),bse(o,v.current))},[o]),$=(0,m.useCallback)(E=>{C&&(E.key==="ArrowLeft"?(E.preventDefault(),R(p-xse)):E.key==="ArrowRight"?(E.preventDefault(),R(p+xse)):E.key==="Home"?(E.preventDefault(),R(u6)):E.key==="End"&&(E.preventDefault(),R(m6)))},[C,R,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:T,"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":u6,"aria-valuemax":m6,"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:$}):null]})})}r(nlt,"SidebarShell");function rlt({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)(Mot,{children:e})})}r(rlt,"SecondarySidebar");var alt="/company/settings/members?tab=invites",ilt="https://docs.paperclip.ing/",olt="https://paperclip.ing/feedback";function llt(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(llt,"deriveInitials$1");function vse({label:e,description:s,icon:n,onClick:a,href:i,external:o=!1,topLevel:l=!1}){const c="flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60",d=(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"mt-0.5 rounded-lg border border-border bg-background/70 p-2 text-muted-foreground",children:(0,t.jsx)(n,{className:"size-4"})}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block text-sm font-medium text-foreground",children:e}),(0,t.jsx)("span",{className:"block text-xs text-muted-foreground",children:s})]})]});return i?o?(0,t.jsx)("a",{href:i,target:"_blank",rel:"noreferrer",className:c,onClick:a,children:d}):l?(0,t.jsx)("a",{href:i,className:c,onClick:a,children:d}):(0,t.jsx)(We,{to:i,className:c,onClick:a,children:d}):(0,t.jsx)("button",{type:"button",className:c,onClick:a,children:d})}r(vse,"MenuAction");function yse({deploymentMode:e,open:s,onOpenChange:n}){const i=!!Ac(),{hidden:o,loaded:l}=tu(),c=tCe(),d=sCe(!i),u=i?c:d?alt:null,h=l&&u!==null&&!lg(o,"company.members")&&!lg(o,"company.invites"),[p,f]=(0,m.useState)(!1),{isMobile:x,setSidebarOpen:b,collapsed:v,peeking:j}=Fa(),N=v&&!j,w=s??p,k=nCe(w),S=n??f,{data:C}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),I=HN({onSignedOut:M}),T=C?.user.name?.trim()||"Board",R=C?.user.email?.trim()||(e==="authenticated"?"Signed in":"Local workspace board"),A=llt(T),D=rCe(C?.user);function M(){S(!1),x&&b(!1)}r(M,"closeNavigationChrome");function $(){I.mutate()}return r($,"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)(yr,{open:w,onOpenChange:S,children:[(0,t.jsx)(Ir,{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)(So,{size:"sm",children:[C?.user.image?(0,t.jsx)(md,{src:C.user.image,alt:T}):null,(0,t.jsx)(Co,{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:T})]})}),(0,t.jsxs)(lr,{side:"top",align:"start",sideOffset:10,className:"w-(--sz-277px) max-w-(--sz-calc-24) overflow-hidden rounded-t-2xl rounded-b-none border-border p-0 shadow-2xl",children:[(0,t.jsx)("div",{className:"h-24 bg-(image:--gradient-extract-25)"}),(0,t.jsxs)("div",{className:"-mt-8 px-4 pb-4",children:[(0,t.jsxs)("div",{className:"relative flex items-start gap-3",children:[(0,t.jsx)(We,{to: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)(So,{size:"lg",children:[C?.user.image?(0,t.jsx)(md,{src:C.user.image,alt:T}):null,(0,t.jsx)(Co,{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:T}),(0,t.jsx)("p",{className:"truncate text-sm text-muted-foreground",children:R}),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)(vse,{label:"Invite",description:"Invite people to your organization.",icon:Yf,href:u,topLevel:i,onClick:M}):null,(0,t.jsx)(vse,{label:"Documentation",description:"Open Paperclip docs in a new tab.",icon:zN,href:ilt,external:!0,onClick:r(()=>S(!1),"onClick")}),(0,t.jsx)(hk,{variant:"menu-action",onAfterToggle:r(()=>S(!1),"onAfterToggle")}),(0,t.jsx)(oCe,{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:$,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)(lCe,{})]})]})]})]}),!N&&!i?(0,t.jsxs)(Un,{children:[(0,t.jsx)(Kn,{asChild:!0,children:(0,t.jsx)("a",{href:olt,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)(wg,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,t.jsx)(Wn,{side:"top",children:"Share feedback"})]}):null]})})}r(yse,"SidebarAccountMenu");function clt(e,s){return jCe(e,s)[0]?.toLowerCase()??null}r(clt,"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 dlt=new Set(["browse","connections","connect","chat","review","attention","gateways","advanced","app"]);function ult(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(ult,"isSkillsStoreRoute");function mlt(){const{sidebarOpen:e,setSidebarOpen:s,toggleSidebar:n,collapsed:a,peeking:i,setPeeking:o,isMobile:l,setForceCollapsed:c}=Fa(),{openNewIssue:d,openOnboarding:u}=Do(),{togglePanelVisible:h}=Zf(),p=Gc()?.pushToast??null,{companies:f,loading:x,selectedCompany:b,selectedCompanyId:v,selectionSource:j,setSelectedCompanyId:N}=gs(),{companyPrefix:w,pluginRoutePath:k}=ga(),S=Ln(),C=ra(),I=sM(),T=Vye(C.pathname,w).isTaskDetail,R=["/company/settings","/company/export","/company/import"].some(bt=>C.pathname.includes(bt)),A=jCe(C.pathname,w),D=A[0]?.toLowerCase()==="tools",M=A[0]?.toLowerCase()==="apps",$=M&&A[1]&&!dlt.has(A[1].toLowerCase())?A[1]:null,E=M&&A[1]?.toLowerCase()==="app"&&A[2]?A[2]:null,B=ult(C.pathname,w),z=(0,m.useRef)(!1),q=(0,m.useRef)(null),U=(0,m.useRef)(null),F=(0,m.useRef)(new Dve),K=(0,m.useRef)(C.key),G=pCe(l&&!T,C.pathname),[se,ee]=(0,m.useState)(!1),ne=(0,m.useMemo)(()=>{if(!w)return null;const bt=w.toUpperCase();return f.find(De=>De.issuePrefix.toUpperCase()===bt)??null},[f,w]),he=!!w&&!x&&f.length>0&&!ne,Z=(0,m.useMemo)(()=>k?.toLowerCase()??clt(C.pathname,w),[w,C.pathname,k]),re=ne?.id??null,ce=ne?.issuePrefix??null,{slots:H}=hd({slotTypes:["page","routeSidebar"],companyId:re,enabled:!!(re&&Z)}),Q=(0,m.useMemo)(()=>q7(H,Z),[Z,H]),Y=(0,m.useMemo)(()=>({companyId:re,companyPrefix:ce}),[re,ce]),te=R?(0,t.jsx)(Yot,{}):$?(0,t.jsx)(fse,{kind:"connection",connectionId:$}):E?(0,t.jsx)(fse,{kind:"application",applicationId:E}):M||D?(0,t.jsx)(Jot,{}):Q?(0,t.jsx)(Lu,{slot:Q,context:Y,className:"h-full w-full",missingBehavior:"placeholder"}):null,ae=te!=null,{data:me}=X({queryKey:P.health,queryFn:r(()=>su.get(),"queryFn"),retry:!1,refetchInterval:r(bt=>bt.state.data?.devServer?.enabled?2e3:!1,"refetchInterval"),refetchIntervalInBackground:!1}),oe=ae||B;(0,m.useLayoutEffect)(()=>(c(oe),()=>c(!1)),[oe,c]),(0,m.useEffect)(()=>{x||z.current||me?.deploymentMode!=="authenticated"&&(me?.cloud||f.length===0&&(z.current=!0,u()))},[f,x,u,me?.cloud,me?.deploymentMode]),(0,m.useEffect)(()=>{if(!w||x||f.length===0)return;if(!ne){const De=(v?f.find(Qe=>Qe.id===v):null)??f[0]??null;De&&v!==De.id&&N(De.id,{source:"route_sync"});return}if(w!==ne.issuePrefix){const De=C.pathname.replace(/^\/[^/]+/,"");S(`/${ne.issuePrefix}${De}${C.search}`,{replace:!0});return}const bt=fCe({matchedCompany:ne,selectedCompanyId:v,companies:f});if(bt){p?.({title:`${ne.name} is archived`,body:`Switched to ${bt.name}.`,tone:"info",dedupeKey:`archived-company-bounce:${ne.id}`}),N(bt.id,{source:"route_sync"}),S(`/${bt.issuePrefix}/dashboard`,{replace:!0});return}xCe({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 ie=h,ge=(0,m.useCallback)(()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",metaKey:!0,bubbles:!0,cancelable:!0}))},[]),be=(0,m.useRef)(null),le=(0,m.useRef)(!1),ue=(0,m.useRef)(!1),Se=(0,m.useCallback)(()=>{be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),ye=(0,m.useCallback)(()=>{Se(),be.current=window.setTimeout(()=>o(!0),50)},[Se,o]),Ie=(0,m.useCallback)(()=>{Se(),o(!0)},[Se,o]),Ke=(0,m.useCallback)(()=>{Se(),be.current=window.setTimeout(()=>o(!1),120)},[Se,o]),rt=(0,m.useCallback)(()=>{le.current=!0,a&&!ue.current&&ye()},[a,ye]),dt=(0,m.useCallback)(()=>{le.current=!1,ue.current=!1,Ke()},[Ke]),de=(0,m.useCallback)(()=>{ue.current||Ie()},[Ie]),ze=(0,m.useCallback)(()=>{le.current||Ke()},[Ke]);(0,m.useEffect)(()=>Se,[Se]);const gt=(0,m.useRef)(a);return(0,m.useEffect)(()=>{a!==gt.current&&(a?(Se(),o(!1),ue.current=le.current):ue.current=!1,gt.current=a)},[a,Se,o]),(0,m.useEffect)(()=>{if(!i)return;const bt=r(De=>{De.key==="Escape"&&(Se(),o(!1))},"onKeyDown");return window.addEventListener("keydown",bt),()=>window.removeEventListener("keydown",bt)},[i,Se,o]),hCe(),cCe({onNewIssue:r(()=>d(),"onNewIssue"),onSearch:ge,onToggleSidebar:n,onTogglePanel:ie,onShowShortcuts:r(()=>ee(!0),"onShowShortcuts"),onGoToInbox:r(()=>S("/inbox"),"onGoToInbox")}),(0,m.useEffect)(()=>{if(!l)return;const bt=30,De=50,Qe=75;let mt=0,Ye=0;const it=r(Ze=>{const Pe=Ze.touches[0];mt=Pe.clientX,Ye=Pe.clientY},"onTouchStart"),Nt=r(Ze=>{const Pe=Ze.changedTouches[0],Ce=Pe.clientX-mt;if(!(Math.abs(Pe.clientY-Ye)>Qe)){if(!e&&mt<bt&&Ce>De){s(!0);return}e&&Ce<-50&&s(!1)}},"onTouchEnd");return document.addEventListener("touchstart",it,{passive:!0}),document.addEventListener("touchend",Nt,{passive:!0}),()=>{document.removeEventListener("touchstart",it),document.removeEventListener("touchend",Nt)}},[l,e,s]),(0,m.useEffect)(()=>{const bt=document.body.style.overflow;return document.body.style.overflow=l?"visible":"clip",()=>{document.body.style.overflow=bt}},[l]),(0,m.useEffect)(()=>{if(!l)return bCe()},[l]),(0,m.useEffect)(()=>{if(typeof document>"u")return;const bt=U.current;return gCe(bt)},[C.pathname]),(0,m.useEffect)(()=>{const bt=U.current;if(!bt)return;const De=r(()=>{F.current.remember(K.current,bt.scrollTop)},"recordScroll");return bt.addEventListener("scroll",De,{passive:!0}),()=>bt.removeEventListener("scroll",De)},[]),(0,m.useLayoutEffect)(()=>{const bt=U.current,De=Mve({previousPathname:q.current,pathname:C.pathname,navigationType:I,state:C.state});q.current=C.pathname;const Qe=I==="POP",mt=Qe?F.current.recall(C.key):0;if(K.current=C.key,Qe){M3(bt,mt);const Ye=requestAnimationFrame(()=>M3(bt,mt));return()=>cancelAnimationFrame(Ye)}De&&Lve(bt)},[C.key,C.pathname,C.state,I]),(0,t.jsx)(Pve,{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)(qSe,{}),(0,t.jsx)(USe,{devServer:me?.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)(pse,{})})}),(0,t.jsx)(yse,{deploymentMode:me?.deploymentMode})]}):(0,t.jsxs)(nlt,{open:e,collapsed:a,peeking:i,resizable:!0,onPanelMouseEnter:rt,onPanelMouseLeave:dt,onPanelFocusCapture:a?de:void 0,onPanelBlurCapture:a?ze:void 0,children:[(0,t.jsx)("div",{className:"flex flex-1 min-h-0",children:(0,t.jsx)(pse,{})}),(0,t.jsx)(yse,{deploymentMode:me?.deploymentMode})]}),!l&&ae?(0,t.jsx)(rlt,{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)(a6,{mobile:l,onNavigateHome:r(()=>S("/dashboard"),"onNavigateHome")}),(0,t.jsx)(slt,{}),l&&R?(0,t.jsx)("div",{className:"border-b border-border px-4 pb-3",children:(0,t.jsx)(Qye,{})}):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:he?(0,t.jsx)(Eu,{scope:"invalid_company_prefix",requestedPrefix:w??b?.issuePrefix}):(0,t.jsx)(HSe,{children:(0,t.jsx)(lb,{})})}),(0,t.jsx)(oje,{})]})]})]}),l&&(0,t.jsx)(zSe,{visible:G}),(0,t.jsx)(dje,{}),(0,t.jsx)(Uje,{}),(0,t.jsx)(PSe,{}),(0,t.jsx)(LSe,{}),(0,t.jsx)($Se,{}),(0,t.jsx)(OSe,{open:se,onOpenChange:ee}),(0,t.jsx)(FSe,{}),(0,t.jsx)(BSe,{localTrusted:me?.deploymentMode==="local_trusted"})]})})}r(mlt,"Layout");var jse=null;function hlt(){return jse??=new IN,jse}r(hlt,"getDetachedClient");function plt(){const e=(0,m.useContext)(fI),{data:s,isFetched:n}=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn"),enabled:e!=null},e??hlt());return e?{enabled:s?.enableConferenceRoomChat===!0,loaded:n}:{enabled:!1,loaded:!0}}r(plt,"useConferenceRoomChatEnabled");function flt(){const{enabled:e,loaded:s}=plt();return s?e?(0,t.jsx)(lb,{}):(0,t.jsx)(Nn,{to:"/dashboard",replace:!0}):null}r(flt,"ConferenceRoomChatGate");var xlt=["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"],glt={"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 }"}},Nos=xlt.map(e=>glt[e]);function wCe({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(wCe,"TaskBrowserActivity");function kCe({item:e}){return(0,t.jsx)("article",{className:"rounded-lg border border-border bg-card p-3","aria-label":`Project created: ${e.name}`,children:(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)(xze,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground","aria-hidden":!0}),(0,t.jsxs)("div",{className:"min-w-0 flex-1 space-y-1",children:[(0,t.jsx)("p",{className:"text-xs text-muted-foreground",children:"Project created"}),(0,t.jsx)(We,{to:`/projects/${e.projectId}`,className:"break-words text-sm font-medium hover:underline focus-visible:underline",children:e.name}),e.description&&(0,t.jsx)("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:e.description}),e.repositories.length>0&&(0,t.jsx)("ul",{className:"space-y-1 pt-1",children:e.repositories.map(s=>(0,t.jsxs)("li",{className:"flex min-w-0 items-center gap-2 text-xs text-muted-foreground",children:[(0,t.jsx)(to,{className:"size-3 shrink-0","aria-hidden":!0}),(0,t.jsx)("a",{className:"truncate hover:underline focus-visible:underline",href:s.url,target:"_blank",rel:"noreferrer",children:s.name})]},s.id))})]})]})})}r(kCe,"TaskChatProjectCreatedCard");function blt({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)(Df,{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(blt,"TaskChatSkillCreatedCard");function vlt(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(vlt,"McpIcon");var ylt=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||ylt.has(s)}r(Gd,"isGenericToolName");function TW(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(TW,"mcpToolIdentity");function RW(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(RW,"identifierWords");function NCe(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(NCe,"sentenceCase");function pk(e){const s=(e??"").trim();return Gd(s)?"Unnamed tool":NCe(RW(TW(s)?.name??s))}r(pk,"humanizeToolName");var Nd=r((e,s,n)=>({key:e,singular:s,plural:n}),"group"),jlt={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"}},wlt={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:[]},klt={read:"read",edit:"update",delete:"delete",move:"move",search:"search",list:"list",execute:"run",think:"think",fetch:"fetch",switch_mode:"switch"};function Nlt(e){return RW(e).join("_")}r(Nlt,"normalizedKey");function Slt(e){const s=e[0];if(!s)return null;for(const[n,a]of Object.entries(wlt))if(a.includes(s))return n;return null}r(Slt,"inferredAction");function Clt(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(Clt,"actionFamily");var _lt={terminal:dg,grep:Dze,search:Gr,read:zN,edit:fM,web:rze,plan:Vy,question:Vc,agent:my,safety:Li,image:OI,wait:Jd,mcp:vlt,other:Df};function Ilt(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(Ilt,"actionCopy");function Alt(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(Alt,"defaultSummaryGroup");function Tlt(e){return e==="read"||e==="list"?Nd("paperclip_read","Paperclip read","Paperclip reads"):Nd("task_operation","task operation","task operations")}r(Tlt,"paperclipSummaryGroup");function jy(e){const s=(e.name??"").trim(),n=TW(s),a=(e.namespace??n?.namespace??"").trim(),i=(n?"mcp":e.transport??"builtin").toLowerCase(),o=(n?.name??s).trim(),l=RW(o),c=Nlt(o),d=jlt[c],u=klt[(e.operation??"").trim().toLowerCase()],h=Slt(l),p=d?.action??u??h??"other",f=d?"exact":u?"kind":h?"inferred":Gd(o)?"unnamed":"fallback",x=Gd(o)?"Unnamed tool":pk(o),b=/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(o),v=h&&b&&l.length>1?l.slice(1):[],j=v.length?NCe(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}`}:Ilt(p,d?void 0:j),w=d?.family??Clt(p),k=i==="mcp"?"mcp":w,S=a?pk(a):i==="mcp"?"MCP":void 0,C=a.toLowerCase()==="paperclip"?Tlt(p):d?.group??Alt(p);return{icon:_lt[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(jy,"toolActivityPresentation");function n4(e){const s=jy({name:e});return{family:s.family,icon:s.icon,verbLabel:s.runningLabel}}r(n4,"toolTaxonomy");function Rlt(e){const s=(e??"").trim().toLowerCase();return s==="thinking"?Yx:s==="responding"||s.startsWith("responding (")?Nze:null}r(Rlt,"statusLabelIcon");var J$=["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"],X$=["Brewing","Tinkering","Distilling","Deliberating"],wse=(()=>{const e=[],s=Math.max(J$.length,X$.length);for(let n=0;n<s;n++)n<J$.length&&e.push(J$[n]),n<X$.length&&e.push(X$[n]);return e})(),Elt=1e4;function Plt(e){const s=(e??"").trim().toLowerCase();return s==="running"||s==="working"}r(Plt,"isGenericStatusLabel");function Mlt(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(Mlt,"fnv1a");function Dlt(e,s=0){const n=Math.floor(Math.max(0,s)/Elt);return wse[(Mlt(e)+n)%wse.length]}r(Dlt,"whimsyWord");var Llt=[{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}],Sos=Array.from(new Set(Llt.map(e=>e.group)));function SCe(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(SCe,"parseCssTimeMs");function $lt(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($lt,"elapsedLabel");function Olt(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(Olt,"liveElapsedLabel");function Flt(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(Flt,"useLiveElapsedMs");function Blt(e,s){return!Number.isFinite(e)||!Number.isFinite(s)||s<=0?0:Math.max(0,Math.round(e/s)-1)}r(Blt,"lineScrollOffset");function mE(e){const s=getComputedStyle(document.documentElement).getPropertyValue(e),n=SCe(s);return Number.isFinite(n)?n:0}r(mE,"motionTokenMs");function zlt({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(Blt(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),mE("--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(zlt,"LiveSelfTalkLine");function qlt(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)},mE("--motion-line-scroll")))},mE("--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=mE("--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(qlt,"useHeldSelfTalk");var Ult={running:{Icon:nt,spin:!0,tone:"text-(--status-agent-running)"},working:{Icon:nt,spin:!0,tone:"text-(--status-agent-running)"},awaiting_approval:{Icon:UN,spin:!1,tone:"text-primary"},interrupted:{Icon:y7,spin:!1,tone:"text-destructive"},refused:{Icon:um,spin:!1,tone:"text-destructive"},truncated:{Icon:Mze,spin:!1,tone:"text-(--status-agent-paused)"}};function CCe({item:e,onApprovalDecision:s,chevronOpen:n,onToggle:a}){const{Icon:i,spin:o,tone:l}=Ult[e.status],c=e.status==="awaiting_approval",d=e.status==="running"||e.status==="working",u=Flt(e.startedAtMs,d),h=qlt(d?e.selfTalk:void 0,d),p=$lt(e.elapsedMs);if(d){const f=Olt(u??e.elapsedMs),x=e.selfTalk!=null,b=e.toolName?n4(e.toolName).icon:x?null:Rlt(e.label),v=x||Plt(e.label)?Dlt(e.id,u??e.elapsedMs??0):e.label,j=(0,t.jsxs)("div",{className:"tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground",children:[n!==void 0?(0,t.jsx)("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center","data-testid":"task-chat-status-caret-slot",children:(0,t.jsx)(Pn,{className: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)(zlt,{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(CCe,"TaskChatStatusPill");var Cg=(0,m.createContext)(null);function Xy(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(Xy,"formatBytes$4");var T5=new Set(["application/octet-stream","binary/octet-stream","application/x-binary"]),Klt=[".mp4",".m4v",".webm",".mov",".qt",".quicktime"],Wlt=[".png",".jpg",".jpeg",".gif",".webp",".avif",".bmp",".ico"],Vlt=new Set(["application/wasm"]),Hlt=new Set(["application/zip","application/x-zip","application/x-zip-compressed"]),_Ce=new Set(["text/markdown","text/x-markdown","application/markdown","application/x-markdown"]),Glt=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"]),Qlt=[".csv",".css",".graphql",".htm",".html",".js",".json",".jsx",".log",".markdown",".md",".mdx",".php",".py",".sh",".sql",".toml",".ts",".tsx",".txt",".xml",".yaml",".yml"];function rA(e){return(e??"").toLowerCase().split(";")[0]?.trim()??""}r(rA,"normalizeOutputContentType");function Ylt(e){const s=(e??"").trim().toLowerCase();return s?Qlt.some(n=>s.endsWith(n)):!1}r(Ylt,"hasDocumentLikeFilename");function ICe(e){return Hlt.has(e)||e.endsWith("+zip")}r(ICe,"isZipContentType");function Jlt(e){return e?!!(e.startsWith("text/")||_Ce.has(e)||Glt.has(e)||e.startsWith("application/")&&(e.endsWith("+json")||e.endsWith("+xml"))):!1}r(Jlt,"isDocumentLikeOutputContentType");function Xlt(e,s){const n=rA(e);return!n||Jlt(n)||T5.has(n)&&Ylt(s)?!1:n.startsWith("video/")||n.startsWith("image/")||n==="application/pdf"||Vlt.has(n)||ICe(n)||T5.has(n)}r(Xlt,"isOutputEligibleContentType");function Zlt(e){const s=rA(e);if(s.startsWith("video/")){const n=s.slice(6);return n==="quicktime"?{label:"MOV",tone:"video"}:{label:(n||"vid").toUpperCase().slice(0,4),tone:"video"}}return s==="application/pdf"?{label:"PDF",tone:"pdf"}:ICe(s)?{label:"ZIP",tone:"zip"}:s.startsWith("image/")?{label:"IMG",tone:"image"}:_Ce.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(Zlt,"getOutputFileGlyph");function $u(e,s){const n=rA(e);if(n.startsWith("video/"))return!0;if(!T5.has(n))return!1;const a=(s??"").trim().toLowerCase();return Klt.some(i=>a.endsWith(i))}r($u,"isVideoLikeOutput");function wy(e){const s=rA(e);return s.startsWith("image/")&&s!=="image/svg+xml"}r(wy,"isImageContentType");function r4(e,s){const n=rA(e);if(wy(n))return!0;if(n&&!T5.has(n))return!1;const a=(s??"").trim().toLowerCase();return Wlt.some(i=>a.endsWith(i))}r(r4,"isImageLikeOutput");function kse(e){const s=new Date(e).getTime();return Number.isNaN(s)?0:s}r(kse,"toTime");function a4(e){const s=(e??[]).filter(n=>n.type==="artifact"&&n.provider==="paperclip").flatMap(n=>{const a=RLe.safeParse(n.metadata);return a.success&&!Xlt(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:kse(a.createdAt)-kse(n.createdAt)),{items:s,primary:s[0]??null,rest:s.slice(1),count:s.length}}r(a4,"getIssueOutputs");function EW(e){return e.metadata?.originalFilename||e.title||"output"}r(EW,"outputFilename");function ACe(e){return new Set(a4(e).items.flatMap(s=>{const n=s.metadata?.attachmentId;return n?[n]:[]}))}r(ACe,"getPromotedOutputAttachmentIds");function ect(e){return e.contentType.toLowerCase().split(";")[0]?.trim()??""}r(ect,"normalizedContentType");function sb(e){return e.originalFilename??e.id}r(sb,"attachmentFilename");function i4(e){return e.openPath??e.contentPath}r(i4,"attachmentOpenPath");function nS(e){return e.downloadPath??`${e.contentPath}?download=1`}r(nS,"attachmentDownloadPath");function TCe(e){const s=ect(e);return r4(s,e.originalFilename)&&!/^image\/hei[cf](?:-sequence)?$/.test(s)}r(TCe,"isImageAttachment$1");function RCe(e){return $u(e.contentType,e.originalFilename)}r(RCe,"isVideoAttachment");function ECe(e){return wpe(e)}r(ECe,"isMarkdownAttachment");function Zy(e){const s=e.contentType.toLowerCase().split(";")[0].trim();return wpe(e)||s.startsWith("text/")||/^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(s)||["","application/octet-stream"].includes(s)&&/\.(txt|log|csv|json|yaml|yml|toml|ini|sh|ts|tsx|js|jsx|py|css|html)$/i.test(e.originalFilename??"")}r(Zy,"isTextAttachment");function PCe(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(PCe,"downloadBlob$1");function tct(e,s,n){PCe(e,new Blob([s],{type:`${n};charset=utf-8`}))}r(tct,"downloadTextFile");var Z$="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 MCe({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,T)=>{c(I),p(null);try{await T(),u(I)}catch(R){u(null),p(R instanceof Error?R.message:"Export failed")}finally{c(null)}clearTimeout(v.current),v.current=setTimeout(()=>{u(null),p(null)},2e3)},[]),N=(0,m.useCallback)(async()=>i??(await At.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:Z$,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)(vs,{"aria-hidden":"true",className:"h-3.5 w-3.5"}):(0,t.jsx)(Ar,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:Z$,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 T=$Fe(a);tct(LJ(n,T),await N(),T==="md"?"text/markdown":"text/plain")})},"onClick"),children:(0,t.jsx)(oo,{"aria-hidden":"true",className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{type:"button",className:Z$,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()=>{PCe(LJ(n,"pdf"),await At.getDocumentPdf(e,s))})},"onClick"),children:(0,t.jsx)(pze,{"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(MCe,"DocumentExportActions");function M_({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(M_,"PreviewFrame");function R5({label:e}){return(0,t.jsx)(M_,{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)(Hc,{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(R5,"PlaceholderPreview");function sct({artifact:e}){const[s,n]=(0,m.useState)(!1);return s||!e.contentPath?(0,t.jsx)(R5,{label:"Image"}):(0,t.jsx)(M_,{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(sct,"ImagePreview");function nct({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)(M_,{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)(so,{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)(M_,{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)(so,{className:"h-5 w-5 translate-x-0.5 text-white","aria-hidden":"true"})})})]})}r(nct,"VideoPreview");function rct({artifact:e}){const s=e.previewText?.trim();return s?(0,t.jsxs)(M_,{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)(R5,{label:e.source==="document"?"Document":"Text"})}r(rct,"TextPreview");function aA({artifact:e}){switch(e.mediaKind){case"image":return(0,t.jsx)(sct,{artifact:e},e.contentPath);case"video":return(0,t.jsx)(nct,{artifact:e},e.contentPath);case"text":case"document":return(0,t.jsx)(rct,{artifact:e});case"file":return(0,t.jsx)(R5,{label:"File"});default:return(0,t.jsx)(R5,{})}}r(aA,"ArtifactPreview");function Nse({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(Nse,"SecondaryAction");function act({artifact:e}){return(0,t.jsxs)(We,{to:e.href,disableIssueQuicklook:!0,"data-testid":"artifact-card","data-media-kind":e.mediaKind,className:"group flex flex-col overflow-hidden rounded-lg border border-border bg-card cursor-pointer transition-colors hover:border-foreground/20 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,t.jsx)(aA,{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)(MCe,{issueId:e.issue.id,documentKey:e.documentKey,title:e.title}):null,e.openPath?(0,t.jsx)(Nse,{href:e.openPath,title:"Open file in new tab",children:(0,t.jsx)(qn,{className:"h-3.5 w-3.5"})}):null,e.downloadPath?(0,t.jsx)(Nse,{href:e.downloadPath,download:!0,title:"Download file",children:(0,t.jsx)(oo,{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(act,"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 DCe(e,s){return X({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(DCe,"useEmailThread");var LCe=(0,m.createContext)(null);function ict({companyId:e,issueId:s,children:n}){const a=DCe(e,s);return(0,t.jsx)(LCe.Provider,{value:a.data??null,children:n})}r(ict,"EmailThreadProvider");function $Ce(e){const s=(0,m.useContext)(LCe),n=s?.messages.find(a=>a.commentId===e);return n&&s?(0,t.jsx)(OCe,{message:n,publication:s.publications.find(a=>a.providerMessageId===n.providerMessageId),issueId:s.issueId}):null}r($Ce,"useEmailComment");function OCe({message:e,publication:s,issueId:n}){const a=X({queryKey:["email-attachments",n],queryFn:r(()=>At.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)(H8,{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)(Hc,{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(OCe,"EmailMessageCard");var Qv=(0,m.createContext)(null);function ej({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=sb(p),x=$u(p.contentType,p.originalFilename);return(0,t.jsx)(FOe,{open:n,onOpenChange:a,children:(0,t.jsxs)($Oe,{children:[(0,t.jsx)(OOe,{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)(UOe,{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:nS(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)(oo,{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)(Vn,{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)(Mu,{className:"h-7 w-7"})})}),(0,t.jsx)("div",{className:"flex-1 flex items-center justify-center min-w-0 min-h-0 h-full px-2",children:x?(0,t.jsx)("video",{ref:c,src:p.contentPath,className:"max-w-full max-h-full rounded-lg",controls:!0,playsInline:!0}):(0,t.jsx)("img",{ref:c,src:p.contentPath,alt:f,className:"max-w-full max-h-full object-contain select-none rounded-lg",draggable:!1})}),(0,t.jsx)("div",{className:"w-16 md:w-24 shrink-0 flex items-center justify-center h-full",children:e.length>1&&(0,t.jsx)("button",{type:"button",onClick:d,className:"rounded-full bg-white/10 p-3 text-white/60 hover:text-white hover:bg-white/20 transition-colors",title:"Next",children:(0,t.jsx)(Pn,{className:"h-7 w-7"})})})]}),(0,t.jsx)("div",{className:"h-6 shrink-0"})]})]})})}r(ej,"ImageGalleryModal");var PW=(0,m.createContext)(null);function oct({value:e,children:s}){return(0,t.jsx)(PW.Provider,{value:e,children:s})}r(oct,"DispositionRecoveryProvider");function lct(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(lct,"readDispositionRecoverySnapshot");function FCe(e){return lct(e,(0,m.useContext)(PW)?.issue.activeRecoveryAction)}r(FCe,"useDispositionRecoverySnapshot");function cct(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(cct,"dispositionRetryUnavailableReason");function dct(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(dct,"descriptionFor");function MW({snapshot:e,createdAt:s,defaultExpanded:n=!1}){const a=(0,m.useContext)(PW),[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=cct(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?vs:Ds;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}.`:dct(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)(nt,{"aria-hidden":"true",className:"size-3 animate-spin motion-reduce:animate-none"}):(0,t.jsx)(Ni,{"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:Zi(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(MW,"DispositionRecoveryNotice");var BCe={neutral:{container:"border-border bg-muted/35 dark:bg-muted/20",iconWrap:"bg-muted text-foreground/70",icon:$f,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:$f,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:la,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:Ds,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:Bk,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 uct(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}r(uct,"formatTimestamp$1");function mct({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(mct,"MetadataRow$1");function zCe({sections:e,tone:s="neutral"}){const n=BCe[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)(mct,{row:o,tone:n},l))})]},i))})}r(zCe,"SystemNoticeMetadataSections");function DW({tone:e="neutral",label:s,body:n,source:a,metadata:i,detailsDefaultOpen:o=!1,timestamp:l,className:c}){const d=BCe[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:uct(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)(zCe,{sections:i,tone:e})}):null]})}r(DW,"SystemNotice");var hct="System update",pct=80;function fct(e){const s=e.match(/Latest retry failure: `([^`]+)`/);return s?s[1]:null}r(fct,"retryFailureCode");function xct(e){const s=e.match(/Recovery owner: \[([^\]]+)\]\(/)?.[1]?.trim();return s&&s.length>0?s:null}r(xct,"recoveryOwnerName");function gct(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<=pct?a:`${a.slice(0,79).trimEnd()}…`}r(gct,"firstSentence");function bct(e){const s=e.presentation?.title?.trim(),n=e.presentation?.tone;if(s)return{title:s,tone:n??"neutral"};const a=e.body??"",i=fct(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=xct(a);return{title:o?`Task paused — waiting on ${o}`:"Task paused — waiting on a recovery owner",tone:n??"warning"}}return{title:hct,tone:n??"neutral",detail:gct(a)}}r(bct,"humanizeSystemNotice");var vct={neutral:"System notice",info:"System notice",success:"System notice",warning:"System warning",danger:"System alert"};function Wj(e,s){const n=e.label?.trim();return n&&n.length>0?n:s}r(Wj,"metadataRowText");function yct(e,s){switch(e.type){case"text":return{kind:"text",label:Wj(e,"Detail"),value:e.text};case"code":return{kind:"code",label:Wj(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:Wj(e,"Task"),identifier:n,href:`/issues/${n}`,title:e.title??void 0}:{kind:"text",label:Wj(e,"Task"),value:e.title??"unknown"}}case"agent_link":{const n=e.name?.trim()||e.agentId.slice(0,8);return{kind:"agent",label:Wj(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:Wj(e,"Run"),runId:e.runId,href:a,status:e.title??void 0}}default:return null}}r(yct,"mapMetadataRow");function LW(e,s={}){return!e||!Array.isArray(e.sections)?[]:e.sections.map(n=>{const a=n.rows.map(o=>yct(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(LW,"mapCommentMetadataToSystemNoticeSections");function qCe(e,s){const n=s?.trim();return n&&n.length>0?n:vct[e]}r(qCe,"systemNoticeLabelForTone");function jct(e){const s=e.presentation?.tone??"neutral",n=qCe(s,e.presentation?.title),a=!!e.presentation?.detailsDefaultOpen,i=LW(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(jct,"buildSystemNoticeProps");var wct={neutral:$f,info:$f,success:la,warning:Ds,danger:Bk},kct={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 Nct({item:e,onTryAgainNoLiveExecutionPath:s,tryAgainNoLiveExecutionPathPending:n=!1}){const a=FCe(e.metadata),i=Rp(),[o,l]=(0,m.useState)(!!e.presentation?.detailsDefaultOpen),c=(0,m.useId)(),{title:d,tone:u,detail:h}=bct({body:e.text,presentation:e.presentation}),p=LW(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=wct[u],b=e.createdAtIso?Zi(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)(MW,{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",kct[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)(Rn,{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)(zCe,{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(Nct,"TaskChatSystemNotice");function $W({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)(_r,{agent:n,name:e,size:24})}),(0,t.jsx)("span",{className:"text-sm font-semibold text-foreground",children:e})]})}r($W,"TaskChatAgentIdentity");function Sse(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(Sse,"galleryItemForMedia");function Cse(e){return e.filter((s,n)=>e.findIndex(a=>s.id&&a.id===s.id||a.url===s.url)===n)}r(Cse,"uniqueAttachmentRefs");function UCe(e){return $Ce(e.item.id)??(0,t.jsx)(Sct,{...e})}r(UCe,"TaskChatBubble");function Sct({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)(Cg),f=(0,m.useContext)(Qv),[x,b]=(0,m.useState)(null),v=(0,m.useCallback)(B=>{f?.(B)||b(B)},[f]);if(e.interstitial)return null;if(e.author==="system")return(0,t.jsx)(Nct,{item:e,onTryAgainNoLiveExecutionPath:d,tryAgainNoLiveExecutionPathPending:u});const j=e.author==="human",N=j&&e.sourceChannel==="imessage-photon",{refs:w,text:k}=aVe(e.text),S=nVe(k),C=rVe(k),I=uZ(w,c),T=uZ(S,c),R=c.filter(B=>B.issueCommentId===e.id).map(B=>({id:B.id,name:B.originalFilename?.trim()||"attachment",url:B.contentPath,contentType:B.contentType,byteSize:B.byteSize,openPath:B.openPath,downloadPath:B.downloadPath})),A=Cse([...T,...I.filter(N2),...R.filter(N2)]),D=Cse([...I.filter(B=>!N2(B)),...R.filter(B=>!N2(B))]),M=[...A,...D.filter(B=>$u(B.contentType,B.name))],$=x!==null&&!M.some(B=>B.url===x)?[Sse(x)]:M.map(B=>Sse(B.url,B.name,B)),E=x===null?-1:Math.max(0,M.findIndex(B=>B.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)($W,{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)(Rn,{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((B,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 ${B.name||`image ${z+1}`}`,onClick:r(()=>v(B.url),"onClick"),children:(0,t.jsx)("img",{src:B.openPath??B.url,alt:B.name,loading:"lazy",className:"h-full w-full object-cover transition-transform group-hover:scale-(--s-1_02)"})},B.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(B=>B.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)(p9,{"data-testid":"task-chat-bubble-attachments",children:D.map(B=>{const z=Rje(B),q=z.icon,U=f9(B.byteSize),F=$u(B.contentType,B.name);return(0,t.jsxs)(c9,{size:"sm",children:[(0,t.jsx)(d9,{className:F?"aspect-video group-data-[size=sm]/attachment:w-20":void 0,children:F?(0,t.jsx)(aA,{artifact:{title:B.name,contentPath:B.openPath??B.url,mediaKind:"video"}}):(0,t.jsx)(q,{"aria-hidden":!0})}),(0,t.jsxs)(u9,{children:[(0,t.jsx)(m9,{className:"max-w-48",children:B.name}),(0,t.jsx)(h9,{className:"max-w-48",children:U?`${z.label} · ${U}`:z.label})]}),(0,t.jsx)(_je,{"aria-label":`Open ${B.name}`,onClick:F?()=>v(B.url):void 0,render:F?(0,t.jsx)("button",{type:"button"}):(0,t.jsx)("a",{href:B.openPath??B.url,onClick:r(K=>{p&&B.id&&Zy({contentType:B.contentType??"",originalFilename:B.name})&&!K.metaKey&&!K.ctrlKey&&!K.shiftKey&&!K.altKey&&(K.preventDefault(),p(B.id,B.name))},"onClick"),target:"_blank",rel:"noreferrer"})})]},B.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((B,z)=>(0,t.jsxs)("li",{children:[(0,t.jsx)("span",{className:"font-mono text-foreground",children:B.commandOrCheck}),B.reasonCode?` · ${B.reasonCode.replaceAll("_"," ")}`:"",B.detail?(0,t.jsx)("span",{className:"block",children:B.detail}):null]},`${B.commandOrCheck}:${z}`))})]}):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)(ej,{items:$,initialIndex:E,open:!0,onOpenChange:r(B=>{B||b(null)},"onOpenChange")}):null]})}r(Sct,"TaskChatBubbleContent");function _se(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(_se,"turnSummaryMetrics");function Ise({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)($W,{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)(Rn,{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?Vn:vs,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&&_se(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:_se(e.summary)})}):null,(0,t.jsx)(Pn,{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)(CCe,{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(Ise,"TaskChatTurn");var Cct={session_start:Cu,interrupted:y7,turn_boundary:wg};function KCe({item:e,onTryAgain:s,tryAgainPending:n=!1}){const[a,i]=(0,m.useState)(!1),o=(0,m.useId)(),l=Rp(),c=e.tone==="neutral"?mb:Cct[e.variant],d=e.variant==="interrupted"&&e.tone!=="neutral",u=e.createdAtIso?Zi(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)(We,{to:e.planHref,children:"View saved plan"})}):null,e.runHref?(0,t.jsx)(L,{asChild:!0,variant:"ghost",size:"xs",children:(0,t.jsx)(We,{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(KCe,"TaskChatMarker");var WCe=(0,m.createContext)(null);function OW(e,s){const n=(0,m.useContext)(WCe),[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(OW,"useTaskChatExpansion");var _ct={pending:{Icon:nt,spin:!1,tone:"text-muted-foreground"},in_progress:{Icon:nt,spin:!0,tone:"text-(--status-agent-running)"},completed:{Icon:vs,spin:!1,tone:"text-muted-foreground"},failed:{Icon:Vn,spin:!1,tone:"text-destructive"},interrupted:{Icon:Vn,spin:!1,tone:"text-muted-foreground"}};function VCe({item:e}){const{Icon:s,spin:n,tone:a}=_ct[e.status],i=n4(e.rawName??e.name).icon,[o,l]=OW(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)(Li,{className:"h-3 w-3"}):(0,t.jsx)(S7,{className:"h-3 w-3"}),e.decision]}):null,c?(0,t.jsx)(Pn,{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(VCe,"TaskChatToolCard");function FW({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)(p7,{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(FW,"TaskChatUsageReadout");function Vp(e,...s){return e.details.find(n=>s.includes(n.label))?.value}r(Vp,"providerDetail");function eO(e){if(!(!e||Gd(e)||/^tool(?:\s+|_)call\b/i.test(e)))return e}r(eO,"meaningfulToolDetail");function Ict(e){const s=e.summary??Vp(e,"Query","URL","Target","Name","Reference","Reason","Summary");switch(e.family){case"research":{const n=Vp(e,"Action")?.toLowerCase();return n==="open_page"?{icon:Gr,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:Gr,runningLabel:"Searching the page",completedLabel:"Searched the page",failedLabel:"Page search failed",interruptedLabel:"Page search stopped",detail:s}:{icon:Gr,runningLabel:"Searching the web",completedLabel:"Searched the web",failedLabel:"Web search failed",interruptedLabel:"Web search stopped",detail:s}}case"tool_execution":{const n=Vp(e,"Name"),a=Vp(e,"Target"),i=Vp(e,"Progress"),o=jy({name:n,transport:Vp(e,"Transport"),namespace:Vp(e,"Namespace"),operation:Vp(e,"Operation"),target:a,progress:i}),l=eO(e.summary)??eO(i)??eO(a),c=!!(l&&n&&pk(l)===pk(n)),d=n?TW(n)?.name??n:o.displayName,u=o.sourceLabel?`${o.sourceLabel} · ${d}`:n&&!Gd(n)&&pk(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:Vy,runningLabel:"Updating the plan",completedLabel:"Updated the plan",failedLabel:"Plan update failed",interruptedLabel:"Plan update stopped",detail:s};case"delegation":{const n=Vp(e,"Action")?.toLowerCase();return n==="message"?{icon:Eo,runningLabel:"Messaging a subagent",completedLabel:"Messaged a subagent",failedLabel:"Subagent message failed",interruptedLabel:"Subagent message stopped",detail:s}:n==="resume"?{icon:Eo,runningLabel:"Resuming a subagent",completedLabel:"Resumed a subagent",failedLabel:"Couldn’t resume the subagent",interruptedLabel:"Subagent resume stopped",detail:s}:n==="close"?{icon:Eo,runningLabel:"Closing a subagent",completedLabel:"Closed a subagent",failedLabel:"Couldn’t close the subagent",interruptedLabel:"Subagent close stopped",detail:s}:n==="wait"?{icon:Eo,runningLabel:"Waiting for subagents",completedLabel:"Finished waiting for subagents",failedLabel:"Subagent wait failed",interruptedLabel:"Stopped waiting for subagents",detail:s}:{icon:Eo,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:Ji,runningLabel:"Switching models",completedLabel:"Switched models",failedLabel:"Model switch failed",interruptedLabel:"Model switch stopped",detail:s}:{icon:Ji,runningLabel:"Verifying the model",completedLabel:"Verified the model",failedLabel:"Model verification failed",interruptedLabel:"Model verification stopped",detail:s};case"context":return{icon:wI,runningLabel:"Compacting context",completedLabel:"Compacted context",failedLabel:"Context compaction failed",interruptedLabel:"Context compaction stopped",detail:s};case"artifact":return e.eventType==="artifact.viewed"?{icon:Y1,runningLabel:"Viewing an artifact",completedLabel:"Viewed an artifact",failedLabel:"Couldn’t view the artifact",interruptedLabel:"Artifact view stopped",detail:s}:{icon:Y1,runningLabel:"Generating an artifact",completedLabel:"Generated an artifact",failedLabel:"Artifact generation failed",interruptedLabel:"Artifact generation stopped",detail:s};case"review":return Vp(e,"State")?.toLowerCase()==="exited"?{icon:UJ,runningLabel:"Leaving review mode",completedLabel:"Left review mode",failedLabel:"Couldn’t leave review mode",interruptedLabel:"Review-mode change stopped",detail:s}:{icon:UJ,runningLabel:"Entering review mode",completedLabel:"Entered review mode",failedLabel:"Couldn’t enter review mode",interruptedLabel:"Review-mode change stopped",detail:s};case"hook":return{icon:to,runningLabel:"Running a hook",completedLabel:"Ran a hook",failedLabel:"Hook failed",interruptedLabel:"Hook stopped",detail:s};case"memory":return{icon:zN,runningLabel:"Checking memory",completedLabel:"Referenced memory",failedLabel:"Memory lookup failed",interruptedLabel:"Memory lookup stopped",detail:s};case"safety":return{icon:Li,runningLabel:"Reviewing safety",completedLabel:"Reviewed safety",failedLabel:"Safety review failed",interruptedLabel:"Safety review stopped",detail:s};case"terminal":return{icon:mg,runningLabel:"Sending terminal input",completedLabel:"Sent terminal input",failedLabel:"Terminal input failed",interruptedLabel:"Terminal input stopped",detail:s};case"wait":return{icon:Jd,runningLabel:"Waiting",completedLabel:"Finished waiting",failedLabel:"Wait failed",interruptedLabel:"Wait stopped",detail:s};case"provider_notice":return{icon:Ds,runningLabel:"Provider notice",completedLabel:"Provider notice",failedLabel:"Provider error",interruptedLabel:"Provider notice",detail:s}}}r(Ict,"providerActivityPresentation$1");function Act(e){const s=e.totals.files||e.files.length,n=s>0?`${s} ${s===1?"file":"files"}`:void 0;return{icon:fM,runningLabel:"Editing files",completedLabel:"Edited files",detail:n}}r(Act,"workspaceChangePresentation");function Tct(e){return{icon:Wa,runningLabel:"Referencing a file",completedLabel:"Referenced a file",detail:e.line==null?e.path:`${e.path}:${e.line}`}}r(Tct,"workspaceFilePresentation");function Rct(e){return{icon:e.resourceKind==="document"?Wa:zk,runningLabel:"Saving a resource",completedLabel:e.resourceKind==="document"?"Added a document":"Added a deliverable",detail:e.title}}r(Rct,"resourcePresentation");function HCe(e){switch(e.surface){case"provider_activity":return Ict(e);case"workspace_change":return Act(e);case"workspace_file":return Tct(e);case"resource":return Rct(e);case"runtime_request":case"run_result":case"run_terminal":return null}}r(HCe,"protocolActivityPresentation");function GCe(e){return e.surface==="provider_activity"?e.status==="running":e.surface==="workspace_change"?!e.complete:!1}r(GCe,"protocolActivityIsRunning");function Ect(e,s){return e.surface!=="provider_activity"?GCe(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(Ect,"protocolActivityLabel");var Pct={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 Mct(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=jy({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=jy({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=HCe(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":Pct[d.family],d.icon,d.order)}s.size||(e.some(d=>d.kind==="thinking")?n("Thought through the task",Yx):e.some(d=>d.kind==="marker")?n("Activity stopped",Td):n("Recorded usage",p7));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:Tl}}r(Mct,"completedActivitySummary");var Ase=5,Dct=8;function Lct(e,s=!1){return s&&(e==="blocked"||e==="failed")?(0,t.jsx)(ug,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0}):e==="in_progress"?(0,t.jsx)(nt,{className:"h-3 w-3 animate-spin text-(--status-agent-running)","aria-hidden":!0}):e==="completed"?(0,t.jsx)(vs,{className:"h-3 w-3 text-(--status-task-icon-done)","aria-hidden":!0}):e==="blocked"||e==="failed"?(0,t.jsx)(Vn,{className:"h-3 w-3 text-destructive","aria-hidden":!0}):(0,t.jsx)(ug,{className:"h-3 w-3 text-muted-foreground","aria-hidden":!0})}r(Lct,"stepStatusIcon");function QCe({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(QCe,"DetailList");function $ct(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e}}r($ct,"sourceHostname");function Oct({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,Ase),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)(qn,{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:$ct(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>Ase?(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)(QCe,{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(Oct,"ResearchDetails");function Fct({item:e,neutral:s=!1}){return e.family==="research"?(0,t.jsx)(Oct,{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:Lct(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)(qn,{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)(QCe,{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(Fct,"ProviderDetails");function Bct({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,Dct),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(Bct,"WorkspaceChangeDetails");function zct({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)(oxe,{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)(Rn,{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(zct,"WorkspaceFileDetails");function YCe(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)(Fct,{item:e,neutral:s}):null;case"workspace_change":return(0,t.jsx)(Bct,{item:e});case"workspace_file":return(0,t.jsx)(zct,{item:e});case"resource":case"runtime_request":case"run_result":case"run_terminal":return null}}r(YCe,"detailContent");function JCe(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(JCe,"safeActivityHref");function qct(e){return e.surface==="resource"?!!JCe(e.href):YCe(e)!==null||e.surface==="provider_activity"&&!!e.summary?.trim()}r(qct,"hasTaskChatProtocolActivityDetails");function Uct({item:e,neutral:s=!1}){const n=YCe(e,s);if(e.surface==="resource"){const a=JCe(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(Uct,"TaskChatProtocolActivityDetails");function XCe(e,s){if(e.kind==="tool"){const d=jy({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:Yx,label:d?"Thinking":"Thought",target:e.lines.filter(u=>u.trim()).at(-1)?.trim(),mono:!1,running:d}}if(e.kind==="protocol"){const d=HCe(e);return d?{icon:d.icon,label:Ect(e,d),target:d.detail,mono:!0,running:s&&GCe(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:p7,label:e.label??"Token usage",target:c||e.detail,mono:!1,running:!1}}r(XCe,"presentation");function h6({item:e,active:s}){const n=XCe(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(h6,"ActivityContent");function Kct({item:e,active:s}){const n=Qke(),[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)(h6,{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)(h6,{item:e,active:s})},e.id)]})}r(Kct,"RollingActivity");function Wct({item:e}){return e.kind==="thinking"?(0,t.jsx)(Rn,{softBreaks:!0,children:e.lines.join(`
|
|
357
357
|
`)}):e.kind==="usage"?(0,t.jsx)(FW,{item:e}):e.kind==="protocol"?(0,t.jsx)(Uct,{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(Wct,"ActivityDetails");function Vct(e){return e.kind==="protocol"?qct(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(Vct,"hasActivityDetails");function Hct({item:e,active:s}){const[n,a]=OW(`runner-detail:${e.id}`,!1),i=(0,m.useId)(),o=Vct(e),l=(0,t.jsx)(h6,{item:e,active:s});return(0,t.jsxs)("li",{className:"min-w-0","data-activity-item-id":e.id,children:[o?(0,t.jsxs)("button",{type:"button",className:"flex h-8 w-full min-w-0 items-center gap-2 rounded-sm text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:r(()=>a(!n),"onClick"),"aria-expanded":n,"aria-controls":n?i:void 0,children:[l,(0,t.jsx)(Pn,{className: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)(Wct,{item:e})}):null]})}r(Hct,"ExpandedActivity");function D_({item:e,defaultExpanded:s=!1}){const[n,a]=OW(e.id,s),i=(0,m.useId)(),o=e.items.filter(h=>XCe(h,!1)!==null),l=o.at(-1),c=Mct(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)(Rn,{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)(Kct,{item:l,active:e.active}):(0,t.jsxs)("span",{className:"flex h-8 min-w-0 flex-1 items-center gap-2 text-xs","data-completed-summary":!0,children:[(0,t.jsx)("span",{className:"flex size-5 shrink-0 items-center justify-center",children:(0,t.jsx)(d,{className:"size-3.5","aria-hidden":"true"})}),(0,t.jsx)("span",{className:"truncate",title:c.fullLabel,children:c.label})]}),(0,t.jsxs)("span",{className:"flex shrink-0 items-center gap-1 text-xs",children:[n?u:e.active?o.length:null,(0,t.jsx)(Pn,{className: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)(Hct,{item:h,active:e.active&&p===o.length-1},h.id))}):null]}):null]})}r(D_,"TaskChatRunnerActivityGroup");var Gct=new Set(["failed","timed_out","cancelled","interrupted","succeeded"]);function Yv(e){return e!=null&&Gct.has(e)}r(Yv,"isTerminalRunStatus$1");function Tse(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(Tse,"splitTranscriptAtAnchors");function Qct(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(Qct,"flattenSelfTalk");function Yct(e){return e==="add"?"add":e==="remove"?"remove":"context"}r(Yct,"diffKind");var Jct=["file_path","path","notebook_path","command","pattern","query","url","prompt","description","skill","subject"],qC=96;function w0(e,s){const n=e.replace(/\s+/g," ").trim();return n.length>s?`${n.slice(0,s-1)}…`:n}r(w0,"clip");function Xct(e){if(e==null)return;if(typeof e=="string")return e.trim()?w0(e,qC):void 0;if(typeof e!="object")return w0(String(e),qC);const s=e;for(const a of Jct){const i=s[a];if(typeof i=="string"&&i.trim())return w0(i,qC)}const n=Object.entries(s).filter(([a,i])=>(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&a!=="text"&&a!=="status");if(n.length!==0)return w0(n.map(([a,i])=>`${a}: ${String(i)}`).join(", "),qC)}r(Xct,"summarizeToolInput$2");function tO(e){const s=(e??"").trim();return Gd(s)?"Unnamed tool":pk(s)}r(tO,"toolDisplayName");function Zct(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(Zct,"thoughtDurationLabel");function edt(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(edt,"appendThinkingText");var Rse=600,C1=8192;function K2(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}r(K2,"objectRecord");function Dc(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}r(Dc,"stringValue");function tdt(e){if(typeof e=="string"&&e.trim())return e.trim();if(typeof e=="number"&&Number.isFinite(e))return String(e);if(typeof e=="boolean")return e?"Yes":"No"}r(tdt,"scalarValue");function sdt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("_"," ").replace(/\b\w/g,s=>s.toUpperCase())}r(sdt,"titleCaseKey$1");function ndt(e){const s=Dc(e);if(!s)return null;try{const n=new URL(s);return n.protocol==="http:"||n.protocol==="https:"?s:null}catch{return null}}r(ndt,"safeHttpHref");var rdt={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 ZCe(e){for(const s of["planId","executionId","researchId","delegationId","routeId","verificationId","compactionId","artifactId","reviewId","hookId","citationId","waitId","noticeId"]){const n=Dc(e.payload[s]);if(n)return`${e.family}:${n}`}return`${e.family}:${e.eventType}:${e.ts}`}r(ZCe,"providerActivityKey");function adt(e,s,n){const a=[];for(const h of rdt[e.family]){const p=tdt(e.payload[h]);p&&(e.family==="tool_execution"&&h==="name"&&Gd(p)||e.family==="tool_execution"&&h==="progress"&&!p6(p)||a.push({label:sdt(h),value:w0(p,e.family==="provider_notice"&&(h==="summary"||h==="message")?4e3:h==="message"||h==="summary"||h==="reason"?320:160),mono:/(?:id|model|target|reference|url|code|bytes)$/i.test(h)}))}if(e.family==="provider_notice"&&Array.isArray(e.payload.details))for(const h of e.payload.details.slice(0,64)){const p=K2(h);typeof p.name=="string"&&typeof p.value=="string"&&a.push({label:w0(p.name,160),value:w0(p.value,4e3),mono:!1})}const i=e.family==="plan"&&Array.isArray(e.payload.steps)?e.payload.steps.map(K2).slice(0,256).map((h,p)=>{const f=Dc(h.status),x=f==="in_progress"||f==="completed"||f==="blocked"?f:"pending";return{id:Dc(h.stepId)??`${s}:plan-step:${p}`,label:Dc(h.body)??"Plan step",status:x}}):[],o=e.family==="research"&&Array.isArray(e.payload.sources)?e.payload.sources.map(K2).slice(0,64).flatMap(h=>{const p=ndt(h.url);return p?[{label:Dc(h.title)??p,href:p,description:Dc(h.snippet)}]:[]}):[],l=e.family==="delegation"&&Array.isArray(e.payload.children)?e.payload.children.map(K2).slice(0,64).map((h,p)=>({id:Dc(h.childId)??`${s}:delegation:${p}`,title:Dc(h.role)??"Subagent",status:Dc(h.status)??"unknown",metadata:[Dc(h.model),Dc(h.activitySummary)].filter(Boolean).join(" · ")||void 0,summary:Dc(h.summary)})):[],c=e.family==="tool_execution"?Dc(e.payload.output):void 0,d=e.payload.outputTruncated===!0||!!(c&&c.length>C1),u=e.summary&&e.summary!==e.eventType?e.summary:Dc(e.payload.explanation)??Dc(e.payload.progress)??Dc(e.payload.message)??Dc(e.payload.summary);return{id:`${s}:provider:${ZCe(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,C1):void 0,outputTruncated:d,transcriptIndex:n}}r(adt,"providerActivityItem");function Kd(e,s){return e.details.find(n=>n.label===s)?.value}r(Kd,"providerItemDetail");function p6(e){return!!(e&&!Gd(e)&&!/^tool(?:\s+|_)call\b/i.test(e))}r(p6,"meaningfulProviderToolSummary");function idt(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"&&!p6(l.value)&&n.has("Progress")||n.set(l.label,l);return{...s,id:e.id,summary:p6(s.summary)?s.summary:e.summary,details:[...n.values()]}}r(idt,"mergeProviderActivityItem");function odt(e){if(e==null)return;const s=(typeof e=="string"?e:String(e)).trim();if(s)return s.length>Rse?`${s.slice(0,Rse)}
|
|
@@ -768,7 +768,7 @@ Last resolved: user values resolve per member`;return(0,t.jsxs)("div",{role:"row
|
|
|
768
768
|
|
|
769
769
|
Review the **original** file.`,markdown:!0,downloadUrl:"data:text/markdown,%23%20Project%20notes"}),(0,t.jsx)(PU,{title:"notes.txt",text:"Plain text stays literal: <example>",markdown:!1,downloadUrl:"data:text/plain,Plain%20text"})]})]}),(0,t.jsxs)(vr,{title:"Connection recovery",children:[(0,t.jsx)(Qn,{title:"Waiting for server",children:(0,t.jsx)(gE,{temporary:!0,retrying:!1,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(Qn,{title:"Checking connection",children:(0,t.jsx)(gE,{temporary:!0,retrying:!0,onRetry:r(()=>{},"onRetry")})}),(0,t.jsx)(Qn,{title:"Access check failed",children:(0,t.jsx)(gE,{temporary:!1,retrying:!1,onRetry:r(()=>{},"onRetry")})})]}),(0,t.jsxs)(vr,{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($=>(0,t.jsx)(Qn,{title:$==="closing-soon"?"Closing soon":$,children:(0,t.jsx)(BRe,{browser:{id:"design-browser",sessionId:"design-session",issueId:"design-task",status:$==="closing-soon"?"idle":$,runStatus:"completed",progress:null,error:null,costCents:15,idleDeadline:new Date($==="closing-soon"?282e3:6e5).toISOString(),expiresAt:null,createdAt:new Date(0).toISOString()},now:0,onControl:r(()=>{},"onControl"),onReconnect:r(()=>{},"onReconnect"),onResize:r(()=>{},"onResize")})},$))]}),(0,t.jsxs)(vr,{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($=>(0,t.jsx)(Qn,{title:$,children:(0,t.jsx)(wCe,{browser:{id:`design-${$}`,sessionId:`design-${$}`,issueId:"design-task",status:$,runStatus:"completed",progress:null,error:null,costCents:0,idleDeadline:null,expiresAt:null,createdAt:new Date(0).toISOString()},onOpen:r(()=>{},"onOpen")})},$))]}),(0,t.jsxs)(vr,{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)(v6,{id:"design-image",title:"Launch artwork",contentPath:"/announcement-preview.svg",contentType:"image/svg+xml",originalFilename:"launch.svg",detail:"Image"}),(0,t.jsx)(v6,{id:"design-video",title:"Video preview unavailable",contentPath:"",contentType:"video/mp4",originalFilename:"preview.mp4",detail:"Video"})]})]}),(0,t.jsx)(vr,{title:"AI Connections",children:(0,t.jsx)(ons,{})}),(0,t.jsxs)(vr,{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)(rk,{status:"needs_setup"}),(0,t.jsx)(rk,{status:"pending_approval"}),(0,t.jsx)(rk,{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(Hns,"DesignGuide");function Gns(){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)(aMe,{candidates:e,selected:s,excludedFolders:a,onChange:r((o,l)=>{n(o),i(l)},"onChange")})}r(Gns,"SkillSourceTreeShowcase");function Qns(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(Qns,"resolveWorktreeRunExecutionDisplayState");function Yns(e){const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}r(Yns,"formatActivationTimestamp");function XMe(){return(0,t.jsxs)(lt,{variant:"outline",className:"text-muted-foreground",children:[(0,t.jsx)(dd,{"aria-hidden":"true"}),"Managed by Paperclip Cloud"]})}r(XMe,"ManagedByCloudBadge");function ho({title:e,description:s,footnote:n,checked:a,onCheckedChange:i,disabled:o,settingKey:l,managed:c,ariaLabel:d}){const{hidden:u}=tu(),h=c?.managed===!0;return u.has(Ape(l))?null:(0,t.jsx)(sn,{className:"block bg-transparent p-5",children:(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:e}),h?(0,t.jsx)(XMe,{}):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)(ui,{checked:a,onCheckedChange:r(p=>{h||i(p)},"onCheckedChange"),disabled:o||h,"aria-label":d})]})})}r(ho,"ExperimentalToggleCard");function Jns(){const{setBreadcrumbs:e}=Fn(),s=Mt(),{hidden:n}=tu(),[a,i]=(0,m.useState)(null);(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Experimental"}])},[e]);const o=X({queryKey:P.instance.experimentalSettings,queryFn:r(()=>Or.getExperimental(),"queryFn")}),l=je({mutationFn:r(async H=>Or.updateExperimental(H),"mutationFn"),onMutate:r(async H=>{await s.cancelQueries({queryKey:P.instance.experimentalSettings});const Q=s.getQueryData(P.instance.experimentalSettings);return Q&&s.setQueryData(P.instance.experimentalSettings,{...Q,...H}),{previousSettings:Q}},"onMutate"),onSuccess:r(async H=>{i(null),s.setQueryData(P.instance.experimentalSettings,H),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((H,Q,Y)=>{Y?.previousSettings&&s.setQueryData(P.instance.experimentalSettings,Y.previousSettings),i(H instanceof Error?H.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=Rit(),d=o.data?.managedKeys??{},u=o.data?.enableWorktreeRunExecution===!0,h=d.enableWorktreeRunExecution?.managed===!0,p=Qns(o.data,Eit()),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,T=o.data?.enableBuiltInAgents===!0,R=o.data?.enableBetaSkills===!0,A=o.data?.enableSummaries===!0,D=o.data?.enableStatusCards===!0,M=d.enableSummaries?.managed===!0,$=d.enableStatusCards?.managed===!0,E=M&&!A,B=$&&D,z=o.data?.enableDecisions===!0,q=o.data?.enableGoalsSidebarLink===!0,U=o.data?.enableCases===!0,F=o.data?.enableServerInfoDebugView===!0,K=o.data?.enablePaperclipDeveloperMode===!0,G=o.data?.enableSimplifiedEnglishInteractions===!0,se=o.data?.enableFirstTaskPlanProposal===!0,ee=o.data?.enableSmokeLab===!0,ne=o.data?.autoRestartDevServerWhenIdle===!0,he=r(H=>!n.has(Ape(H)),"isVisible"),Z=c&&he("enableWorktreeRunExecution"),re=Z||["autoRestartDevServerWhenIdle","enableManagedSandboxOnly","enablePaperclipDeveloperMode","enableServerInfoDebugView","enableSmokeLab","enableIssuePlanDecompositions"].some(he),ce=he("enableClassicTaskInterface")||he("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)(Pm,{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)(Ds,{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)(ho,{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(H=>l.mutate({enableAgentChat:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableAgentChat",managed:d.enableAgentChat,ariaLabel:"Toggle agent chat experimental setting"}),(0,t.jsx)(ho,{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:R,onCheckedChange:r(H=>l.mutate({enableBetaSkills:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableBetaSkills",managed:d.enableBetaSkills,ariaLabel:"Toggle beta skills experimental setting"}),(0,t.jsx)(ho,{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:T,onCheckedChange:r(H=>l.mutate({enableBuiltInAgents:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableBuiltInAgents",managed:d.enableBuiltInAgents,ariaLabel:"Toggle built-in agents experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enableCases:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCases",managed:d.enableCases,ariaLabel:"Toggle cases experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enableChatConnectors:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableChatConnectors",managed:d.enableChatConnectors,ariaLabel:"Toggle chat connectors experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enableCombinedInboxTasks:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableCombinedInboxTasks",managed:d.enableCombinedInboxTasks,ariaLabel:"Toggle combined inbox and task list experimental setting"}),null,(0,t.jsx)(ho,{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:z,onCheckedChange:r(H=>l.mutate({enableDecisions:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableDecisions",managed:d.enableDecisions,ariaLabel:"Toggle decisions experimental setting"}),(0,t.jsx)(ho,{title:"Enable Environments",description:"Show environment management in company settings and allow project and agent environment assignment controls.",checked:f,onCheckedChange:r(H=>l.mutate({enableEnvironments:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableEnvironments",managed:d.enableEnvironments,ariaLabel:"Toggle environments experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enableExternalObjects:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableExternalObjects",managed:d.enableExternalObjects,ariaLabel:"Toggle external objects experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enableIsolatedWorkspaces:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIsolatedWorkspaces",managed:d.enableIsolatedWorkspaces,ariaLabel:"Toggle isolated workspaces experimental setting"}),(0,t.jsx)(ho,{title:"Experimental File Viewer",description:"Show task detail controls for browsing and previewing workspace files relative to a task.",checked:C,onCheckedChange:r(H=>l.mutate({enableExperimentalFileViewer:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableExperimentalFileViewer",managed:d.enableExperimentalFileViewer,ariaLabel:"Toggle experimental file viewer setting"}),(0,t.jsx)(ho,{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:se,onCheckedChange:r(H=>l.mutate({enableFirstTaskPlanProposal:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableFirstTaskPlanProposal",managed:d.enableFirstTaskPlanProposal,ariaLabel:"Toggle first task plan proposal experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enableMemoryConnectors:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableMemoryConnectors",managed:d.enableMemoryConnectors,ariaLabel:"Toggle memory connectors experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enableNativeRunner:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableNativeRunner",managed:d.enableNativeRunner,ariaLabel:"Toggle Paperclip Runner experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enablePixelsOffice:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePixelsOffice",managed:d.enablePixelsOffice,ariaLabel:"Toggle Pixels Office experimental setting"}),(0,t.jsx)(ho,{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:G,onCheckedChange:r(H=>l.mutate({enableSimplifiedEnglishInteractions:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableSimplifiedEnglishInteractions",managed:d.enableSimplifiedEnglishInteractions,ariaLabel:"Toggle simplified english interactions experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate(H?{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)(ho,{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(H=>l.mutate({enableStreamlinedUi:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableStreamlinedUi",managed:d.enableStreamlinedUi,ariaLabel:"Toggle Streamlined UI experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate(H||!D?{enableSummaries:H}:{enableSummaries:!1,enableStatusCards:!1}),"onCheckedChange"),disabled:l.isPending||B,settingKey:"enableSummaries",managed:d.enableSummaries,ariaLabel:"Toggle summaries experimental setting"}),j&&(0,t.jsx)(ho,{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(H=>l.mutate({enableIsolatedWorkspacesByDefault:H}),"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)(ho,{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(H=>l.mutate({autoRestartDevServerWhenIdle:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"autoRestartDevServerWhenIdle",managed:d.autoRestartDevServerWhenIdle,ariaLabel:"Toggle guarded dev-server auto-restart"}),(0,t.jsx)(ho,{title:"Managed Environment Only",description:"Hide the local environment and run all agents in the platform-managed environment.",checked:v,onCheckedChange:r(H=>l.mutate({enableManagedSandboxOnly:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableManagedSandboxOnly",managed:d.enableManagedSandboxOnly,ariaLabel:"Toggle managed environment only experimental setting"}),(0,t.jsx)(ho,{title:"Paperclip Developer Mode",description:"Show internal Paperclip maintainer tools and observability links, including Honeycomb trace queries on run pages.",checked:K,onCheckedChange:r(H=>l.mutate({enablePaperclipDeveloperMode:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enablePaperclipDeveloperMode",managed:d.enablePaperclipDeveloperMode,ariaLabel:"Toggle Paperclip developer mode experimental setting"}),Z?(0,t.jsx)(sn,{className:"block bg-transparent p-5",children:(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)("h3",{className:"text-sm font-semibold",children:"Run tasks in this worktree"}),h?(0,t.jsx)(XMe,{}):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)(ui,{checked:u,onCheckedChange:r(H=>{h||l.mutate({enableWorktreeRunExecution:H})},"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)(so,{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:Yns(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)(Ds,{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)(ho,{title:"Server Info Debug View",description:'Show a "Server" section in the account drawer with the current server restart time and running commit.',checked:F,onCheckedChange:r(H=>l.mutate({enableServerInfoDebugView:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableServerInfoDebugView",managed:d.enableServerInfoDebugView,ariaLabel:"Toggle server info debug view experimental setting"}),(0,t.jsx)(ho,{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:ee,onCheckedChange:r(H=>l.mutate({enableSmokeLab:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableSmokeLab",managed:d.enableSmokeLab,ariaLabel:"Toggle smoke lab experimental setting"}),(0,t.jsx)(ho,{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(H=>l.mutate({enableIssuePlanDecompositions:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableIssuePlanDecompositions",managed:d.enableIssuePlanDecompositions,ariaLabel:"Toggle task plan decomposition panel experimental setting"})]}):null,ce?(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)(ho,{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(H=>l.mutate({enableClassicTaskInterface:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableClassicTaskInterface",managed:d.enableClassicTaskInterface,ariaLabel:"Toggle classic task interface experimental setting"}),(0,t.jsx)(ho,{title:"Goals Sidebar Link",description:"Restore the Goals item in the main sidebar while the goals surface is being evaluated.",checked:q,onCheckedChange:r(H=>l.mutate({enableGoalsSidebarLink:H}),"onCheckedChange"),disabled:l.isPending,settingKey:"enableGoalsSidebarLink",managed:d.enableGoalsSidebarLink,ariaLabel:"Toggle goals sidebar link experimental setting"})]}):null]})}r(Jns,"InstanceExperimentalSettings");function Xns(){const{userId:e,settled:s}=Qf(),{setBreadcrumbs:n}=Fn(),{pushToast:a}=pi(),i=Mt(),[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=X({queryKey:P.access.adminUsers(o),queryFn:r(()=>hr.searchAdminUsers(o),"queryFn")}),f=X({...$De(e),enabled:s&&p.isSuccess}),x=f.data??[],b=(0,m.useMemo)(()=>p.data?.find(w=>w.id===c)??null,[c,p.data]),v=X({queryKey:P.access.userCompanyAccess(c??""),queryFn:r(()=>hr.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(()=>hr.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?hr.promoteInstanceAdmin(c):hr.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 un&&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)(jI,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Instance Access"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Search users, manage instance-admin status, and control which organizations they can access."})]}),(0,t.jsxs)("div",{className:"grid gap-6 lg:grid-cols-(--gtc-34)",children:[(0,t.jsxs)(sn,{className:"block space-y-4 p-4",children:[(0,t.jsxs)("label",{className:"block space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Search users"}),(0,t.jsx)("input",{className:"w-full rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(w=>l(w.target.value),"onChange"),placeholder:"Search by name or email"})]}),(0,t.jsx)("div",{className:"space-y-2",children:(p.data??[]).map(w=>(0,t.jsxs)("button",{type:"button",onClick:r(()=>d(w.id),"onClick"),className:`w-full rounded-lg border px-3 py-3 text-left transition-colors ${w.id===c?"border-foreground bg-accent":"border-border hover:bg-accent/40"}`,children:[(0,t.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"truncate font-medium",children:w.name||w.email||w.id}),(0,t.jsx)("div",{className:"truncate text-sm text-muted-foreground",children:w.email||w.id})]}),w.isInstanceAdmin?(0,t.jsx)(Li,{className:"h-4 w-4 text-emerald-600"}):null]}),(0,t.jsxs)("div",{className:"mt-2 text-xs text-muted-foreground",children:[w.activeCompanyMembershipCount," active organization memberships"]})]},w.id))})]}),(0,t.jsx)(sn,{className:"block space-y-4 p-5",children:c?v.isLoading?(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:"Loading user access…"}):v.error?(0,t.jsx)("div",{className:"text-sm text-destructive",children:v.error instanceof Error?v.error.message:"Failed to load user access."}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-lg font-semibold",children:b?.name||b?.email||c}),(0,t.jsx)("div",{className:"text-sm text-muted-foreground",children:b?.email||c})]}),(0,t.jsx)(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)(mi,{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(Xns,"InstanceAccess");var Phe={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")},Zns=[{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 PR(e,s){return`${e}:${[...s].sort().join(",")}`}r(PR,"policyKey");function ers({companyId:e}){const s=Mt(),[n,a]=(0,m.useState)(null),i=(0,m.useRef)(null),o=X({queryKey:e?P.inboxAgentPolicy.mine(e):["inbox-agent-policy","none"],queryFn:r(()=>Phe.getMine(e),"queryFn"),enabled:!!e}),l=o.data,c=X({queryKey:e?P.agents.list(e):["agents","none"],queryFn:r(()=>Lt.list(e),"queryFn"),enabled:!!e}),d=(0,m.useMemo)(()=>(c.data??[]).filter(Of),[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=PR(l.mode,l.allowedAgentIds);a(b=>b===null||PR(b.mode,b.allowedAgentIds)===i.current?{mode:l.mode,allowedAgentIds:l.allowedAgentIds}:b),i.current=x},[l]);const p=je({mutationFn:r(x=>Phe.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&&PR(n.mode,n.allowedAgentIds)!==PR(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)(cd,{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)(mm,{ariaLabel:"Inbox agent archiving policy",value:n.mode,onValueChange:r(x=>a(b=>b&&{...b,mode:x}),"onValueChange"),options:Zns,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)(Yy,{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)(nt,{className:"size-4 animate-spin"}):(0,t.jsx)(If,{className:"size-4"}),p.isPending?"Saving…":"Save"]})]})]})}r(ers,"InboxAgentPolicyControl");var trs={granted:"Allowed",denied:"Blocked in browser settings",default:"Not requested yet",unsupported:"Not supported in this browser"},Mhe={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 srs(){const[e,s]=(0,m.useState)({});return(0,m.useEffect)(()=>{let n=!1;const a=r(()=>{Promise.all(vI.map(async o=>[o,(await fTe(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=hTe(a);return()=>{n=!0,i()}},[]),e}r(srs,"useCustomSoundNames");function nrs({kind:e,customName:s,disabled:n,onError:a}){const i=CTe(),o=i.kinds[e],l=(0,m.useId)(),[c,d]=(0,m.useState)(!1),u=JIt[e];async function h(x){const b=uTe(x);if(!b.ok){a(`${u}: ${b.error}`);return}d(!0);try{await GIt(e,x),AT(e,{soundId:Jae}),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 QIt(e),gg().kinds[e].soundId==="custom"&&AT(e,{soundId:oP[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)(ui,{checked:o.enabled,onCheckedChange:r(x=>AT(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)(Da,{value:o.soundId,onValueChange:r(x=>AT(e,{soundId:x}),"onValueChange"),disabled:f,children:[(0,t.jsx)(Ma,{className:"min-w-0 flex-1 sm:w-(--sz-170px) sm:flex-none","aria-label":`${u} sound`,children:(0,t.jsx)(Ea,{})}),(0,t.jsxs)(Pa,{children:[xTe.map(x=>(0,t.jsx)(Sn,{value:x.id,children:x.label},x.id)),s?(0,t.jsxs)(Sn,{value:Jae,children:["Custom: ",s]}):null,(0,t.jsx)(Sn,{value:YIt,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)(so,{})}),(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)(nt,{className:"animate-spin"}):(0,t.jsx)(hy,{}),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)(ua,{})}):null]})]})}r(nrs,"KindRow");function rrs({userId:e}){const s=CTe(),n=lAt(),a=srs(),[i,o]=(0,m.useState)(()=>L1()),[l,c]=(0,m.useState)(null),[d,u]=(0,m.useState)(null),[h,p]=(0,m.useState)(!1),f=lTe(),x=n.status==="active",b=(0,m.useCallback)(()=>{e&&CU(gg(),e)},[e]);async function v(){const S=await LIt();return o(S),S==="granted"&&b(),S}r(v,"askPermission");async function j(S){CE(C=>({...C,enabled:S})),S&&L1()==="default"&&await v()}r(j,"setEnabled");async function N(S){CE(C=>({...C,pushEnabled:S})),S&&L1()==="default"&&await v()}r(N,"setPushEnabled");async function w(){p(!0),c(null),u(null);try{const S=await cP.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)(ZBe,{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)(ui,{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:trs[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?Mhe[n.status]:Mhe.unsupported,n.error?`: ${n.error}`:""]})]}),(0,t.jsx)(ui,{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,$It()?(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=>CE(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:vI.map(S=>(0,t.jsx)(nrs,{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)(nt,{className:"animate-spin"}):(0,t.jsx)(FI,{}),"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(rrs,"NotificationSettingsSection");function ars(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(ars,"deriveInitials");function irs(){const{setBreadcrumbs:e}=Fn(),{selectedCompanyId:s,selectedCompany:n}=gs(),a=Mt(),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=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{e([{label:"Settings",href:"/company/settings"},{label:"Profile"}])},[e]),(0,m.useEffect)(()=>{const R=f.data;R&&(c(R.user.name??""),u(R.user.image??""))},[f.data]);function x(R){a.setQueryData(P.auth.session,A=>A&&{...A,user:{...A.user,...R}})}r(x,"syncSessionProfile");async function b(R){const A=await La.updateProfile(R);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(R=>b(R),"mutationFn"),onSuccess:r(R=>{p(null),c(R.name??""),u(R.image??"")},"onSuccess"),onError:r(R=>{p(R instanceof Error?R.message:"Failed to update profile.")},"onError")}),N=je({mutationFn:r(async R=>{if(!s)throw new Error("Select an organization before uploading a profile avatar.");const A=await fb.uploadImage(s,R,`profiles/${f.data?.user.id??"board-user"}`);return b({name:v(),image:A.contentPath})},"mutationFn"),onSuccess:r(R=>{p(null),c(R.name??""),u(R.image??"")},"onSuccess"),onError:r(R=>{p(R instanceof Error?R.message:"Failed to upload avatar.")},"onError")}),w=je({mutationFn:r(()=>b({name:v(),image:null}),"mutationFn"),onSuccess:r(R=>{p(null),c(R.name??""),u(R.image??"")},"onSuccess"),onError:r(R=>{p(R instanceof Error?R.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=ars(k),I=j.isPending||N.isPending||w.isPending,T=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)(yM,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Profile"})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Control how your account appears in the sidebar and other board surfaces."})]}),h?(0,t.jsx)("div",{className:"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive",children:h}):null,(0,t.jsxs)("section",{className:"space-y-8",children:[(0,t.jsxs)(sn,{className:"block relative overflow-hidden rounded-(--rad-28) border-border/70",children:[(0,t.jsx)("div",{className:"absolute inset-x-0 top-0 h-32 bg-(image:--gradient-extract-26)"}),(0,t.jsx)("div",{className:"absolute inset-0 bg-(image:--gradient-extract-7)"}),(0,t.jsx)("div",{className:"relative p-6 pt-10",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-end gap-5 rounded-(--rad-24) border border-border/70 bg-background/92 p-5 shadow-(--shadow-extract-18) backdrop-blur-sm",children:[(0,t.jsxs)("div",{className:"space-y-3",children:[(0,t.jsxs)("label",{htmlFor:i,className:"group relative block cursor-pointer rounded-full focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background",children:[(0,t.jsx)("input",{ref:o,id:i,type:"file",accept:"image/*",className:"sr-only",disabled:!s||I,onChange:r(R=>{const A=R.target.files?.[0];A&&(N.mutate(A),R.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)(nt,{className:"size-4 animate-spin"}):(0,t.jsx)(qJ,{className:"size-4"})}),(0,t.jsxs)(So,{size:"lg",className:"data-[size=lg]:size-24 ring-4 ring-background shadow-xl",children:[S?(0,t.jsx)(md,{src:S,alt:k}):null,(0,t.jsx)(Co,{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)(nt,{className:"size-4 animate-spin"}):(0,t.jsx)(qJ,{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)(nt,{className:"size-4 animate-spin"}):(0,t.jsx)(ua,{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. ",T]})]})]})})]}),(0,t.jsxs)("form",{className:"grid gap-6 md:grid-cols-2",onSubmit:r(R=>{R.preventDefault(),j.mutate({name:v(),image:d.trim()||null})},"onSubmit"),children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsx)(Ws,{htmlFor:"profile-name",children:"Display name"}),(0,t.jsx)(pt,{id:"profile-name",value:l,onChange:r(R=>c(R.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)(Ws,{htmlFor:"profile-email",children:"Email"}),(0,t.jsx)(pt,{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)(nt,{className:"size-4 animate-spin"}):(0,t.jsx)(If,{className:"size-4"}),j.isPending?"Saving...":"Save profile"]})})]}),(0,t.jsx)(ers,{companyId:s}),(0,t.jsx)(rrs,{userId:f.data.user.id??null})]})]})}r(irs,"ProfileSettings");function ors(e){return e?e.split(/\r?\n/).map(s=>s.trim()).find(Boolean)??null:null}r(ors,"firstNonEmptyLine");function Dhe(e){return ors(e.lastError)??"Plugin entered an error state without a stored error message."}r(Dhe,"getPluginErrorSummary");function Lhe(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(Lhe,"isExperimentalPluginIdentity");function $he(){return(0,t.jsx)(lt,{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($he,"ExperimentalBadge");function lrs(){const{selectedCompany:e}=gs(),{setBreadcrumbs:s}=Fn(),n=Mt(),{pushToast:a}=pa(),[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}=X({queryKey:P.plugins.all,queryFn:r(()=>xl.list(),"queryFn")}),N=X({queryKey:P.plugins.examples,queryFn:r(()=>xl.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=>xl.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=>xl.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=>xl.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=>xl.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")}),T=b??[],R=N.data??[],A=new Map(T.map(E=>[E.packageName,E])),D=new Map(R.map(E=>[E.packageName,E])),M=k.variables?.isLocalPath?k.error?.message??null:null,$=(0,m.useMemo)(()=>new Map(T.map(E=>[E.id,Dhe(E)])),[T]);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)(Jx,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Plugin Manager"})]}),(0,t.jsxs)(Vs,{open:l,onOpenChange:c,children:[(0,t.jsx)(qy,{asChild:!0,children:(0,t.jsxs)(L,{size:"sm",className:"gap-2",children:[(0,t.jsx)(bn,{className:"h-4 w-4"}),"Install Plugin"]})}),(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Install Plugin"}),(0,t.jsx)(yn,{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)(Ws,{htmlFor:"packageName",children:"npm Package Name"}),(0,t.jsx)(pt,{id:"packageName",placeholder:"@tickernelz/paperclip-pro-plugin-example",value:i,onChange:r(E=>o(E.target.value),"onChange")})]})}),(0,t.jsxs)(mr,{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)(Ds,{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)(Pm,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Available Plugins"}),(0,t.jsx)(lt,{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."}):R.length===0?(0,t.jsx)("div",{className:"rounded-md border border-dashed px-4 py-3 text-sm text-muted-foreground",children:"No bundled plugins were found in this checkout."}):(0,t.jsx)(sn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:R.map(E=>{const B=A.get(E.packageName),z=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)(lt,{variant:"outline",children:E.tag==="first-party"?"First-party":"Example"}),Lhe({packageName:E.packageName,packagePath:E.localPath,bundledExperimental:E.experimental})&&(0,t.jsx)($he,{}),B?(0,t.jsx)(lt,{variant:B.status==="ready"?"default":"secondary",className:B.status==="ready"?"bg-green-600 hover:bg-green-700":"",children:B.status}):(0,t.jsx)(lt,{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}),z&&!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:B?(0,t.jsxs)(t.Fragment,{children:[B.status!=="ready"&&(0,t.jsx)(L,{variant:"outline",size:"sm",disabled:C.isPending,onClick:r(()=>C.mutate(B.id),"onClick"),children:"Enable"}),(0,t.jsx)(L,{variant:"outline",size:"sm",asChild:!0,children:(0,t.jsx)(We,{to:`/company/settings/instance/plugins/${B.id}`,children:B.status==="ready"?"Open Settings":"Review"})})]}):(0,t.jsx)(L,{size:"sm",disabled:z||k.isPending,onClick:r(()=>k.mutate({packageName:E.localPath,isLocalPath:!0}),"onClick"),children:z?"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)(Jx,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Installed Plugins"})]}),T.length?(0,t.jsx)(sn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:T.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)(We,{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)(lt,{variant:"outline",children:D.get(E.packageName)?.tag==="first-party"?"First-party":"Example"}),Lhe({packageName:E.packageName,packagePath:E.packagePath,manifestJson:E.manifestJson,bundledExperimental:D.get(E.packageName)?.experimental})&&(0,t.jsx)($he,{})]}),(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)(Ds,{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:$.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)(lt,{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)(j7,{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)(ua,{className:"h-4 w-4"})})]}),(0,t.jsx)(L,{variant:"outline",size:"sm",className:"mt-2 h-8",asChild:!0,children:(0,t.jsxs)(We,{to:`/company/settings/instance/plugins/${E.id}`,children:[(0,t.jsx)(Xd,{className:"h-4 w-4"}),"Configure"]})})]})})]})},E.id))})}):(0,t.jsx)(sn,{className:"bg-muted/30",children:(0,t.jsxs)(Qa,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(Jx,{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)(Vs,{open:d!==null,onOpenChange:r(E=>{E||u(null)},"onOpenChange"),children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Uninstall Plugin"}),(0,t.jsxs)(yn,{children:["Are you sure you want to uninstall ",(0,t.jsx)("strong",{children:h}),"? This action cannot be undone."]})]}),(0,t.jsxs)(mr,{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)(Vs,{open:f!==null,onOpenChange:r(E=>{E||x(null)},"onOpenChange"),children:(0,t.jsxs)(Qs,{className:"sm:max-w-2xl",children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Error Details"}),(0,t.jsxs)(yn,{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)(Ds,{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?Dhe(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)(mr,{children:(0,t.jsx)(L,{variant:"outline",onClick:r(()=>x(null),"onClick"),children:"Close"})})]})})]})}r(lrs,"PluginManager");function crs(){const{selectedCompany:e,selectedCompanyId:s}=gs(),{setBreadcrumbs:n}=Fn(),{companyPrefix:a,pluginId:i}=ga(),{hideHostPaths:o}=cA(),[l,c]=(0,m.useState)("configuration"),{data:d,isLoading:u}=X({queryKey:P.plugins.detail(i),queryFn:r(()=>xl.get(i),"queryFn"),enabled:!!i}),{data:h,isLoading:p}=X({queryKey:P.plugins.health(i),queryFn:r(()=>xl.health(i),"queryFn"),enabled:!!i&&d?.status==="ready",refetchInterval:3e4}),{data:f}=X({queryKey:P.plugins.dashboard(i),queryFn:r(()=>xl.dashboard(i),"queryFn"),enabled:!!i,refetchInterval:3e4}),{data:x}=X({queryKey:P.plugins.logs(i),queryFn:r(()=>xl.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}=X({queryKey:j,queryFn:r(()=>xl.getConfig(i,s),"queryFn"),enabled:!!i&&!!v&&!!s}),{slots:k}=hd({slotTypes:["settingsPage"],companyId:s,enabled:!!s}),S=k.filter(B=>B.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)(Nn,{to:"/company/settings/instance/plugins",replace:!0});const I=d.status,T=d.status==="ready"?"default":d.status==="error"?"destructive":"secondary",R=d.manifestJson.description||"No description provided.",A=d.manifestJson.capabilities??[],D=d.manifestJson.environmentDrivers??[],M=d.manifestJson.localFolders??[],$=M.length>0&&!o,E=D.map(B=>B.displayName?.trim()||B.driverKey).filter((B,z,q)=>q.indexOf(B)===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)(We,{to:"/company/settings/instance/plugins",children:(0,t.jsx)(L,{variant:"outline",size:"icon",className:"h-8 w-8",children:(0,t.jsx)(gl,{className:"h-4 w-4"})})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(Jx,{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)(lt,{variant:T,className:"ml-2",children:I}),(0,t.jsxs)(lt,{variant:"outline",className:"ml-1",children:["v",d.manifestJson.version??d.version]})]})]}),(0,t.jsxs)(Ii,{value:l,onValueChange:r(B=>c(B),"onValueChange"),className:"space-y-6",children:[(0,t.jsx)(_c,{align:"start",items:[{value:"configuration",label:"Configuration"},{value:"status",label:"Status"}],value:l,onValueChange:r(B=>c(B),"onValueChange")}),(0,t.jsx)(xa,{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:R})]}),(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(B=>(0,t.jsx)(lt,{variant:"outline",className:"capitalize",children:B},B)):(0,t.jsx)("span",{className:"text-foreground",children:"None"})})]})]})]})]}),(0,t.jsx)(Al,{}),(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"})}),$?(0,t.jsx)(drs,{pluginId:i,companyId:s,declarations:M}):null,C?(0,t.jsx)("div",{className:"space-y-3",children:S.map(B=>(0,t.jsx)(Lu,{slot:B,context:{companyId:s,companyPrefix:a??null},missingBehavior:"placeholder"},`${B.pluginKey}:${B.id}`))}):v?(0,t.jsx)(frs,{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)(We,{to:"/company/settings/instance/environments",children:(0,t.jsx)(L,{variant:"outline",size:"sm",children:"Open Environments"})})})]}):$?null:(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"This plugin does not require any settings."})]})]})}),(0,t.jsx)(xa,{value:"status",className:"space-y-6",children:(0,t.jsxs)("div",{className:"grid gap-6 xl:grid-cols-(--gtc-39)",children:[(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(sn,{children:[(0,t.jsxs)(Xi,{children:[(0,t.jsxs)(go,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(dm,{className:"h-4 w-4"}),"Runtime Dashboard"]}),(0,t.jsx)(Il,{children:"Worker process, scheduled jobs, and webhook deliveries"})]}),(0,t.jsx)(Qa,{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)(dm,{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)(lt,{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:xrs(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)(Ds,{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:grs(f.worker.lastCrashAt)})]})]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No worker process registered."})]}),(0,t.jsx)(Al,{}),(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)(G0,{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(B=>(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)(brs,{status:B.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:B.jobKey??B.jobId,children:B.jobKey??B.jobId.slice(0,8)}),(0,t.jsx)(lt,{variant:"outline",className:"px-1 py-0 text-(length:--text-nano)",children:B.trigger})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[B.durationMs!=null?(0,t.jsx)("span",{children:Fhe(B.durationMs)}):null,(0,t.jsx)("span",{title:B.createdAt,children:Bhe(B.createdAt)})]})]},B.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No job runs recorded yet."})]}),(0,t.jsx)(Al,{}),(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)(I7,{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(B=>(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)(vrs,{status:B.status}),(0,t.jsx)("span",{className:"truncate font-mono text-xs",title:B.webhookKey,children:B.webhookKey})]}),(0,t.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-muted-foreground",children:[B.durationMs!=null?(0,t.jsx)("span",{children:Fhe(B.durationMs)}):null,(0,t.jsx)("span",{title:B.createdAt,children:Bhe(B.createdAt)})]})]},B.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No webhook deliveries recorded yet."})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1.5 border-t border-border/50 pt-2 text-xs text-muted-foreground",children:[(0,t.jsx)(io,{className:"h-3 w-3"}),"Last checked: ",new Date(f.checkedAt).toLocaleTimeString()]})]}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"Runtime diagnostics are unavailable right now."})})]}),x&&x.length>0?(0,t.jsxs)(sn,{children:[(0,t.jsxs)(Xi,{children:[(0,t.jsxs)(go,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(WJ,{className:"h-4 w-4"}),"Recent Logs"]}),(0,t.jsxs)(Il,{children:["Last ",x.length," log entries"]})]}),(0,t.jsx)(Qa,{children:(0,t.jsx)("div",{className:"max-h-64 space-y-1 overflow-y-auto font-mono text-xs",children:x.map(B=>(0,t.jsxs)("div",{className:`flex gap-2 py-0.5 ${B.level==="error"?"text-destructive":B.level==="warn"?"text-yellow-600 dark:text-yellow-400":B.level==="debug"?"text-muted-foreground/60":"text-muted-foreground"}`,children:[(0,t.jsx)("span",{className:"shrink-0 text-muted-foreground/50",children:new Date(B.createdAt).toLocaleTimeString()}),(0,t.jsx)(lt,{variant:"outline",className:"h-4 shrink-0 px-1 text-(length:--text-nano)",children:B.level}),(0,t.jsx)("span",{className:"truncate",title:B.message,children:B.message})]},B.id))})})]}):null]}),(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)(sn,{children:[(0,t.jsx)(Xi,{children:(0,t.jsxs)(go,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(WJ,{className:"h-4 w-4"}),"Health Status"]})}),(0,t.jsx)(Qa,{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)(lt,{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((B,z)=>(0,t.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,t.jsx)("span",{className:"truncate text-muted-foreground",title:B.name,children:B.name}),B.passed?(0,t.jsx)(aze,{className:"h-4 w-4 shrink-0 text-green-500"}):(0,t.jsx)(Cc,{className:"h-4 w-4 shrink-0 text-destructive"})]},z))}):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)(lt,{variant:T,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)(sn,{children:[(0,t.jsx)(Xi,{children:(0,t.jsx)(go,{className:"text-base",children:"Details"})}),(0,t.jsxs)(Qa,{className:"space-y-3 text-sm text-muted-foreground",children:[(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Plugin ID"}),(0,t.jsx)("span",{className:"font-mono text-xs text-right",children:d.id})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Plugin Key"}),(0,t.jsx)("span",{className:"font-mono text-xs text-right",children:d.pluginKey})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"NPM Package"}),(0,t.jsx)("span",{className:"max-w-(--sz-170px) truncate text-right text-xs",title:d.packageName,children:d.packageName})]}),(0,t.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,t.jsx)("span",{children:"Version"}),(0,t.jsxs)("span",{className:"text-right text-foreground",children:["v",d.manifestJson.version??d.version]})]})]})]}),(0,t.jsxs)(sn,{children:[(0,t.jsx)(Xi,{children:(0,t.jsxs)(go,{className:"text-base flex items-center gap-1.5",children:[(0,t.jsx)(hc,{className:"h-4 w-4"}),"Permissions"]})}),(0,t.jsx)(Qa,{children:A.length>0?(0,t.jsx)("ul",{className:"space-y-2 text-sm text-muted-foreground",children:A.map(B=>(0,t.jsx)("li",{className:"rounded-md bg-muted/40 px-2.5 py-2 font-mono text-xs text-foreground/85",children:B},B))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground italic",children:"No special permissions requested."})})]})]})]})})]})]})}r(crs,"PluginSettings");function drs({pluginId:e,companyId:s,declarations:n}){const{data:a,isLoading:i,error:o}=X({queryKey:s?P.plugins.localFolders(e,s):["plugins",e,"companies","none","local-folders"],queryFn:r(()=>xl.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)(Po,{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)(nt,{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)(urs,{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(drs,"PluginLocalFoldersSettings");function urs({pluginId:e,companyId:s,declaration:n,status:a}){const i=Mt(),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=>xl.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(!prs(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)(lt,{variant:"outline",className:"font-mono text-(length:--text-nano)",children:n.folderKey}),(0,t.jsx)(lt,{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)(lt,{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)(az,{label:"Configured",value:a?.configured?"Yes":"No",ok:!!a?.configured}),(0,t.jsx)(az,{label:"Readable",value:a?.readable?"Yes":"No",ok:!!a?.readable}),(0,t.jsx)(az,{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)(nt,{className:"h-3.5 w-3.5 animate-spin"}):(0,t.jsx)(If,{className:"h-3.5 w-3.5"}),"Save"]})]})]}),(0,t.jsx)(mrs,{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(urs,"PluginLocalFolderRow");function az({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)(lt,{variant:n?"default":"secondary",children:s})]})}r(az,"FolderStatusMetric");function mrs({status:e,declaration:s}){const n=e?.requiredDirectories??s.requiredDirectories??[],a=e?.requiredFiles??s.requiredFiles??[],i=e?.missingDirectories??n,o=e?.missingFiles??a,l=hrs(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)(Ohe,{title:"Required directories",items:n,missingItems:i,missingLabel:"Missing directories",inspectionUnavailable:l}),(0,t.jsx)(Ohe,{title:"Required files",items:a,missingItems:o,missingLabel:"Missing files",inspectionUnavailable:l})]})}r(mrs,"FolderRequirements");function hrs(e){return!e?.configured||e.readable?!1:e.problems.some(s=>s.code==="missing"||s.code==="not_readable"||s.code==="not_directory")}r(hrs,"isRootNotInspected");function Ohe({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)(lt,{variant:"secondary",className:"text-(length:--text-nano)",children:"Not inspected"}):n.length>0?(0,t.jsxs)(lt,{variant:"destructive",className:"text-(length:--text-nano)",children:[n.length," missing"]}):(0,t.jsx)(lt,{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(Ohe,"RequirementList");function prs(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}r(prs,"isLikelyAbsolutePath");function frs({pluginId:e,companyId:s,schema:n,initialValues:a,isLoading:i,pluginStatus:o,supportsConfigTest:l}){const c=Mt(),[d,u]=(0,m.useState)(()=>({...jf(n),...a??{}})),h=(0,m.useRef)(!1);(0,m.useEffect)(()=>{h.current=!1,u(jf(n))},[s,e,n]),(0,m.useEffect)(()=>{a&&!h.current&&(h.current=!0,u({...jf(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({...jf(n),...a??{}}),w=je({mutationFn:r(T=>{if(!s)throw new Error("Select an organization before saving plugin configuration.");return xl.saveConfig(e,s,T)},"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(T=>{b({type:"error",text:T.message||"Failed to save configuration."})},"onError")}),k=je({mutationFn:r(T=>{if(!s)throw new Error("Select an organization before testing plugin configuration.");return xl.testConfig(e,s,T)},"mutationFn"),onSuccess:r(T=>{T.valid?j({type:"success",text:"Configuration test passed."}):j({type:"error",text:T.message||"Configuration test failed."})},"onSuccess"),onError:r(T=>{j({type:"error",text:T.message||"Configuration test failed."})},"onError")}),S=(0,m.useCallback)(T=>{u(T),f({}),b(null)},[]),C=(0,m.useCallback)(()=>{const T=gy(n,d);if(Object.keys(T).length>0){f(T);return}f({}),w.mutate(d)},[n,d,w]),I=(0,m.useCallback)(()=>{const T=gy(n,d);if(Object.keys(T).length>0){f(T);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)(nt,{className:"h-4 w-4 animate-spin"}),"Loading configuration..."]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(YI,{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)(nt,{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)(nt,{className:"h-3.5 w-3.5 animate-spin"}),"Testing..."]}):"Test Configuration"})]})]})}r(frs,"PluginConfigForm");function xrs(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(xrs,"formatUptime");function Fhe(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${(e/6e4).toFixed(1)}m`}r(Fhe,"formatDuration");function Bhe(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(Bhe,"formatRelativeTime");function grs(e){return new Date(e).toLocaleString()}r(grs,"formatTimestamp");function brs({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(brs,"JobStatusDot");function vrs({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(vrs,"DeliveryStatusDot");function iz({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:qf(e.type)}),(0,t.jsx)(lt,{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)(Po,{className:"h-4 w-4 text-amber-500"})}):(0,t.jsx)("span",{title:"Installed from npm",children:(0,t.jsx)(Ih,{className:"h-4 w-4 text-red-500"})})),e.version&&(0,t.jsxs)(lt,{variant:"secondary",className:"font-mono text-(length:--text-nano)",children:["v",e.version]}),e.overriddenBuiltin&&(0,t.jsx)(lt,{variant:"secondary",className:"text-blue-600 border-blue-400",children:"Overrides built-in"}),u&&(0,t.jsxs)(lt,{variant:"secondary",className:"text-blue-600 border-blue-400",children:["Overridden by ",u]}),e.disabled&&(0,t.jsx)(lt,{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)(oo,{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)(Si,{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)(j7,{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)(ua,{className:"h-4 w-4"})})]})]})})}r(iz,"AdapterRow");function yrs(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(yrs,"fetchNpmLatestVersion");function jrs({adapter:e,open:s,isReinstalling:n,onConfirm:a,onCancel:i}){const{data:o,isLoading:l}=X({queryKey:["npm-latest-version",e?.packageName],queryFn:r(()=>e?.packageName?yrs(e.packageName):null,"queryFn"),enabled:s&&!!e?.packageName,staleTime:6e4}),c=e?.version&&o&&e.version===o;return(0,t.jsx)(Vs,{open:s,onOpenChange:r(d=>{d||i()},"onOpenChange"),children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Reinstall Adapter"}),(0,t.jsxs)(yn,{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)(mr,{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(jrs,"ReinstallDialog");function zhe(){const{selectedCompany:e}=gs(),{setBreadcrumbs:s}=Fn(),n=Mt(),{pushToast:a}=pa(),[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}=X({queryKey:P.adapters.all,queryFn:r(()=>ch.list(),"queryFn")}),w=r(()=>{n.invalidateQueries({queryKey:P.adapters.all})},"invalidate"),k=je({mutationFn:r(E=>ch.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=>ch.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:B})=>ch.setDisabled(E,B),"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:B})=>ch.setOverridePaused(E,B),"mutationFn"),onSuccess:r(()=>{w()},"onSuccess"),onError:r(E=>{a({title:"Override toggle failed",body:E.message,tone:"error"})},"onError")}),T=je({mutationFn:r(E=>ch.reload(E),"mutationFn"),onSuccess:r(E=>{w(),Bq(E.type),Qee(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")}),R=je({mutationFn:r(E=>ch.reinstall(E),"mutationFn"),onSuccess:r(E=>{w(),Bq(E.type),Qee(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(B=>B.type===E.type)).map(E=>({type:E.type,label:qf(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 $=k.isPending||S.isPending||C.isPending||I.isPending||T.isPending||R.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)(dm,{className:"h-6 w-6 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Adapters"}),(0,t.jsx)(lt,{variant:"outline",className:"text-amber-600 border-amber-400",children:"Alpha"})]}),(0,t.jsxs)(Vs,{open:h,onOpenChange:p,children:[(0,t.jsx)(qy,{asChild:!0,children:(0,t.jsxs)(L,{size:"sm",className:"gap-2",children:[(0,t.jsx)(bn,{className:"h-4 w-4"}),"Install Adapter"]})}),(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Install External Adapter"}),(0,t.jsxs)(yn,{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)(Ih,{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)(Po,{className:"h-3.5 w-3.5"}),"Local path"]})]}),d?(0,t.jsxs)("div",{className:"grid gap-2",children:[(0,t.jsx)(Ws,{htmlFor:"adapterLocalPath",children:"Path to adapter package"}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(pt,{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)(Ws,{htmlFor:"adapterPackageName",children:"Package Name"}),(0,t.jsx)(pt,{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)(Ws,{htmlFor:"adapterVersion",children:"Version (optional)"}),(0,t.jsx)(pt,{id:"adapterVersion",placeholder:"latest",value:l,onChange:r(E=>c(E.target.value),"onChange")})]})]})]}),(0,t.jsxs)(mr,{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)(Ds,{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)(dm,{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)(sn,{className:"bg-muted/30",children:(0,t.jsxs)(Qa,{className:"flex flex-col items-center justify-center py-10",children:[(0,t.jsx)(dm,{className:"h-10 w-10 text-muted-foreground mb-4"}),(0,t.jsx)("p",{className:"text-sm font-medium",children:"No external adapters installed"}),(0,t.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Install an adapter package to extend model support."})]})}):(0,t.jsx)(sn,{className:"block py-0",children:(0,t.jsx)("ul",{className:"divide-y",children:D.map(E=>{const B=E.overriddenBuiltin,z=B&&!!E.overridePaused,q=B?{...E,disabled:z??!1}:E;return(0,t.jsx)(iz,{adapter:q,canRemove:!0,onToggle:B?(U,F)=>I.mutate({type:U,paused:F}):(U,F)=>C.mutate({type:U,disabled:F}),onRemove:r(U=>x(U),"onRemove"),onReload:r(U=>T.mutate(U),"onReload"),onReinstall:E.isLocalPath?void 0:U=>v(E),isToggling:B?I.isPending:C.isPending,isReloading:T.isPending,isReinstalling:R.isPending,toggleTitleDisabled:B?"Pause external override":void 0,toggleTitleEnabled:B?"Resume external override":void 0,disabledBadgeLabel:B?"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)(dm,{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)(sn,{className:"block py-0",children:(0,t.jsxs)("ul",{className:"divide-y",children:[A.map(E=>(0,t.jsx)(iz,{adapter:E,canRemove:!1,onToggle:r((B,z)=>C.mutate({type:B,disabled:z}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:$},E.type)),M.map(E=>(0,t.jsx)(iz,{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((B,z)=>C.mutate({type:B,disabled:z}),"onToggle"),onRemove:r(()=>{},"onRemove"),isToggling:$,overriddenBy:E.overridePaused?void 0:E.overriddenBy},E.type))]})})]}),(0,t.jsx)(Vs,{open:f!==null,onOpenChange:r(E=>{E||x(null)},"onOpenChange"),children:(0,t.jsxs)(Qs,{children:[(0,t.jsxs)(xn,{children:[(0,t.jsx)(Js,{children:"Remove Adapter"}),(0,t.jsxs)(yn,{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)(mr,{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)(jrs,{adapter:b,open:b!==null,isReinstalling:R.isPending,onConfirm:r(()=>{b&&R.mutate(b.type,{onSettled:r(()=>v(null),"onSettled")})},"onConfirm"),onCancel:r(()=>v(null),"onCancel")})]})}r(zhe,"AdapterManager");function qhe(){const e=ga(),{companyPrefix:s,pluginId:n,pluginRoutePath:a}=e,i=e["*"],{companies:o,selectedCompanyId:l}=gs(),{setBreadcrumbs:c}=Fn(),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}=X({queryKey:P.plugins.uiContributions,queryFn:r(()=>xl.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 q7(j,a)!==null},[f,a]);if((0,m.useEffect)(()=>{if(x){if(v){c([{label:wrs(x,i)}]);return}c([{label:"Plugins",href:"/company/settings/instance/plugins"},{label:x.pluginDisplayName}])}},[x,i,c,v]),!h)return u?(0,t.jsx)(Eu,{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)(Eu,{scope:"board"});const j=n?`/company/settings/instance/plugins/${n}`:"/company/settings/instance/plugins";return(0,t.jsx)(Nn,{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)(We,{to:p?`/${p}/dashboard`:"/dashboard",children:[(0,t.jsx)(gl,{className:"h-4 w-4 mr-1"}),"Back"]})})}),(0,t.jsx)(Lu,{slot:x,context:b,className:"min-h-(--sz-200px)",missingBehavior:"placeholder"})]})}r(qhe,"PluginPage");function wrs(e,s){return krs(s)??e.displayName??e.pluginDisplayName}r(wrs,"resolveRouteSidebarPageTitle");function krs(e){const s=(e??"").split("/").filter(Boolean).map(Nrs);return s.length===0?null:s[0]==="page"&&s.length>1?Uhe(s.slice(1).join("/"),{preserveCase:!0}):Uhe(s[0]??null)}r(krs,"titleFromRouteSplat");function Uhe(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(Uhe,"titleFromPath");function Nrs(e){try{return decodeURIComponent(e)}catch{return e}}r(Nrs,"decodeRouteSegment");var AC="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",Khe=r(e=>e.status==="fail"||e.checks.some(s=>s.code==="adapter_auth_missing"),"blocking");function Srs(){const{selectedCompanyId:e}=gs(),[s]=hi();return e?(0,t.jsx)(Crs,{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(Srs,"NewAgentSetup");function Crs({companyId:e,name:s,adapterType:n,runnerProvider:a,createdAgentId:i}){const o=Ln(),l=Mt(),{openNewIssue:c}=Do(),d=xSe(`${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=iZe(h),b=f||h==="hermes_local",v=b||!!Wee[n],j=!["cursor_cloud","hermes_gateway"].includes(n),[N,w]=(0,m.useState)(""),[k,S]=(0,m.useState)(""),[C,I]=(0,m.useState)(""),[T,R]=(0,m.useState)("kimi"),[A,D]=(0,m.useState)(i?"saved":p?"connect":"runtime"),[M,$]=(0,m.useState)(""),E=u?[]:p5(n,M),[B,z]=(0,m.useState)(""),[q,U]=(0,m.useState)(!1),[F,K]=(0,m.useState)(""),[G,se]=(0,m.useState)("openrouter"),[ee,ne]=(0,m.useState)(""),[he,Z]=(0,m.useState)(null),[re,ce]=(0,m.useState)(()=>h==="opencode_local"?{provider:"openrouter",method:"api_key",mode:"responsible_user"}:void 0),[H,Q]=(0,m.useState)(null),Y=re??H?.aiConnection,[te,ae]=(0,m.useState)(""),[me,oe]=(0,m.useState)(""),[ie,ge]=(0,m.useState)(null),be=X({queryKey:P.agents.detail(i??"new"),queryFn:r(()=>Lt.get(i,e),"queryFn"),enabled:!!i,retry:!1}),le=ie??(be.data?.companyId===e?be.data:null),[ue,Se]=(0,m.useState)(!1),[ye,Ie]=(0,m.useState)("idle"),[Ke,rt]=(0,m.useState)(null),[dt,de]=(0,m.useState)(null),ze=(0,m.useRef)(0),gt=(0,m.useRef)(!1);(0,m.useEffect)(()=>()=>{ze.current++},[]);const bt=r(()=>{ze.current++,rt(null),Ie("idle"),de(null)},"resetTest"),De=X({queryKey:P.adapters.all,queryFn:ch.list}),Qe=X({queryKey:P.agents.list(e),queryFn:r(()=>Lt.list(e),"queryFn")}),mt=X({queryKey:P.environments.list(e),queryFn:r(()=>Ri.list(e),"queryFn")}),Ye=X({queryKey:P.instance.settings,queryFn:Or.get}),it=X({queryKey:P.instance.experimentalSettings,queryFn:Or.getExperimental}),Nt=X({queryKey:P.instance.generalSettings,queryFn:Or.getGeneral}),Ze=X({queryKey:P.environments.capabilities(e),queryFn:r(()=>Ri.capabilities(e),"queryFn")}),Pe=X({queryKey:P.agents.adapterModels(e,h,null,Y?.provider),queryFn:r(()=>Lt.adapterModels(e,h,{provider:Y?.provider}),"queryFn"),enabled:!!h&&j,retry:!1}),Ce=X({queryKey:P.secrets.list(e),queryFn:r(()=>Sr.list(e),"queryFn"),enabled:v&&n!=="cursor_cloud"}),Ve=X({queryKey:P.secrets.myUserSecrets(e),queryFn:r(()=>Sr.listMyUserSecrets(e),"queryFn"),enabled:v&&n!=="cursor_cloud",retry:!1}),Ge=yW(Nt.data?.executionMode,mt.data??[]),ot=it.data?.enableManagedSandboxOnly===!0;let Ee=null,Je=null;try{Ee=Ge.forced?Ge.kubernetesEnvironment?.id??null:Zk({agentDefaultEnvironmentId:F||null,instanceDefaultEnvironmentId:Ye.data?.defaultEnvironmentId??null,localDefaultEnvironmentId:tN(mt.data??[]),managedSandboxOnly:ot,managedSandboxEnvironmentId:eN(mt.data??[]),visibleEnvironmentIds:(mt.data??[]).map(Le=>Le.id)})}catch(Le){Je=Le instanceof Error?Le.message:"Could not resolve the environment."}const _e=mt.data?.find(Le=>Le.id===Ee),He=typeof _e?.config?.provider=="string"?_e.config.provider:"",ns=_e?.driver==="sandbox"&&Ze.data?.sandboxProviders?.[He]?.supportsLoginPty===!0,fe=Wee[n]??x[G]??"API_KEY",ct=Ve.data?.find(Le=>Le.definition.key===fe&&Le.secret),Ue=Ce.data?.find(Le=>Le.key===fe&&Le.status==="active"),Et=n==="cursor_cloud"?null:he??(Ue?{type:"secret_ref",secretId:Ue.id,version:"latest"}:ct?{type:"user_secret_ref",key:fe,version:"latest"}:null),$t=n==="kimi_local"&&!!(ee.trim()||Et),js=!!Ac(),Fe=gSe(n,{cloud:js,nativeRunnerEnabled:it.data?.enableNativeRunner===!0})&&De.data?.some(Le=>Le.type===n&&Le.loaded&&!Le.disabled&&!Nh(n).comingSoon),xt=!!(Fe&&!Je&&!mt.isPending&&!Ye.isPending&&!it.isPending&&!Nt.isPending&&!Qe.isPending&&!Ze.isPending&&!mt.error&&!Ye.error&&!it.error&&!Nt.error&&!Qe.error&&!Ze.error&&(!(ot||Ge.forced)||Ee)),Wt=ye==="running"||ue;function Cs(Le=H,et=Et){const vt={...tb,adapterType:n,model:M||(h==="codex_local"?Yk:""),thinkingEffort:B,dangerouslyBypassSandbox:n==="codex_local",envBindings:Le?.env??{},...u?{adapterSchemaValues:{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{}}}:{}},$e=tS(n).buildAdapterConfig(vt);return u&&Object.assign($e,{provider:a==="claude"||a==="grok"?"acpx":a,...a==="claude"||a==="grok"?{acpxAgent:a}:{},...M?{model:M}:{}}),!Y&&!Le?.aiConnection&&v&&et&&(n==="hermes_gateway"?$e.apiKey=et:$e.env={...$e.env??{},[fe]:et}),n==="cursor_cloud"&&Object.assign($e,{repoUrl:te.trim(),...me.trim()?{repoStartingRef:me.trim()}:{}}),n==="hermes_gateway"&&($e.apiBaseUrl=N.trim()),$t&&(delete $e.model,$e.env={...$e.env??{},KIMI_MODEL_NAME:{type:"plain",value:k.trim()},KIMI_MODEL_PROVIDER_TYPE:{type:"plain",value:T},...C.trim()?{KIMI_MODEL_BASE_URL:{type:"plain",value:C.trim()}}:{}}),$e}r(Cs,"buildConfig");function Ts(Le=H){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)&&!ee.trim()&&!Et)throw new Error(n==="cursor_cloud"?"Enter a Cursor API key.":`Enter ${fe} or select an organization secret.`);if(n==="hermes_gateway")try{const et=new URL(N.trim());if(!["https:","http:"].includes(et.protocol))throw new Error}catch{throw new Error("Enter the Hermes API base URL.")}if($t&&!k.trim())throw new Error("Enter the Kimi API model name.");return Cs(Le)}r(Ts,"preparedConfig");function Ct(Le=H){return Y||Le?.aiConnection?{}:{...Le?.credentials,...v&&ee.trim()?{[fe]:ee.trim()}:{}}}r(Ct,"pendingCredentials");async function ds(Le=H){if(!xt)return!1;const et=++ze.current;Ie("running"),rt(null),de(null);try{const vt=await Ts(Le),$e=await eNe({companyId:e,adapterType:n,providerAdapter:h,adapterConfig:vt,testCredentials:Ct(Le),aiConnection:re??Le?.aiConnection,environmentId:Ee});return et!==ze.current?!1:(rt($e),Ie(Khe($e)?"fail":$e.status),!Khe($e)&&(!p||$e.checks.some(Ft=>Ft.code.endsWith("hello_probe_passed"))))}catch(vt){return et===ze.current&&(de(vt instanceof Error?vt.message:"Could not test the agent."),Ie("fail")),!1}}r(ds,"runTest");async function Oe(){if(gt.current||i||le||!xt||!s.trim()||ye==="running"||ye==="fail"||p&&!H)return;gt.current=!0,Se(!0),de(null);const Le=[];let et=!1;try{const vt=Ts(),$e=Ct();if(Object.keys($e).length&&!await ds())return;for(const[Zt,us]of Object.entries($e)){const ht=await(p?uNe:rZe)(e,Zt,us);Le.push(ht),n==="hermes_gateway"&&Zt==="API_SERVER_KEY"?vt.apiKey=ht.binding:vt.env={...vt.env??{},[Zt]:ht.binding}}const Ft=Qe.data??[],wt=Ft.find(Zt=>Zt.role==="ceo"&&Zt.status!=="terminated"),Yt=await Lt.hire(e,{name:s.trim(),appearance:d.appearance,role:Ft.length?"general":"ceo",...wt?{reportsTo:wt.id}:{},adapterType:n,adapterConfig:vt,defaultEnvironmentId:F||(Ge.forced||ot?Ee:null),runtimeConfig:{...i_e({heartbeatEnabled:!1}),...Y?{aiConnection:Y}:{}},budgetMonthlyCents:0,...H?.storedSessionId?{storedSessionId:H.storedSessionId}:{},...H?.applyStoredClaudeLogin?{applyStoredClaudeLogin:!0}:{}});et=!0,ne(""),Q(null),ge(Yt.agent),d.clear(),D("saved"),o(`/agents/new?${new URLSearchParams({name:Yt.agent.name,adapterType:n,runnerProvider:a,createdAgentId:Yt.agent.id})}`,{replace:!0}),l.setQueryData(P.agents.detail(Yt.agent.id),Yt.agent),await Promise.all([l.invalidateQueries({queryKey:P.agents.list(e)}),l.invalidateQueries({queryKey:P.approvals.list(e)})])}catch(vt){de(vt instanceof Error?vt.message:"Could not create the agent.")}finally{if(!et)try{await Promise.all(Le.map(vt=>vt.remove()))}catch{de(vt=>`${vt?`${vt} `:""}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)}),gt.current=!1,Se(!1)}}if(r(Oe,"finish"),i&&!le)return(0,t.jsx)("p",{role:be.error?"alert":"status",className:"text-sm text-muted-foreground",children:be.error?"Could not load the created agent. Return to Agents to view it.":"Loading your agent…"});if(!s||!n)return(0,t.jsx)(bSe,{open:!0,initialAdapter:n,onClose:r(()=>o("/agents/all"),"onClose"),onContinue:r(Le=>o(`/agents/new?${new URLSearchParams(Le)}`,{replace:!0}),"onContinue")});const xe=[...p?["connect"]:[],"runtime","saved"],Gt={connect:"Connect",runtime:"Configure",saved:"Confirmation"},Pt=le?.defaultEnvironmentId?mt.data?.find(Le=>Le.id===le.defaultEnvironmentId):_e,os=le?.adapterConfig?.env?.KIMI_MODEL_NAME,ws=le?.adapterConfig?.model||(typeof os=="string"?os:os?.value)||M||"Default",Hs=n==="cursor_cloud"?"Cursor Cloud":n==="hermes_gateway"?"Hermes Gateway":Pt?Hv(Pt):"Local machine",tr=De.error??mt.error??Ye.error??it.error??Nt.error??Qe.error??Ze.error;return(0,t.jsx)(Fke,{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)(T_,{appearance:le?.appearance??d.appearance,size:256,className:"size-48",trackingScope:"page",state:le||ye==="pass"?"success":ye==="running"?"loading":"sleepy",muted:!le&&ye!=="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:Nh(h).label}),u&&(0,t.jsxs)("span",{children:["·"," ",a==="codex"?"Native app server runner":"Paperclip Runner"]})]})]})]}),Je&&!mt.isPending&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:Je}),tr&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:tr.message}),De.data&&!Fe&&(0,t.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:"This adapter is unavailable. Choose an enabled adapter."}),(ot||Ge.forced)&&!mt.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((Le,et)=>(0,t.jsx)("li",{children:(0,t.jsxs)("button",{type:"button","aria-current":Le===A?"step":void 0,disabled:Wt||!!le||et>xe.indexOf(A),onClick:r(()=>D(Le),"onClick"),className:W("flex w-full items-center gap-3 rounded-md px-3 py-3 text-left text-sm",Le===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",Le===A?"border-foreground bg-foreground text-background":"border-border"),children:et+1}),Gt[Le]]})},Le))})}),(0,t.jsx)("div",{className:"min-w-0 flex-1",children:(0,t.jsx)(eS,{mode:"wait",initial:!1,children:(0,t.jsx)(fl.div,{...wZe,children:A==="connect"&&p?(0,t.jsxs)(ppt,{className:"mx-auto",children:[(0,t.jsx)("div",{className:"mb-8",children:(0,t.jsx)(o_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:AC,value:F,disabled:Wt||Ge.forced,onChange:r(Le=>{K(Le.target.value),Q(null),bt()},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Hs]}),(mt.data??[]).filter(Le=>Le.status==="active"&&(!ot||Le.driver!=="local")).map(Le=>(0,t.jsx)("option",{value:Le.id,children:Hv(Le)},Le.id))]})})}),(0,t.jsx)(wSe,{companyId:e,adapterType:p,environmentId:Ee,canLogin:ns,localEnvironment:_e?.driver==="local",onBack:r(()=>o("/agents/all"),"onBack"),testConnection:ds,testError:dt??(Ke?.checks.find(Le=>Le.level==="error")??Ke?.checks.find(Le=>Le.code.includes("hello_probe")&&Le.level==="warn"))?.message,onConnected:r(Le=>{Q(Le),bt(),D("runtime")},"onConnected")},Ee??"local")]}):A==="saved"&&le?(0,t.jsxs)("div",{className:"space-y-6",children:[(0,t.jsxs)("div",{className:"space-y-6 rounded-lg border border-border p-6",children:[(0,t.jsxs)("h2",{className:"flex items-center gap-3 text-lg font-semibold",children:[(0,t.jsx)(vs,{className:"size-5"}),le.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:Nh(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:Hs})]}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:le.status==="pending_approval"?"An organization administrator must approve this agent before it can work.":"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(`${xm(le)}/runtime`),"onClick"),children:[(0,t.jsx)(k7,{className:"size-4"}),"Edit configuration"]}),(0,t.jsxs)(L,{disabled:le.status==="pending_approval",onClick:r(()=>c({assigneeAgentId:le.id,status:"todo"}),"onClick"),children:["Assign ",le.name," a Task",(0,t.jsx)(el,{className:"size-4"})]})]})]}):(0,t.jsxs)("form",{className:"space-y-8",onSubmit:r(Le=>{Le.preventDefault(),Oe()},"onSubmit"),children:[(0,t.jsx)("h2",{className:"text-xl font-semibold",children:"Configure your agent"}),(0,t.jsxs)("fieldset",{disabled:Wt,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"}),rW(h)&&(H&&!Y?(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)(Zke,{companyId:e,agentName:s,adapterType:h,model:M,environmentId:Ee??void 0,value:Y,onChange:r(Le=>{Le.mode!=="router"&&ce(Le),bt()},"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&&!$t||E.length>0)&&(0,t.jsxs)("div",{className:"grid items-start gap-5 sm:grid-cols-2",children:[j&&!$t&&(0,t.jsx)(wW,{models:Pe.data??[],value:M,onChange:r(Le=>{$(Le),B&&!p5(n,Le).includes(B)&&z("");const et=Le.split("/")[0];f&&dNe[et]&&et!==G&&(se(et),ne(""),Z(null)),bt()},"onChange"),open:q,onOpenChange:U,allowDefault:!f,required:f,creatable:!0,groupByProvider:f,preserveOrder:mW(h)}),E.length>0&&(0,t.jsx)(Ss,{label:"Thinking effort",children:(0,t.jsxs)("select",{"aria-label":"Thinking effort",className:AC,value:B,onChange:r(Le=>{z(Le.target.value),bt()},"onChange"),children:[(0,t.jsx)("option",{value:"",children:"Auto"}),E.map(Le=>(0,t.jsx)("option",{value:Le,children:Le},Le))]})})]}),Vee[n]&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:Vee[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&&!Y&&(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:AC,value:G,onChange:r(Le=>{se(Le.target.value),$(""),ne(""),Z(null),bt()},"onChange"),children:Object.keys(x).map(Le=>(0,t.jsx)("option",{value:Le,children:Le==="openrouter"?"OpenRouter":Le==="openai"?"OpenAI":Le==="anthropic"?"Anthropic":{google:"Google",xai:"xAI",groq:"Groq",opencode:"OpenCode"}[Le]??Le},Le))})}),(0,t.jsx)("div",{className:n==="cursor_cloud"?"sm:col-span-2":void 0,children:(0,t.jsx)(Ss,{label:fe,children:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(pt,{"aria-label":fe,type:"password",autoComplete:"off",value:ee,onChange:r(Le=>{ne(Le.target.value),Z(null),bt()},"onChange"),placeholder:Et?"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)(fW,{secretId:Et&&typeof Et=="object"&&Et.type==="secret_ref"?Et.secretId:"",secrets:Ce.data??[],disabled:Wt,onSelect:r(Le=>{Z({type:"secret_ref",secretId:Le,version:"latest"}),ne(""),bt()},"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 ${G}/model ID.`]})]}),n==="hermes_gateway"&&(0,t.jsx)(Ss,{label:"Hermes API base URL",children:(0,t.jsx)(pt,{"aria-label":"Hermes API base URL",value:N,onChange:r(Le=>{w(Le.target.value),bt()},"onChange"),placeholder:"https://hermes.example.com"})}),$t&&(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)(pt,{"aria-label":"Kimi API model name",value:k,onChange:r(Le=>{S(Le.target.value),bt()},"onChange"),placeholder:"kimi-for-coding"})}),(0,t.jsx)(Ss,{label:"Kimi API protocol",children:(0,t.jsx)("select",{"aria-label":"Kimi API protocol",className:AC,value:T,onChange:r(Le=>{R(Le.target.value),bt()},"onChange"),children:["kimi","anthropic","openai"].map(Le=>(0,t.jsx)("option",{children:Le},Le))})}),(0,t.jsx)(Ss,{label:"Kimi API base URL",hint:"Optional override for your provider endpoint.",children:(0,t.jsx)(pt,{"aria-label":"Kimi API base URL",value:C,onChange:r(Le=>{I(Le.target.value),bt()},"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)(pt,{"aria-label":"GitHub repository",value:te,onChange:r(Le=>{ae(Le.target.value),bt()},"onChange"),placeholder:"https://github.com/your-org/repo"})}),(0,t.jsx)(Ss,{label:"Branch",children:(0,t.jsx)(pt,{"aria-label":"Branch",placeholder:"Repository default",value:me,onChange:r(Le=>{oe(Le.target.value),bt()},"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:AC,value:F,disabled:Ge.forced,onChange:r(Le=>{K(Le.target.value),Q(null),bt(),p&&D("connect")},"onChange"),children:[(0,t.jsxs)("option",{value:"",children:["Default: ",Hs]}),(mt.data??[]).filter(Le=>Le.status==="active"&&(!ot||Le.driver!=="local")).map(Le=>(0,t.jsx)("option",{value:Le.id,children:Hv(Le)},Le.id))]})]})]}),(0,t.jsx)(mNe,{state:ye,result:Ke,error:dt,disabled:!xt||Wt,onTest:r(()=>{ds()},"onTest")}),dt&&ye!=="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:Wt,onClick:r(()=>D("connect"),"onClick"),children:[(0,t.jsx)(gl,{className:"size-4"}),"Connection"]}):(0,t.jsx)("span",{}),(0,t.jsxs)(L,{type:"submit",disabled:!xt||Wt||ye==="fail"||!!(p&&!H),children:[ue?"Creating…":"Finish setup",(0,t.jsx)(vs,{className:"size-4"})]})]})]})},A)})})]})]})})}r(Crs,"Setup");function _rs(){const{setBreadcrumbs:e}=Fn();return(0,m.useEffect)(()=>{e([{label:"Agents",href:"/agents"},{label:"New agent"}])},[e]),(0,t.jsx)(Srs,{})}r(_rs,"NewAgent");var GP="paperclip:pending-invite-token";function SG(){return typeof window<"u"&&typeof window.localStorage<"u"}r(SG,"canUseStorage");function Whe(e){const s=e.trim();if(!(!s||!SG()))try{window.localStorage.setItem(GP,s)}catch{}}r(Whe,"rememberPendingInviteToken");function MR(e){if(SG())try{const s=window.localStorage.getItem(GP);if(e&&s!==e.trim())return;window.localStorage.removeItem(GP)}catch{}}r(MR,"clearPendingInviteToken");function Irs(){if(!SG())return null;try{const e=window.localStorage.getItem(GP)?.trim();return e?`/invite/${e}`:null}catch{return null}}r(Irs,"getRememberedInvitePath");var Vhe=[" ",".","·","▪","▫","○"],Ars=1e3/24,DR=[[" ╭────╮ "," ╭╯╭──╮│ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ │ ││ "," │ ╰──╯│ "," ╰─────╯ "],[" ╭─────╮ "," │╭──╮╰╮ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," ││ │ │ "," │╰──╯ │ "," ╰────╯ "]];function Hhe(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(Hhe,"measureChar");function Trs(e){let s=0;for(const n of e)s=Math.max(s,n.length);return{width:s,height:e.length}}r(Trs,"spriteSize");function Rrs(){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 B=Math.floor(Math.max(0,Math.min(.999,E))*Vhe.length);return Vhe[B]??" "}r(w,"toGlyph");function k(){const E=Math.max(0,Math.ceil(n.clientWidth/Math.max(1,h))),B=Math.max(0,Math.ceil(n.clientHeight/Math.max(1,p)));if(E===d&&B===u)return;d=E,u=B;const z=d*u;f=new Float32Array(z),x=new Float32Array(d),b=new Float32Array(u),v=new Uint16Array(z),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 F=0;F<d;F++){const K=(Math.sin(F*.11+U*.04)+Math.cos(U*.08-F*.02))*.18+.22;E[U][F]=w(K)}const B=18,z=13;for(let U=1;U<u-9;U+=z){const F=Math.floor(U/z)%2===0?2:10;for(let K=F;K<d-10;K+=B){const G=DR[(K+U)%DR.length];for(let se=0;se<G.length;se++){const ee=G[se];for(let ne=0;ne<ee.length;ne++){const he=ee[ne]??" ";if(he===" ")continue;const Z=U+se,re=K+ne;Z<0||Z>=u||re<0||re>=d||(E[Z][re]=he)}}}}const q=E.map(U=>U.join("")).join(`
|
|
770
770
|
`);n.textContent=q,N=q}r(S,"drawStaticFrame");function C(){const E=DR[Math.floor(Math.random()*DR.length)],B=Trs(E),z=Math.random();let q=0,U=0,F=0,K=0;z<.68?(q=Math.random()<.5?-B.width-1:d+1,U=Math.random()*Math.max(1,u-B.height),F=q<0?.04+Math.random()*.05:-(.04+Math.random()*.05),K=(Math.random()-.5)*.014):(q=Math.random()*Math.max(1,d-B.width),U=Math.random()<.5?-B.height-1:u+1,F=(Math.random()-.5)*.014,K=U<0?.028+Math.random()*.034:-(.028+Math.random()*.034)),j.push({x:q,y:U,vx:F,vy:K,life:0,maxLife:260+Math.random()*220,drift:(Math.random()-.5)*1.2,sprite:E,width:B.width,height:B.height})}r(C,"spawnClip");function I(E,B){const z=Math.round(E.x),q=Math.round(E.y);for(let U=0;U<E.sprite.length;U++){const F=E.sprite[U],K=q+U;if(!(K<0||K>=u))for(let G=0;G<F.length;G++){const se=F[G]??" ";if(se===" ")continue;const ee=z+G;if(ee<0||ee>=d)continue;const ne=K*d+ee,he=se==="│"||se==="─"?.8:.92;f[ne]=Math.max(f[ne]??0,B*he),v[ne]=se.charCodeAt(0)}}}r(I,"stampClip");function T(E){if(!o||(s.current=requestAnimationFrame(T),E-l<Ars||d<=0||u<=0))return;const B=Math.min(2,l===0?1:(E-l)/16.6667);l=E,c+=B;const z=d*u,q=Math.max(3,Math.floor(z/2200));for(;j.length<q;)C();for(let F=0;F<f.length;F++)f[F]*=.92;v.fill(0);for(let F=j.length-1;F>=0;F--){const K=j[F];K.life+=B;const G=Math.sin((K.y+K.drift+c*.12)*.09)*.0018,se=Math.cos((K.x-K.drift-c*.09)*.08)*.0014;if(K.vx=(K.vx+G)*.998,K.vy=(K.vy+se)*.998,K.x+=K.vx*B,K.y+=K.vy*B,K.life>=K.maxLife||K.x<-K.width-2||K.x>d+2||K.y<-K.height-2||K.y>u+2){j.splice(F,1);continue}const ee=K.life/K.maxLife;I(K,ee<.12?ee/.12:ee>.88?(1-ee)/.12:1)}for(let F=0;F<d;F++)x[F]=Math.sin(F*.08+c*.06);for(let F=0;F<u;F++)b[F]=Math.cos(F*.1-c*.05);let U="";for(let F=0;F<u;F++){for(let K=0;K<d;K++){const G=F*d+K,se=v[G];if(se>0){U+=String.fromCharCode(se);continue}const ee=(x[K]+b[F])*.08+.1,ne=Math.max(f[G]??0,ee*.45);U+=w(ne)}F<u-1&&(U+=`
|
|
771
|
-
`)}U!==N&&(n.textContent=U,N=U)}r(T,"step");function R(){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(T))}r(R,"syncLoop");const A=new ResizeObserver(()=>{const E=Hhe(n);h=E.w,p=E.h,k(),R()});A.observe(n);const D=r(()=>{i=document.visibilityState!=="hidden",R()},"onVisibilityChange");document.addEventListener("visibilitychange",D);const M=r(()=>{R()},"onMotionChange");a.addEventListener("change",M);const $=Hhe(n);return h=$.w,p=$.h,k(),R(),()=>{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(Rrs,"AsciiArtAnimation");function Ers({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(Ers,"PaperclipLockup");function Prs(){const e=Mt(),s=Ln(),[n]=hi(),[a,i]=(0,m.useState)("sign_in"),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),x="auth-error",b=(0,m.useMemo)(()=>ZSe(n.get("next")||Irs()||"/"),[n]),v=X({queryKey:P.health,queryFn:r(()=>su.get(),"queryFn"),retry:!1}),{data:j,isLoading:N,error:w}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{j&&(tV(),s(b,{replace:!0}))},[j,s,b]);const k=je({mutationFn:r(async()=>{if(a==="sign_in"){await La.signInEmail({email:c.trim(),password:u});return}await La.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)(Dm,{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)(sV,{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)(hk,{})}),(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)(Ers,{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)(Rrs,{})})]})}r(Prs,"AuthPage");function Mrs(){const e=Mt(),s=ga(),[n]=hi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),c=X({queryKey:["board-claim",a,i],queryFn:r(()=>hr.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>hr.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)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Claim challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const u=c.data;return u?u.status==="claimed"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate organization ownership access from local trusted mode."}),d.error&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to claim board ownership"}),(0,t.jsx)(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)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Claim challenge unavailable."})}r(Mrs,"BoardClaimPage");function Drs(){const e=Mt(),s=ga(),[n]=hi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),c=X({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>hr.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>hr.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await c.refetch()},"onSuccess")}),u=je({mutationFn:r(()=>hr.cancelCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid CLI auth URL."});if(l.isLoading||c.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading CLI auth challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"CLI auth challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const h=c.data;return h?h.status==="approved"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"CLI access approved"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The Paperclip CLI can now finish authentication on the requesting machine."}),(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Command: ",(0,t.jsx)("span",{className:"font-mono text-foreground",children:h.command})]})]})}):h.status==="cancelled"||h.status==="expired"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h.status==="expired"?"CLI auth challenge expired":"CLI auth challenge cancelled"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Start the CLI auth flow again from your terminal to generate a new approval request."})]})}):h.requiresSignIn||!l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Approve Paperclip CLI access"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local Paperclip CLI process is requesting board access to this instance."}),(0,t.jsxs)("div",{className:"mt-5 space-y-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Command"}),(0,t.jsx)("div",{className:"font-mono text-foreground",children:h.command})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Client"}),(0,t.jsx)("div",{className:"text-foreground",children:h.clientName??"paperclip-pro cli"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested access"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),h.requestedCompanyName&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested organization"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedCompanyName})]})]}),(d.error||u.error)&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:(d.error??u.error)instanceof Error?(d.error??u.error).message:"Failed to update CLI auth challenge"}),!h.canApprove&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),(0,t.jsxs)("div",{className:"mt-5 flex gap-3",children:[(0,t.jsx)(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(Drs,"CliAuthPage");var Lrs=wLe.filter(e=>e!=="paperclip_runner"),Ghe=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function $rs(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($rs,"readNestedString");var vw="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",Qhe="border border-zinc-800 bg-zinc-950/95 p-6",Yhe="flex-1 border px-3 py-2 text-sm transition-colors";function Ors(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(Ors,"formatHumanRole");function ZMe(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(ZMe,"getAuthErrorCode");function Frs(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(Frs,"getAuthErrorMessage");function Brs(e,s,n){const a=ZMe(e),i=Frs(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(Brs,"mapInviteAuthFeedback");function Jhe(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(Jhe,"isBootstrapAcceptancePayload");function zrs(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(zrs,"isApprovedHumanJoinPayload");function M8({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(GN,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(M8,"InviteCompanyLogo");function Xhe({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)(M8,{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(Xhe,"AwaitingJoinApprovalPanel");function qrs(){const e=Mt(),s=Ln(),{setSelectedCompanyId:n}=gs(),a=(ga().token??"").trim(),[i,o]=(0,m.useState)("sign_up"),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(""),[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,T]=(0,m.useState)(null),[R,A]=(0,m.useState)(!1),D="invite-auth-error",M=X({queryKey:P.health,queryFn:r(()=>su.get(),"queryFn"),retry:!1}),$=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),E=X({queryKey:P.access.invite(a),queryFn:r(()=>hr.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),B=U8({enabled:!!$.data&&!!E.data?.companyId,staleTime:0}),z=M.data?.deploymentMode!=="local_trusted"?B.isFetchedAfterMount:!0,q=z?B.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&Whe(a)},[a]),(0,m.useEffect)(()=>{A(!1)},[a]),(0,m.useEffect)(()=>{if(!z)return;const ge=B.data?.companies;!ge||!E.data?.companyId||ge.some(be=>be.id===E.data.companyId)&&MR(a)},[B.data,E.data,z,a]);const U=E.data,F=!!$.data&&!!U?.companyId&&!z,K=!!U?.companyId&&q.some(ge=>ge.id===U?.companyId),G=U?.companyName?.trim()||"this Paperclip company",se=U?.companyLogoUrl?.trim()||null,ee=U?.invitedByUserName?.trim()||null,ne=U?.inviteMessage?.trim()||null,he=Ors(U?.humanRole),Z=U?.joinRequestStatus??null,re=U?.joinRequestType??null,ce=re==="human"&&(Z==="pending_approval"||Z==="approved"),H=M.data?.deploymentMode==="authenticated"&&!$.data&&U?.allowedJoinTypes!=="agent",Q=U?.inviteType!=="bootstrap_ceo"&&U?.allowedJoinTypes==="agent",Y=!!$.data&&!Q&&U?.inviteType!=="bootstrap_ceo"&&(!Z||ce)&&!F&&!K&&!w&&S===null,te=$.data?.user.name?.trim()||$.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),me=je({mutationFn:r(async()=>{if(!U)throw new Error("Invite not found");if(F)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"?hr.acceptInvite(a,{requestType:"human"}):hr.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:b,capabilities:j.trim()||null})},"mutationFn"),onSuccess:r(async ge=>{C(null),MR(a);const be=Jhe(ge);k({kind:be?"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&&zrs(ge,Q)&&(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)(()=>{!Y||R||me.isPending||(A(!0),C(null),me.mutate())},[me,R,Y]);const oe=je({mutationFn:r(async()=>{if(i==="sign_in"){await La.signInEmail({email:d.trim(),password:h});return}await La.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{T(null),Whe(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 UDe(e);if(U?.companyId&&ge.some(be=>be.id===U.companyId)){MR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!U||U.inviteType!=="bootstrap_ceo"))try{Jhe(await me.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ge=>{const be=Brs(ge,i,d);ZMe(ge)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),T(be)},"onError")}),ie=(0,m.useMemo)(()=>U?K?"Open organization":U.inviteType==="bootstrap_ceo"?"Accept invite":Q?"Submit request":$.data?"Accept invite":"Continue":"Continue",[U,K,$.data,Q]);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||$.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(F)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(Z==="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(Z==="pending_approval"&&!ce)return(0,t.jsx)(Xhe,{companyDisplayName:G,companyLogoUrl:se,invitedByUserName:ee});if(Z&&!ce)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:Z==="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)(We,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ge=w.payload,be=typeof ge.claimSecret=="string"?ge.claimSecret:null,le=typeof ge.claimApiKeyPath=="string"?ge.claimApiKeyPath:null,ue=$rs(ge.onboarding,["textInstructions","url"]);return!Q&&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)(M8,{companyDisplayName:G,companyLogoUrl:se,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)(We,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(Xhe,{companyDisplayName:G,companyLogoUrl:se,invitedByUserName:ee,claimSecret:be,claimApiKeyPath:le,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:`${Qhe} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(M8,{companyDisplayName:G,companyLogoUrl:se,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 ${G}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:Q?"Review the invite details, then submit the agent information below to start the join request.":H?"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:G})]}),(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:ee??"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:Q?"Agent join request":he??"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,$.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:`${Qhe} h-fit`,children:Q?(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 ",G,"."]})]}),(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:vw,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:vw,value:b,onChange:r(ge=>v(ge.target.value),"onChange"),children:Lrs.map(ge=>(0,t.jsxs)("option",{value:ge,disabled:!Ghe.has(ge),children:[qf(ge),Ghe.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:vw,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:me.isPending||f.trim().length===0,onClick:r(()=>me.mutate(),"onClick"),children:me.isPending?"Working...":ie})]}):H?(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 ${G}.`:"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:`${Yhe} ${i==="sign_up"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{T(null),o("sign_up")},"onClick"),children:"Create account"}),(0,t.jsx)("button",{type:"button",className:`${Yhe} ${i==="sign_in"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{T(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(),!oe.isPending){if(!ae){T({tone:"error",message:"Please fill in all required fields."});return}oe.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:vw,value:l,onChange:r(ge=>{c(ge.target.value),T(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:vw,value:d,onChange:r(ge=>{u(ge.target.value),T(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:vw,value:h,onChange:r(ge=>{p(ge.target.value),T(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:oe.isPending,"aria-disabled":!ae||oe.isPending,children:oe.isPending?"Working...":i==="sign_in"?"Sign in and continue":"Create account and continue"})]}),(0,t.jsx)("p",{className:"text-xs leading-5 text-zinc-500",children:i==="sign_up"?"Already signed up before? Use the existing-account option instead so the invite lands on the right Paperclip user.":"No account yet? Switch back to create account so you can accept the invite with a new login."})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:K?"Already in this organization":Y?"Completing organization access":U.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Y?`Granting your access to ${G}.`:K?`This account already belongs to ${G}.`:`This will ${U.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${G}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Y?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:me.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)(L,{className:"w-full rounded-none",disabled:me.isPending,onClick:r(()=>{if(K&&U.companyId){MR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}me.mutate()},"onClick"),children:me.isPending?"Working...":ie})]})})]})})})}r(qrs,"InviteLandingPage");var Urs=15e3,Krs={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Wrs(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Wrs,"useNoIndexMeta");function D8(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(D8,"sharePath");var Vrs=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function Hrs(e,s){const n=Vrs.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(Hrs,"publicShareImageSrc");function TC({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(TC,"Section");function L8({actor:e}){return(0,t.jsx)(Bl,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(L8,"ActorIdentity");function $8({value:e}){return(0,t.jsx)("time",{dateTime:e,title:Lr(e),className:"text-xs text-muted-foreground",children:or(e)})}r($8,"Timestamp");function Grs({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(Grs,"ActiveRunPill");function e4e({attachments:e}){return(0,t.jsx)(p9,{children:e.map(s=>{const n=Rje({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=f9(s.byteSize);return(0,t.jsxs)(c9,{size:"sm",children:[(0,t.jsx)(d9,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(u9,{children:[(0,t.jsx)(m9,{className:"max-w-48",children:s.filename}),(0,t.jsx)(h9,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(_je,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(e4e,"AttachmentList");function Qrs({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)(Wi,{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:Krs[e.relation]}),e.navigable?(0,t.jsx)(rd,{to:n?D8(s,e.id):D8(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(Qrs,"RelatedIssueRow");function Yrs({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)(L8,{actor:e.author}),(0,t.jsx)($8,{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)(L8,{actor:e.author}),(0,t.jsx)($8,{value:e.createdAt})]}),(0,t.jsx)(Rn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:s,children:e.body}),e.attachments.length>0?(0,t.jsx)(e4e,{attachments:e.attachments}):null]})}r(Yrs,"TimelineEntry");function Jrs({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)(Wa,{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)($8,{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)(oo,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(Rn,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(Jrs,"DocumentCard");function Xrs({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)(qn,{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)(oo,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(Xrs,"WorkProductRow");function Zhe({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(Zhe,"CenteredNotice");function Zrs({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>Hrs(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)(GN,{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)(rd,{to:D8(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(gl,{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)(Zh,{status:a.status}),(0,t.jsx)(Rfe,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(L8,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(Grs,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",Lr(a.createdAt)," · Updated ",or(a.updatedAt),a.completedAt?` · Completed ${Lr(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(Rn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)(TC,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(Qrs,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(TC,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(Jrs,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(TC,{title:"Attachments",children:(0,t.jsx)(e4e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(TC,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(Xrs,{product:o},o.id))})}):null,(0,t.jsx)(TC,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(Yrs,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(Zrs,"PublicIssueShareContent");function epe(){const{token:e="",issueId:s}=ga();Wrs();const n=NBe.test(e),a=X({queryKey:P.publicShare.view(e,s??null),queryFn:r(()=>s?_k.getPublicShareIssue(e,s):_k.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?Urs:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Zhe,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(Zrs,{view:a.data,token:e}):a.isError?(0,t.jsx)(Zhe,{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)(gn,{className:"h-6 w-1/2"}),(0,t.jsx)(gn,{className:"h-4 w-1/3"}),(0,t.jsx)(gn,{className:"h-24 w-full"})]})})}r(epe,"PublicIssueSharePage");function eas(){const{selectedCompany:e,selectedCompanyId:s}=gs(),{setBreadcrumbs:n}=Fn(),{pushToast:a}=pi(),i=Mt(),[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=X({queryKey:P.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>hr.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=je({mutationFn:r(f=>hr.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=>hr.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 un&&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)(Yze,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Join Request Queue"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Review human and agent join requests outside the mixed inbox feed. This queue uses the same approval mutations as the inline inbox cards."})]}),(0,t.jsxs)(sn,{className:"flex-row flex-wrap gap-3 p-4",children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Status"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(f=>l(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"pending_approval",children:"Pending approval"}),(0,t.jsx)("option",{value:"approved",children:"Approved"}),(0,t.jsx)("option",{value:"rejected",children:"Rejected"})]})]}),(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Request type"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:c,onChange:r(f=>d(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"all",children:"All"}),(0,t.jsx)("option",{value:"human",children:"Human"}),(0,t.jsx)("option",{value:"agent",children:"Agent"})]})]})]}),(0,t.jsx)("div",{className:"space-y-4",children:(u.data??[]).length===0?(0,t.jsx)("div",{className:"rounded-xl border border-dashed border-border px-4 py-8 text-sm text-muted-foreground",children:"No join requests match the current filters."}):u.data.map(f=>(0,t.jsxs)(sn,{className:"block p-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(lt,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(lt,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(lt,{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(eas,"JoinRequestQueue");var tas=(0,m.lazy)(()=>Wc(()=>import("./CompanyExport-fZQCAxR3.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]))),sas=(0,m.lazy)(()=>Wc(()=>import("./Agents.production-CQk3vdUE.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]))),nas=(0,m.lazy)(()=>Wc(()=>import("./Routines.production-BfGvfmpS.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]))),tpe=(0,m.lazy)(()=>Wc(()=>import("./RoutineDetail.production-Cgm2eWNX.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]))),ras=(0,m.lazy)(()=>Wc(()=>import("./CompanySkills.production-DZ9QO3Qb.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]))),aas=(0,m.lazy)(()=>Wc(()=>import("./CompanyActivity.production-CYOblDJ_.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]))),ias=(0,m.lazy)(()=>Wc(()=>import("./Costs.production-DGzfBw_5.js").then(e=>({default:e.Costs})),__vite__mapDeps([58,5,7,27,28,13,12,44,41,50,26,51,23,24]))),oas=(0,m.lazy)(()=>Wc(()=>import("./OrgChart.production-DKLPpvm-.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([59,5,7,8,9,10,11,12,13,26,45,46,51,23,24])));function u0({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(Dm,{}),children:e})}r(u0,"ProductionSurface");function las(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{index:!0,element:(0,t.jsx)(Nn,{to:"dashboard",replace:!0})}),(0,t.jsx)(st,{path:"dashboard",element:(0,t.jsx)(ONt,{})}),(0,t.jsx)(st,{path:"dashboard/live",element:(0,t.jsx)(FNt,{})}),(0,t.jsx)(st,{path:"timeline",element:e?(0,t.jsx)(Zp,{to:"/activity/timeline"}):(0,t.jsx)(b2e,{})}),(0,t.jsx)(st,{path:"onboarding",element:(0,t.jsx)(n4e,{})}),(0,t.jsx)(st,{path:"companies",element:(0,t.jsx)(SSt,{})}),(0,t.jsx)(st,{path:"company/settings",element:(0,t.jsx)(JKt,{})}),(0,t.jsx)(st,{path:"company/settings/environments",element:(0,t.jsx)(Nn,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(st,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(Nn,{to:"/company/export",replace:!0})}),(0,t.jsxs)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.members"}),children:[(0,t.jsx)(st,{path:"company/settings/members",element:(0,t.jsx)(vVt,{})}),(0,t.jsx)(st,{path:"company/settings/access",element:(0,t.jsx)(yVt,{})})]}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.invites"}),children:(0,t.jsx)(st,{path:"company/settings/invites",element:(0,t.jsx)(Nn,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.export"}),children:(0,t.jsx)(st,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(Dm,{}),children:(0,t.jsx)(tas,{})})})}),(0,t.jsx)(st,{element:(0,t.jsx)(Ydt,{}),children:(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.import"}),children:(0,t.jsx)(st,{path:"company/import",element:(0,t.jsx)(ens,{})})})}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.secrets"}),children:(0,t.jsx)(st,{path:"company/settings/secrets",element:(0,t.jsx)(Qts,{})})}),(0,t.jsx)(st,{path:"company/settings/tools",element:(0,t.jsx)(rpe,{})}),(0,t.jsx)(st,{path:"company/settings/tools/:tab",element:(0,t.jsx)(rpe,{})}),(0,t.jsx)(st,{path:"tools",element:(0,t.jsx)(ape,{})}),(0,t.jsx)(st,{path:"tools/:tab",element:(0,t.jsx)(ape,{})}),(0,t.jsx)(st,{path:"apps",element:(0,t.jsx)(hGt,{})}),(0,t.jsx)(st,{path:"apps/browse",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/connections",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/byo",element:(0,t.jsx)(SPe,{byoOnly:!0})}),(0,t.jsx)(st,{path:"apps/vercel-connect",element:(0,t.jsx)(spe,{credentialSource:"vercel_connect"})}),(0,t.jsx)(st,{path:"apps/connect",element:(0,t.jsx)(spe,{})}),(0,t.jsx)(st,{path:"apps/chat/connect",element:(0,t.jsx)(LB,{children:(0,t.jsx)(CQt,{})})}),(0,t.jsx)(st,{path:"apps/chat/:endpointId",element:(0,t.jsx)(LB,{children:(0,t.jsx)(Nn,{to:"settings",replace:!0})})}),(0,t.jsx)(st,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(LB,{children:(0,t.jsx)(PYt,{})})}),(0,t.jsx)(st,{path:"apps/connect/:appKey",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/review",element:(0,t.jsx)(zYt,{})}),(0,t.jsx)(st,{path:"apps/attention",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/gateways",element:(0,t.jsx)(ame,{})}),(0,t.jsx)(st,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(Nn,{to:"overview",replace:!0})}),(0,t.jsx)(st,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(gJt,{})}),(0,t.jsx)(st,{path:"apps/advanced",element:(0,t.jsx)(Aue,{})}),(0,t.jsx)(st,{path:"apps/advanced/gateways",element:(0,t.jsx)(ame,{})}),(0,t.jsx)(st,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(Mue,{mode:"new"})}),(0,t.jsx)(st,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(Mue,{mode:"edit"})}),(0,t.jsx)(st,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(FHt,{})}),(0,t.jsx)(st,{path:"apps/advanced/audit",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/advanced/:tab",element:(0,t.jsx)(Aue,{})}),(0,t.jsx)(st,{path:"apps/app/:applicationId",element:(0,t.jsx)(sme,{})}),(0,t.jsx)(st,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(sme,{})}),(0,t.jsx)(st,{path:"apps/:connectionId",element:(0,t.jsx)(Nn,{to:"permissions",replace:!0})}),(0,t.jsx)(st,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(BGt,{})}),(0,t.jsx)(st,{path:"company/settings/instance",element:(0,t.jsx)(Nn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.profile"}),children:(0,t.jsx)(st,{path:"company/settings/instance/profile",element:(0,t.jsx)(irs,{})})}),(0,t.jsx)(st,{path:"company/settings/instance/general",element:(0,t.jsx)(Nn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(st,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(Nn,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.environments"}),children:[(0,t.jsx)(st,{path:"company/settings/instance/environments",element:(0,t.jsx)(kB,{})}),(0,t.jsx)(st,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(kB,{mode:"create"})}),(0,t.jsx)(st,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(kB,{mode:"edit"})})]}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.access"}),children:(0,t.jsx)(st,{path:"company/settings/instance/access",element:(0,t.jsx)(Xns,{})})}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.experimental"}),children:(0,t.jsx)(st,{path:"company/settings/instance/experimental",element:(0,t.jsx)(Jns,{})})}),(0,t.jsxs)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(st,{path:"company/settings/instance/plugins",element:(0,t.jsx)(lrs,{})}),(0,t.jsx)(st,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(crs,{})})]}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.adapters"}),children:(0,t.jsx)(st,{path:"company/settings/instance/adapters",element:(0,t.jsx)(zhe,{})})}),(0,t.jsx)(st,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(mVt,{})}),(0,t.jsx)(st,{path:"skills/sources",element:(0,t.jsx)(Rme,{})}),(0,t.jsx)(st,{path:"skills/sources/:sourceId",element:(0,t.jsx)(Rme,{})}),(0,t.jsx)(st,{path:"skills/studio",element:(0,t.jsx)(QB,{})}),(0,t.jsx)(st,{path:"skills/studio/new",element:(0,t.jsx)(QB,{})}),(0,t.jsx)(st,{path:"skills/studio/:skillId",element:(0,t.jsx)(QB,{})}),(0,t.jsx)(st,{path:"skills/:skillId/studio",element:(0,t.jsx)(t4e,{})}),(0,t.jsx)(st,{path:"skills/*",element:e?(0,t.jsx)(EXt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(ras,{})})}),(0,t.jsx)(st,{path:"settings",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"settings/*",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"plugins/:pluginId",element:(0,t.jsx)(qhe,{})}),(0,t.jsx)(st,{path:"org",element:e?(0,t.jsx)(Nn,{to:"/agents/all",replace:!0}):(0,t.jsx)(u0,{children:(0,t.jsx)(oas,{})})}),(0,t.jsx)(st,{path:"agents",element:(0,t.jsx)(Nn,{to:"/agents/all",replace:!0})}),UV.map(a=>(0,t.jsx)(st,{path:`agents/${a}`,element:e?(0,t.jsx)(XSt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(sas,{})})},a)),(0,t.jsx)(st,{path:"agents/new",element:(0,t.jsx)(_rs,{})}),(0,t.jsx)(st,{path:"agents/:agentId",element:(0,t.jsx)(ZO,{})}),(0,t.jsx)(st,{path:"agents/:agentId/:tab",element:(0,t.jsx)(ZO,{})}),(0,t.jsx)(st,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(ZO,{})}),(0,t.jsx)(st,{path:"projects",element:(0,t.jsx)(mIt,{})}),(0,t.jsx)(st,{path:"projects/:projectId",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/overview",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/issues",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{element:(0,t.jsx)(nO,{}),children:(0,t.jsx)(st,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(W2t,{})})}),(0,t.jsx)(st,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/budget",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{element:(0,t.jsx)(nO,{}),children:(0,t.jsx)(st,{path:"workspaces",element:(0,t.jsx)(G2t,{})})}),(0,t.jsx)(st,{path:"issues",element:(0,t.jsx)(ZTt,{})}),(0,t.jsx)(st,{path:"tasks",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"search",element:(0,t.jsx)(CRt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"issues/all",element:(0,t.jsx)(ah,{view:"all"})}),(0,t.jsx)(st,{path:"issues/active",element:(0,t.jsx)(ah,{view:"active"})}),(0,t.jsx)(st,{path:"issues/backlog",element:(0,t.jsx)(ah,{view:"backlog"})}),(0,t.jsx)(st,{path:"issues/done",element:(0,t.jsx)(ah,{view:"done"})}),(0,t.jsx)(st,{path:"issues/recent",element:(0,t.jsx)(ah,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"issues/all",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"issues/active",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"issues/backlog",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"issues/done",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"issues/recent",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})})]}),(0,t.jsx)(st,{path:"chats",element:(0,t.jsx)(fMt,{})}),(0,t.jsx)(st,{path:"chats/:agentRef",element:(0,t.jsx)(gMt,{})}),(0,t.jsx)(st,{path:"issues/:issueId",element:(0,t.jsx)(dMt,{})}),null,(0,t.jsx)(st,{path:"routines",element:e?(0,t.jsx)(YMt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(nas,{})})}),(0,t.jsx)(st,{path:"cases",element:(0,t.jsx)(Ose,{children:(0,t.jsx)(xut,{})})}),(0,t.jsx)(st,{path:"cases/:caseIdentifier",element:(0,t.jsx)(Ose,{children:(0,t.jsx)(Zht,{})})}),(0,t.jsx)(st,{path:"pixels-office",element:(0,t.jsx)(Qdt,{children:(0,t.jsx)(_zt,{})})}),(0,t.jsx)(st,{path:"status",element:(0,t.jsx)(Fse,{children:(0,t.jsx)(Ile,{})})}),(0,t.jsx)(st,{path:"status/:cardId",element:(0,t.jsx)(Fse,{children:(0,t.jsx)(Ile,{})})}),(0,t.jsx)(st,{path:"status-cards",element:(0,t.jsx)(ipe,{})}),(0,t.jsx)(st,{path:"status-cards/:cardId",element:(0,t.jsx)(ipe,{})}),(0,t.jsx)(st,{path:"review-queue",element:(0,t.jsx)(e0,{children:(0,t.jsx)(pLt,{})})}),(0,t.jsx)(st,{path:"learnings",element:(0,t.jsx)(e0,{children:(0,t.jsx)(xLt,{})})}),(0,t.jsx)(st,{path:"pipelines",element:(0,t.jsx)(e0,{children:(0,t.jsx)(FF,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(FF,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(e0,{children:(0,t.jsx)(FF,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(e0,{children:(0,t.jsx)(c$t,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(MDt,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(RDt,{})})}),(0,t.jsx)(st,{path:"routines/:routineId",element:e?(0,t.jsx)(Tce,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(tpe,{})})}),(0,t.jsx)(st,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(Tce,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(tpe,{})})}),(0,t.jsx)(st,{element:(0,t.jsx)(nO,{}),children:(0,t.jsxs)(st,{element:(0,t.jsx)(Xdt,{}),children:[(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(hw,{})})]})}),(0,t.jsx)(st,{path:"goals",element:(0,t.jsx)(k6t,{})}),(0,t.jsx)(st,{path:"goals/:goalId",element:(0,t.jsx)(M6t,{})}),(0,t.jsx)(st,{path:"artifacts",element:(0,t.jsx)(Mce,{})}),(0,t.jsx)(st,{path:"approvals",element:(0,t.jsx)(Nn,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(st,{path:"approvals/pending",element:(0,t.jsx)(Lce,{})}),(0,t.jsx)(st,{path:"approvals/all",element:(0,t.jsx)(Lce,{})}),(0,t.jsx)(st,{path:"approvals/:approvalId",element:(0,t.jsx)(D6t,{})}),(0,t.jsx)(st,{path:"activity",element:e?(0,t.jsx)(wUt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(aas,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"activity/runs",element:(0,t.jsx)(JC,{section:"runs"})}),(0,t.jsx)(st,{path:"activity/costs",element:(0,t.jsx)(JC,{section:"costs"})}),(0,t.jsx)(st,{path:"activity/budgets",element:(0,t.jsx)(JC,{section:"budgets"})}),(0,t.jsx)(st,{path:"activity/timeline",element:(0,t.jsx)(JC,{section:"timeline"})}),(0,t.jsx)(st,{path:"audit",element:(0,t.jsx)(Zp,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(st,{path:"audit/activity",element:(0,t.jsx)(Zp,{to:"/activity"})}),(0,t.jsx)(st,{path:"audit/runs",element:(0,t.jsx)(Zp,{to:"/activity/runs"})}),(0,t.jsx)(st,{path:"audit/costs",element:(0,t.jsx)(Zp,{to:"/activity/costs"})}),(0,t.jsx)(st,{path:"audit/budgets",element:(0,t.jsx)(Zp,{to:"/activity/budgets"})}),(0,t.jsx)(st,{path:"audit/timeline",element:(0,t.jsx)(Zp,{to:"/activity/timeline"})}),(0,t.jsx)(st,{path:"runs",element:(0,t.jsx)(Zp,{to:"/activity/runs"})}),(0,t.jsx)(st,{path:"costs",element:(0,t.jsx)(Zp,{to:"/activity/costs"})}),(0,t.jsx)(st,{path:"budgets",element:(0,t.jsx)(Zp,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"costs",element:(0,t.jsx)(u0,{children:(0,t.jsx)(ias,{})})}),(0,t.jsx)(st,{path:"audit",element:(0,t.jsx)(Nn,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(st,{element:(0,t.jsx)(flt,{}),children:[(0,t.jsx)(st,{path:"board-chat",element:(0,t.jsx)(OKt,{})}),(0,t.jsx)(st,{path:"artifacts",element:(0,t.jsx)(Mce,{})})]}),null,(0,t.jsx)(st,{path:"decisions",element:(0,t.jsx)(cKt,{})}),(0,t.jsx)(st,{path:"decisions/queues/:key",element:(0,t.jsx)(hKt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"inbox",element:(0,t.jsx)(npe,{})}),(0,t.jsx)(st,{path:"inbox/mine",element:(0,t.jsx)(ah,{view:"mine"})}),(0,t.jsx)(st,{path:"inbox/recent",element:(0,t.jsx)(ah,{view:"recent"})}),(0,t.jsx)(st,{path:"inbox/unread",element:(0,t.jsx)(ah,{view:"unread"})}),(0,t.jsx)(st,{path:"inbox/blocked",element:(0,t.jsx)(ah,{view:"blocked"})}),(0,t.jsx)(st,{path:"inbox/all",element:(0,t.jsx)(ah,{view:"everything"})}),(0,t.jsx)(st,{path:"inbox/new",element:(0,t.jsx)(ah,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"inbox",element:(0,t.jsx)(npe,{})}),(0,t.jsx)(st,{path:"inbox/mine",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/recent",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/unread",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/blocked",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/all",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/new",element:(0,t.jsx)(Nn,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(st,{path:"inbox/requests",element:(0,t.jsx)(eas,{})}),(0,t.jsx)(st,{path:"u/:userSlug",element:(0,t.jsx)(Jqt,{})}),(0,t.jsx)(st,{path:"design-guide",element:(0,t.jsx)(Hns,{})}),(0,t.jsx)(st,{path:"instance/settings/adapters",element:(0,t.jsx)(zhe,{})}),(0,t.jsx)(st,{path:":pluginRoutePath/*",element:(0,t.jsx)(qhe,{})}),(0,t.jsx)(st,{path:"*",element:(0,t.jsx)(Eu,{scope:"board"})})]})}r(las,"boardRoutes");function spe({credentialSource:e="paperclip_vault"}={}){const s=ra(),n=new URLSearchParams(s.search),{enabled:a}=sS();return wat(n,{chatConnectorsEnabled:a})?(0,t.jsx)(SPe,{credentialSource:e}):(0,t.jsx)(Nn,{to:"/apps",replace:!0})}r(spe,"AppsConnectEntryRoute");function npe(){const{enabled:e}=fc(),{enabled:s}=VI();return e&&s?(0,t.jsx)(ah,{view:v$e(TJ())}):(0,t.jsx)(Nn,{to:`/inbox/${TJ()}`,replace:!0})}r(npe,"InboxRootRedirect");function ah({view:e}){const s=ra(),n=new URLSearchParams(s.search);return n.set(OR,e),(0,t.jsx)(Nn,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(ah,"TaskViewRedirect");function t4e(){const e=ra(),{companies:s,selectedCompany:n,loading:a}=gs(),{companyPrefix:i,skillId:o}=ga();if(a)return null;const l=(i?s.find(c=>c.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;return!l||!o?(0,t.jsx)(Nn,{to:"/skills/studio",replace:!0}):(0,t.jsx)(Nn,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(t4e,"LegacySkillStudioRedirect");function Iv(){const e=ra(),{companies:s,selectedCompany:n,loading:a}=gs(),{companyPrefix:i}=ga(),{hidden:o}=tu();if(a)return(0,t.jsx)(Dm,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return IW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(Nn,{to:"/onboarding",replace:!0}):(0,t.jsx)(CG,{});const c=IKe(nye(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(Nn,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(Iv,"LegacySettingsRedirect");function rpe(){const{tab:e}=ga();return(0,t.jsx)(Nn,{to:s4e(e),replace:!0})}r(rpe,"LegacyToolsSettingsRedirect");function ape(){const{tab:e}=ga();return(0,t.jsx)(Nn,{to:s4e(e),replace:!0})}r(ape,"LegacyToolsRedirect");function s4e(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(s4e,"legacyToolsRedirectTarget");function n4e(){const{companies:e}=gs(),{openOnboarding:s}=Do(),{t:n}=Rve(),a=Ac(),i=XSe(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=mM(),{companyPrefix:c}=ga(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(_it({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:N5(),companyId:d.id}):a&&i?Mm(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(n4e,"OnboardingRoutePage");function cas(){const{companies:e,selectedCompany:s,loading:n}=gs(),a=ra();if(n)return(0,t.jsx)(Dm,{});const i=s??e[0]??null;return i?(0,t.jsx)(Nn,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):IW({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(Nn,{to:"/onboarding",replace:!0}):(0,t.jsx)(CG,{})}r(cas,"CompanyRootRedirect");function ipe(){const{cardId:e}=ga(),s=b$e(),n=s?`/${s}`:"";return(0,t.jsx)(Nn,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(ipe,"StatusCardsLegacyRedirect");function Zp({to:e,forceAgentMode:s=!1}){const n=ra(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(Nn,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(Zp,"AuditCompatibilityRedirect");function va(){const e=ra(),{companies:s,selectedCompany:n,loading:a}=gs();if(a)return(0,t.jsx)(Dm,{});const i=n??s[0]??null;return i?(0,t.jsx)(Nn,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):IW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(Nn,{to:"/onboarding",replace:!0}):(0,t.jsx)(CG,{})}r(va,"UnprefixedBoardRedirect");function CG(){const{openOnboarding:e}=Do(),{t:s}=Rve(),n=Ac(),a=XSe(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?Mm(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(CG,"NoCompaniesStartPage");function das(){const{enabled:e,loaded:s}=fc(),{enabled:n}=VI();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(i$e,{children:[(0,t.jsx)(st,{path:"oauth-handoff",element:(0,t.jsx)(QYt,{})}),(0,t.jsx)(st,{path:"auth",element:(0,t.jsx)(Prs,{})}),(0,t.jsx)(st,{path:"board-claim/:token",element:(0,t.jsx)(Mrs,{})}),(0,t.jsx)(st,{path:"cli-auth/:id",element:(0,t.jsx)(Drs,{})}),(0,t.jsx)(st,{path:"invite/:token",element:(0,t.jsx)(qrs,{})}),(0,t.jsx)(st,{path:"s/:token",element:(0,t.jsx)(epe,{})}),(0,t.jsx)(st,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(epe,{})}),(0,t.jsx)(st,{element:s?(0,t.jsx)(Ene,{allowMembershipRequest:!0}):(0,t.jsx)(Dm,{}),children:(0,t.jsx)(st,{path:"chat-identity/confirm",element:(0,t.jsx)(FYt,{})})}),(0,t.jsx)(st,{path:"tests/perf/long-thread",element:(0,t.jsx)(IMt,{})}),(0,t.jsx)(st,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(lVt,{})}),(0,t.jsx)(st,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(cVt,{})}),(0,t.jsx)(st,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(uVt,{})}),(0,t.jsxs)(st,{element:s?(0,t.jsx)(Ene,{}):(0,t.jsx)(Dm,{}),children:[(0,t.jsx)(st,{index:!0,element:(0,t.jsx)(cas,{})}),(0,t.jsx)(st,{path:"onboarding",element:(0,t.jsx)(n4e,{})}),(0,t.jsx)(st,{path:"instance",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"instance/settings",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"instance/settings/*",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"companies",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"dashboard",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"inbox/*",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"issues",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"tasks",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"issues/:issueId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"routines",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"routines/:routineId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"review-queue",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"learnings",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"cases",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"cases/:caseIdentifier",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pixels-office",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"status",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"status/:cardId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"status-cards",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"status-cards/:cardId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"artifacts",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"audit",element:(0,t.jsx)(va,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"audit/*",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"activity",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"activity/*",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"runs",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"costs",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"budgets",element:(0,t.jsx)(va,{})})]}):null,(0,t.jsx)(st,{path:"decisions",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"u/:userSlug",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"skills/studio",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"skills/studio/new",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"skills/studio/:skillId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"skills/:skillId/studio",element:(0,t.jsx)(t4e,{})}),(0,t.jsx)(st,{path:"skills/*",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"settings",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"settings/*",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"agents",element:(0,t.jsx)(va,{})}),UV.map(a=>(0,t.jsx)(st,{path:`agents/${a}`,element:(0,t.jsx)(va,{})},a)),(0,t.jsx)(st,{path:"agents/new",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"agents/:agentId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"agents/:agentId/:tab",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/overview",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/issues",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/configuration",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"workspaces",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:":companyPrefix",element:e?(0,t.jsx)(Pot,{}):(0,t.jsx)(mlt,{}),children:las(e,n)}),(0,t.jsx)(st,{path:"*",element:(0,t.jsx)(Eu,{scope:"global"})})]})]}),(0,t.jsx)(Ipt,{}),(0,t.jsx)(hot,{})]})}r(das,"App");var uas=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){VSe(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 mas(){const{data:e}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return Wit(s,n),()=>{Vit()}},[s,n]),null}r(mas,"SentryGate");function has(e){let s=gg();tie(s),CU(s,e.userId);const n=STe(()=>{const o=gg();o!==s&&(s=o,tie(o),CU(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=gAt(o.data);l&&(l.type==="navigate"?e.navigate(l.url):fAt(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(has,"startNotificationRuntime");function pas(){const e=Ln(),s=(0,m.useRef)(e),{data:n}=X({queryKey:P.auth.session,queryFn:r(()=>La.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 has({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(pas,"NotificationRuntime");function fas(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(fas,"managedRoutineToRow");function xas({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=fas(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)(lEe,{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(xas,"ManagedRoutinesList");function ope(e){return new Set(e??[])}r(ope,"toPathSet");function gas({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(cj,{...l,selectedFile:n,expandedDirs:ope(e),checkedFiles:s?ope(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(gas,"PluginSdkFileTree");function bas(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return Wc(()=>import("./MarkdownEditor-BOTosEGR.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(bas,"PluginSdkMarkdownEditor");function vas(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(vas,"compactIssueFilters");function yas({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=Mt(),d=(0,m.useMemo)(()=>vas({...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}=X({queryKey:P.agents.list(e??"__no-company__"),queryFn:r(()=>Lt.list(e),"queryFn"),enabled:!!e}),{data:x}=X({queryKey:P.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>ma.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),b=P.liveRuns(e??"__no-company__"),v=bo({companyId:e,resourceKey:"live-runs",queryKey:b,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:j,dataUpdatedAt:N}=X({queryKey:b,queryFn:r(()=>Zr.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});vo(v,j,N);const{data:w,isLoading:k,error:S}=X({queryKey:p,queryFn:r(()=>At.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>yg(j,w),[w,j]),I=je({mutationFn:r(({id:T,data:R})=>At.update(T,R),"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)(cg,{issues:w??[],isLoading:k,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((T,R)=>I.mutate({id:T,data:R}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(yas,"PluginSdkIssuesList");function jas({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=z7(),f=e??p.companyId??null,{data:x}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),enabled:c}),b=x?.user?.id??x?.session?.userId??null,{data:v}=X({queryKey:P.agents.list(f??"__no-company__"),queryFn:r(()=>Lt.list(f),"queryFn"),enabled:!!f}),{data:j}=X({queryKey:P.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>hr.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),N=(0,m.useMemo)(()=>pz(),[]),w=(0,m.useMemo)(()=>N.map(T=>T.startsWith("agent:")?T.slice(6):null).filter(T=>!!T),[N]),k=(0,m.useMemo)(()=>cy((v??[]).filter(T=>d||T.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?Cfe(b):[],...c?BN(j?.users,{excludeUserIds:[b]}):[],...k.map(T=>({id:ph({assigneeAgentId:T.id}),label:T.name,searchText:`${T.name} ${T.role} ${T.title??""}`}))],[j?.users,b,c,k]),C=Bv(s),I=C.assigneeAgentId?k.find(T=>T.id===C.assigneeAgentId):null;return(0,m.createElement)(Au,{value:s,options:S,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(T=>{const R=Bv(T);R.assigneeAgentId&&ly(R.assigneeAgentId),R.assigneeUserId&&Z1(R.assigneeUserId),n(T,R)},"onChange"),renderTriggerValue:r(T=>T?I?(0,m.createElement)(QP,null,(0,m.createElement)(S5,{icon:I.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},T.label)):(0,m.createElement)("span",{className:"truncate"},T.label):(0,m.createElement)("span",{className:"text-muted-foreground"},a),"renderTriggerValue"),renderOption:r(T=>{if(!T.id)return(0,m.createElement)("span",{className:"truncate"},T.label);const R=Bv(T.id),A=R.assigneeAgentId?k.find(D=>D.id===R.assigneeAgentId):null;return(0,m.createElement)(QP,null,A?(0,m.createElement)(S5,{icon:A.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(Uc,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},T.label))},"renderOption")})}r(jas,"PluginSdkAssigneePicker");function was({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=z7(),p=e??h.companyId??null,{data:f}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:b}=X({queryKey:P.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>ma.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(b??[]).filter(S=>c||!S.archivedAt),[c,b]),{orderedProjects:j}=Gy({projects:v,companyId:p,userId:x}),N=(0,m.useMemo)(()=>dy(),[]),w=(0,m.useMemo)(()=>j.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[j]),k=j.find(S=>S.id===s)??null;return(0,m.createElement)(Au,{value:s,options:w,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&H0(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!k?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(QP,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)(QP,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(was,"PluginSdkProjectPicker");function QP({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(QP,"FragmentSafe");function kas({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(kas,"PluginSdkStatusBadge");function Nas({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(Nas,"PluginSdkDataTable");function Sas({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(Sas,"PluginSdkKeyValueList");function Cas({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(Cas,"PluginSdkMetricCard");function _as({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(_as,"PluginSdkJsonTree");function Ias({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(Ias,"PluginSdkSpinner");var Aas=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 Tas(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:$Ke,usePluginAction:OKe,useHostContext:z7,useHostLocation:BKe,useHostNavigation:FKe,usePluginStream:qKe,usePluginToast:zKe,copyTextToClipboard:ha,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(Rn,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:Cas,StatusBadge:kas,DataTable:Nas,KeyValueList:Sas,JsonTree:_as,Spinner:Ias,ErrorBoundary:Aas,MarkdownEditor:bas,FileTree:gas,IssuesList:yas,AssigneePicker:jas,ProjectPicker:was,ManagedRoutinesList:xas}}}r(Tas,"initPluginBridge");var Ras=1e4;function Eas(e=Ras){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(Eas,"startPerfMeasureReaper");var Pas=Oy((e=>{function s(q,U){var F=q.length;q.push(U);e:for(;0<F;){var K=F-1>>>1,G=q[K];if(0<i(G,U))q[K]=U,q[F]=G,F=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],F=q.pop();if(F!==U){q[0]=F;e:for(var K=0,G=q.length,se=G>>>1;K<se;){var ee=2*(K+1)-1,ne=q[ee],he=ee+1,Z=q[he];if(0>i(ne,F))he<G&&0>i(Z,ne)?(q[K]=Z,q[he]=F,K=he):(q[K]=ne,q[ee]=F,K=ee);else if(he<G&&0>i(Z,F))q[K]=Z,q[he]=F,K=he;else break e}}return U}r(a,"pop");function i(q,U){var F=q.sortIndex-U.sortIndex;return F!==0?F: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,$());else{var U=n(u);U!==null&&z(C,U.startTime-q)}}r(C,"handleTimeout");var I=!1,T=-1,R=5,A=-1;function D(){return j?!0:!(e.unstable_now()-A<R)}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(T),T=-1),x=!0;var F=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 G=K(p.expirationTime<=q);if(q=e.unstable_now(),typeof G=="function"){p.callback=G,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 se=n(u);se!==null&&z(C,se.startTime-q),U=!1}}break e}finally{p=null,f=F,x=!1}U=void 0}}finally{U?$():I=!1}}}r(M,"performWorkUntilDeadline");var $;if(typeof k=="function")$=r(function(){k(M)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var E=new MessageChannel,B=E.port2;E.port1.onmessage=M,$=r(function(){B.postMessage(null)},"schedulePerformWorkUntilDeadline")}else $=r(function(){N(M,0)},"schedulePerformWorkUntilDeadline");function z(q,U){T=N(function(){q(e.unstable_now())},U)}r(z,"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||(R=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 F=f;f=U;try{return q()}finally{f=F}},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 F=f;f=q;try{return U()}finally{f=F}},e.unstable_scheduleCallback=function(q,U,F){var K=e.unstable_now();switch(typeof F=="object"&&F!==null?(F=F.delay,F=typeof F=="number"&&0<F?K+F:K):F=K,q){case 1:var G=-1;break;case 2:G=250;break;case 5:G=1073741823;break;case 4:G=1e4;break;default:G=5e3}return G=F+G,q={id:h++,callback:U,priorityLevel:q,startTime:F,expirationTime:G,sortIndex:-1},F>K?(q.sortIndex=F,s(u,q),n(d)===null&&q===n(u)&&(v?(w(T),T=-1):v=!0,z(C,F-K))):(q.sortIndex=G,s(d,q),b||x||(b=!0,I||(I=!0,$()))),q},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(q){var U=f;return function(){var F=f;f=U;try{return q.apply(this,arguments)}finally{f=F}}}})),Mas=Oy(((e,s)=>{s.exports=Pas()})),Das=Oy((e=>{var s=Mas(),n=O8(),a=Ipe();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,O=y;;){var V=_.return;if(V===null)break;var J=V.alternate;if(J===null){if(O=V.return,O!==null){_=O;continue}break}if(V.child===J.child){for(J=V.child;J;){if(J===_)return u(V),g;if(J===O)return u(V),y;J=J.sibling}throw Error(i(188))}if(_.return!==O.return)_=V,O=J;else{for(var ve=!1,Be=V.child;Be;){if(Be===_){ve=!0,_=V,O=J;break}if(Be===O){ve=!0,O=V,_=J;break}Be=Be.sibling}if(!ve){for(Be=J.child;Be;){if(Be===_){ve=!0,_=J,O=V;break}if(Be===O){ve=!0,O=J,_=V;break}Be=Be.sibling}if(!ve)throw Error(i(189))}}if(_.alternate!==O)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"),T=Symbol.for("react.suspense_list"),R=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),D=Symbol.for("react.activity"),M=Symbol.for("react.memo_cache_sentinel"),$=Symbol.iterator;function E(g){return g===null||typeof g!="object"?null:(g=$&&g[$]||g["@@iterator"],typeof g=="function"?g:null)}r(E,"getIteratorFn");var B=Symbol.for("react.client.reference");function z(g){if(g==null)return null;if(typeof g=="function")return g.$$typeof===B?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 T: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 R:return y=g.displayName||null,y!==null?y:z(g.type)||"Memo";case A:y=g._payload,g=g._init;try{return z(g(y))}catch{}}return null}r(z,"getComponentNameFromType");var q=Array.isArray,U=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,F=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},G=[],se=-1;function ee(g){return{current:g}}r(ee,"createCursor");function ne(g){0>se||(g.current=G[se],G[se]=null,se--)}r(ne,"pop");function he(g,y){se++,G[se]=g.current,g.current=y}r(he,"push");var Z=ee(null),re=ee(null),ce=ee(null),H=ee(null);function Q(g,y){switch(he(ce,y),he(re,g),he(Z,null),y.nodeType){case 9:case 11:g=(g=y.documentElement)&&(g=g.namespaceURI)?TY(g):0;break;default:if(g=y.tagName,y=y.namespaceURI)y=TY(y),g=RY(y,g);else switch(g){case"svg":g=1;break;case"math":g=2;break;default:g=0}}ne(Z),he(Z,g)}r(Q,"pushHostContainer");function Y(){ne(Z),ne(re),ne(ce)}r(Y,"popHostContainer");function te(g){g.memoizedState!==null&&he(H,g);var y=Z.current,_=RY(y,g.type);y!==_&&(he(re,g),he(Z,_))}r(te,"pushHostContext");function ae(g){re.current===g&&(ne(Z),ne(re)),H.current===g&&(ne(H),LS._currentValue=K)}r(ae,"popHostContext");var me,oe;function ie(g){if(me===void 0)try{throw Error()}catch(_){var y=_.stack.trim().match(/\n( *(at )?)/);me=y&&y[1]||"",oe=-1<_.stack.indexOf(`
|
|
771
|
+
`)}U!==N&&(n.textContent=U,N=U)}r(T,"step");function R(){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(T))}r(R,"syncLoop");const A=new ResizeObserver(()=>{const E=Hhe(n);h=E.w,p=E.h,k(),R()});A.observe(n);const D=r(()=>{i=document.visibilityState!=="hidden",R()},"onVisibilityChange");document.addEventListener("visibilitychange",D);const M=r(()=>{R()},"onMotionChange");a.addEventListener("change",M);const $=Hhe(n);return h=$.w,p=$.h,k(),R(),()=>{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(Rrs,"AsciiArtAnimation");function Ers({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(Ers,"PaperclipLockup");function Prs(){const e=Mt(),s=Ln(),[n]=hi(),[a,i]=(0,m.useState)("sign_in"),[o,l]=(0,m.useState)(""),[c,d]=(0,m.useState)(""),[u,h]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),x="auth-error",b=(0,m.useMemo)(()=>ZSe(n.get("next")||Irs()||"/"),[n]),v=X({queryKey:P.health,queryFn:r(()=>su.get(),"queryFn"),retry:!1}),{data:j,isLoading:N,error:w}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1});(0,m.useEffect)(()=>{j&&(tV(),s(b,{replace:!0}))},[j,s,b]);const k=je({mutationFn:r(async()=>{if(a==="sign_in"){await La.signInEmail({email:c.trim(),password:u});return}await La.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)(Dm,{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)(sV,{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)(hk,{})}),(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)(Ers,{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)(Rrs,{})})]})}r(Prs,"AuthPage");function Mrs(){const e=Mt(),s=ga(),[n]=hi(),a=(s.token??"").trim(),i=(n.get("code")??"").trim(),o=(0,m.useMemo)(()=>`/board-claim/${encodeURIComponent(a)}${i?`?code=${encodeURIComponent(i)}`:""}`,[a,i]),l=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),c=X({queryKey:["board-claim",a,i],queryFn:r(()=>hr.getBoardClaimStatus(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>hr.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)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Claim challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const u=c.data;return u?u.status==="claimed"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Board ownership claimed"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This instance is now linked to your authenticated user."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:"/",children:"Open board"})})]})}):l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Claim Board ownership"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"This will promote your user to instance admin and migrate organization ownership access from local trusted mode."}),d.error&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive",children:d.error instanceof Error?d.error.message:"Failed to claim board ownership"}),(0,t.jsx)(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)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to claim Board ownership."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Claim challenge unavailable."})}r(Mrs,"BoardClaimPage");function Drs(){const e=Mt(),s=ga(),[n]=hi(),a=(s.id??"").trim(),i=(n.get("token")??"").trim(),o=(0,m.useMemo)(()=>`/cli-auth/${encodeURIComponent(a)}${i?`?token=${encodeURIComponent(i)}`:""}`,[a,i]),l=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),c=X({queryKey:["cli-auth-challenge",a,i],queryFn:r(()=>hr.getCliAuthChallenge(a,i),"queryFn"),enabled:a.length>0&&i.length>0,retry:!1}),d=je({mutationFn:r(()=>hr.approveCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await e.invalidateQueries({queryKey:P.auth.session}),await c.refetch()},"onSuccess")}),u=je({mutationFn:r(()=>hr.cancelCliAuthChallenge(a,i),"mutationFn"),onSuccess:r(async()=>{await c.refetch()},"onSuccess")});if(!a||!i)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-destructive",children:"Invalid CLI auth URL."});if(l.isLoading||c.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading CLI auth challenge..."});if(c.error)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"CLI auth challenge unavailable"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:c.error instanceof Error?c.error.message:"Challenge is invalid or expired."})]})});const h=c.data;return h?h.status==="approved"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"CLI access approved"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"The Paperclip CLI can now finish authentication on the requesting machine."}),(0,t.jsxs)("p",{className:"mt-4 text-sm text-muted-foreground",children:["Command: ",(0,t.jsx)("span",{className:"font-mono text-foreground",children:h.command})]})]})}):h.status==="cancelled"||h.status==="expired"?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:h.status==="expired"?"CLI auth challenge expired":"CLI auth challenge cancelled"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Start the CLI auth flow again from your terminal to generate a new approval request."})]})}):h.requiresSignIn||!l.data?(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Sign in required"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sign in or create an account, then return to this page to approve the CLI access request."}),(0,t.jsx)(L,{asChild:!0,className:"mt-4",children:(0,t.jsx)(We,{to:`/auth?next=${encodeURIComponent(o)}`,children:"Sign in / Create account"})})]})}):(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10",children:(0,t.jsxs)(sn,{className:"block p-6",children:[(0,t.jsx)("h1",{className:"text-xl font-semibold",children:"Approve Paperclip CLI access"}),(0,t.jsx)("p",{className:"mt-2 text-sm text-muted-foreground",children:"A local Paperclip CLI process is requesting board access to this instance."}),(0,t.jsxs)("div",{className:"mt-5 space-y-3 text-sm",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Command"}),(0,t.jsx)("div",{className:"font-mono text-foreground",children:h.command})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Client"}),(0,t.jsx)("div",{className:"text-foreground",children:h.clientName??"paperclip-pro cli"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested access"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedAccess==="instance_admin_required"?"Instance admin":"Board"})]}),h.requestedCompanyName&&(0,t.jsxs)("div",{children:[(0,t.jsx)("div",{className:"text-muted-foreground",children:"Requested organization"}),(0,t.jsx)("div",{className:"text-foreground",children:h.requestedCompanyName})]})]}),(d.error||u.error)&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:(d.error??u.error)instanceof Error?(d.error??u.error).message:"Failed to update CLI auth challenge"}),!h.canApprove&&(0,t.jsx)("p",{className:"mt-4 text-sm text-destructive",children:"This challenge requires instance-admin access. Sign in with an instance admin account to approve it."}),(0,t.jsxs)("div",{className:"mt-5 flex gap-3",children:[(0,t.jsx)(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(Drs,"CliAuthPage");var Lrs=wLe.filter(e=>e!=="paperclip_runner"),Ghe=new Set(["claude_local","codex_local","gemini_local","kimi_local","opencode_local","pi_local","cursor"]);function $rs(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($rs,"readNestedString");var vw="w-full border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100 outline-none focus:border-zinc-500",Qhe="border border-zinc-800 bg-zinc-950/95 p-6",Yhe="flex-1 border px-3 py-2 text-sm transition-colors";function Ors(e){return e?e.charAt(0).toUpperCase()+e.slice(1):null}r(Ors,"formatHumanRole");function ZMe(e){if(!e||typeof e!="object")return null;const s=e.code;return typeof s=="string"&&s.trim().length>0?s:null}r(ZMe,"getAuthErrorCode");function Frs(e){if(!(e instanceof Error))return null;const s=e.message.trim();return s.length>0?s:null}r(Frs,"getAuthErrorMessage");function Brs(e,s,n){const a=ZMe(e),i=Frs(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(Brs,"mapInviteAuthFeedback");function Jhe(e){return!!(e&&typeof e=="object"&&"bootstrapAccepted"in e)}r(Jhe,"isBootstrapAcceptancePayload");function zrs(e,s){return!e||typeof e!="object"||s?!1:e.status==="approved"}r(zrs,"isApprovedHumanJoinPayload");function M8({companyDisplayName:e,companyLogoUrl:s,className:n}){return(0,t.jsx)(GN,{companyName:e,logoUrl:s,logoFit:"contain",className:n})}r(M8,"InviteCompanyLogo");function Xhe({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)(M8,{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(Xhe,"AwaitingJoinApprovalPanel");function qrs(){const e=Mt(),s=Ln(),{setSelectedCompanyId:n}=gs(),a=(ga().token??"").trim(),[i,o]=(0,m.useState)("sign_up"),[l,c]=(0,m.useState)(""),[d,u]=(0,m.useState)(""),[h,p]=(0,m.useState)(""),[f,x]=(0,m.useState)(""),[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,T]=(0,m.useState)(null),[R,A]=(0,m.useState)(!1),D="invite-auth-error",M=X({queryKey:P.health,queryFn:r(()=>su.get(),"queryFn"),retry:!1}),$=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),E=X({queryKey:P.access.invite(a),queryFn:r(()=>hr.getInvite(a),"queryFn"),enabled:a.length>0,retry:!1}),B=U8({enabled:!!$.data&&!!E.data?.companyId,staleTime:0}),z=M.data?.deploymentMode!=="local_trusted"?B.isFetchedAfterMount:!0,q=z?B.data?.companies??[]:[];(0,m.useEffect)(()=>{a&&Whe(a)},[a]),(0,m.useEffect)(()=>{A(!1)},[a]),(0,m.useEffect)(()=>{if(!z)return;const ge=B.data?.companies;!ge||!E.data?.companyId||ge.some(be=>be.id===E.data.companyId)&&MR(a)},[B.data,E.data,z,a]);const U=E.data,F=!!$.data&&!!U?.companyId&&!z,K=!!U?.companyId&&q.some(ge=>ge.id===U?.companyId),G=U?.companyName?.trim()||"this Paperclip company",se=U?.companyLogoUrl?.trim()||null,ee=U?.invitedByUserName?.trim()||null,ne=U?.inviteMessage?.trim()||null,he=Ors(U?.humanRole),Z=U?.joinRequestStatus??null,re=U?.joinRequestType??null,ce=re==="human"&&(Z==="pending_approval"||Z==="approved"),H=M.data?.deploymentMode==="authenticated"&&!$.data&&U?.allowedJoinTypes!=="agent",Q=U?.inviteType!=="bootstrap_ceo"&&U?.allowedJoinTypes==="agent",Y=!!$.data&&!Q&&U?.inviteType!=="bootstrap_ceo"&&(!Z||ce)&&!F&&!K&&!w&&S===null,te=$.data?.user.name?.trim()||$.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),me=je({mutationFn:r(async()=>{if(!U)throw new Error("Invite not found");if(F)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"?hr.acceptInvite(a,{requestType:"human"}):hr.acceptInvite(a,{requestType:"agent",agentName:f.trim(),adapterType:b,capabilities:j.trim()||null})},"mutationFn"),onSuccess:r(async ge=>{C(null),MR(a);const be=Jhe(ge);k({kind:be?"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&&zrs(ge,Q)&&(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)(()=>{!Y||R||me.isPending||(A(!0),C(null),me.mutate())},[me,R,Y]);const oe=je({mutationFn:r(async()=>{if(i==="sign_in"){await La.signInEmail({email:d.trim(),password:h});return}await La.signUpEmail({name:l.trim(),email:d.trim(),password:h})},"mutationFn"),onSuccess:r(async()=>{T(null),Whe(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 UDe(e);if(U?.companyId&&ge.some(be=>be.id===U.companyId)){MR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}if(!(!U||U.inviteType!=="bootstrap_ceo"))try{Jhe(await me.mutateAsync())&&s("/",{replace:!0})}catch{return}},"onSuccess"),onError:r(ge=>{const be=Brs(ge,i,d);ZMe(ge)==="USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL"&&(o("sign_in"),p("")),T(be)},"onError")}),ie=(0,m.useMemo)(()=>U?K?"Open organization":U.inviteType==="bootstrap_ceo"?"Accept invite":Q?"Submit request":$.data?"Accept invite":"Continue":"Continue",[U,K,$.data,Q]);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||$.isLoading)return(0,t.jsx)("div",{className:"mx-auto max-w-xl py-10 text-sm text-muted-foreground",children:"Loading invite..."});if(F)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(Z==="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(Z==="pending_approval"&&!ce)return(0,t.jsx)(Xhe,{companyDisplayName:G,companyLogoUrl:se,invitedByUserName:ee});if(Z&&!ce)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:Z==="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)(We,{to:"/",children:"Open board"})})})]})});if(w?.kind==="join"){const ge=w.payload,be=typeof ge.claimSecret=="string"?ge.claimSecret:null,le=typeof ge.claimApiKeyPath=="string"?ge.claimApiKeyPath:null,ue=$rs(ge.onboarding,["textInstructions","url"]);return!Q&&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)(M8,{companyDisplayName:G,companyLogoUrl:se,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)(We,{to:"/",children:"Open board"})})})]})}):(0,t.jsx)(Xhe,{companyDisplayName:G,companyLogoUrl:se,invitedByUserName:ee,claimSecret:be,claimApiKeyPath:le,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:`${Qhe} space-y-6`,children:[(0,t.jsxs)("div",{className:"flex items-start gap-4",children:[(0,t.jsx)(M8,{companyDisplayName:G,companyLogoUrl:se,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 ${G}`}),(0,t.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-zinc-300",children:Q?"Review the invite details, then submit the agent information below to start the join request.":H?"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:G})]}),(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:ee??"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:Q?"Agent join request":he??"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,$.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:`${Qhe} h-fit`,children:Q?(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 ",G,"."]})]}),(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:vw,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:vw,value:b,onChange:r(ge=>v(ge.target.value),"onChange"),children:Lrs.map(ge=>(0,t.jsxs)("option",{value:ge,disabled:!Ghe.has(ge),children:[qf(ge),Ghe.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:vw,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:me.isPending||f.trim().length===0,onClick:r(()=>me.mutate(),"onClick"),children:me.isPending?"Working...":ie})]}):H?(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 ${G}.`:"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:`${Yhe} ${i==="sign_up"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{T(null),o("sign_up")},"onClick"),children:"Create account"}),(0,t.jsx)("button",{type:"button",className:`${Yhe} ${i==="sign_in"?"border-zinc-100 bg-zinc-100 text-zinc-950":"border-zinc-800 text-zinc-300 hover:border-zinc-600"}`,onClick:r(()=>{T(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(),!oe.isPending){if(!ae){T({tone:"error",message:"Please fill in all required fields."});return}oe.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:vw,value:l,onChange:r(ge=>{c(ge.target.value),T(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:vw,value:d,onChange:r(ge=>{u(ge.target.value),T(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:vw,value:h,onChange:r(ge=>{p(ge.target.value),T(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:oe.isPending,"aria-disabled":!ae||oe.isPending,children:oe.isPending?"Working...":i==="sign_in"?"Sign in and continue":"Create account and continue"})]}),(0,t.jsx)("p",{className:"text-xs leading-5 text-zinc-500",children:i==="sign_up"?"Already signed up before? Use the existing-account option instead so the invite lands on the right Paperclip user.":"No account yet? Switch back to create account so you can accept the invite with a new login."})]}):(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:K?"Already in this organization":Y?"Completing organization access":U.inviteType==="bootstrap_ceo"?"Accept bootstrap invite":"Accept organization invite"}),(0,t.jsx)("p",{className:"mt-1 text-sm text-zinc-400",children:Y?`Granting your access to ${G}.`:K?`This account already belongs to ${G}.`:`This will ${U.inviteType==="bootstrap_ceo"?"finish setting up Paperclip":`grant or complete your access to ${G}`}.`})]}),S?(0,t.jsx)("p",{className:"text-xs text-red-400",children:S}):null,Y?(0,t.jsx)("div",{className:"text-sm text-zinc-400",children:me.isPending?"Submitting request...":"Finishing sign-in..."}):(0,t.jsx)(L,{className:"w-full rounded-none",disabled:me.isPending,onClick:r(()=>{if(K&&U.companyId){MR(a),n(U.companyId,{source:"manual"}),s("/",{replace:!0});return}me.mutate()},"onClick"),children:me.isPending?"Working...":ie})]})})]})})})}r(qrs,"InviteLandingPage");var Urs=15e3,Krs={parent:"Parent task",child:"Sub-task",blocked_by:"Blocked by",blocks:"Blocks"};function Wrs(){(0,m.useEffect)(()=>{const e=document.createElement("meta");return e.name="robots",e.content="noindex",document.head.appendChild(e),()=>e.remove()},[])}r(Wrs,"useNoIndexMeta");function D8(e,s){const n=`/s/${encodeURIComponent(e)}`;return s?`${n}/issues/${encodeURIComponent(s)}`:n}r(D8,"sharePath");var Vrs=/^(?:https?:\/\/[^/]+)?\/api\/attachments\/([^/?#]+)\/content(?:[?#].*)?$/i;function Hrs(e,s){const n=Vrs.exec(s.trim());return n?`/api/public/share/${encodeURIComponent(e)}/attachments/${n[1]}/content`:null}r(Hrs,"publicShareImageSrc");function TC({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(TC,"Section");function L8({actor:e}){return(0,t.jsx)(Bl,{name:e.name,avatarUrl:e.iconUrl,size:"sm"})}r(L8,"ActorIdentity");function $8({value:e}){return(0,t.jsx)("time",{dateTime:e,title:Lr(e),className:"text-xs text-muted-foreground",children:or(e)})}r($8,"Timestamp");function Grs({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(Grs,"ActiveRunPill");function e4e({attachments:e}){return(0,t.jsx)(p9,{children:e.map(s=>{const n=Rje({name:s.filename,url:s.url,contentType:s.contentType,byteSize:s.byteSize}),a=n.icon,i=f9(s.byteSize);return(0,t.jsxs)(c9,{size:"sm",children:[(0,t.jsx)(d9,{children:(0,t.jsx)(a,{"aria-hidden":!0})}),(0,t.jsxs)(u9,{children:[(0,t.jsx)(m9,{className:"max-w-48",children:s.filename}),(0,t.jsx)(h9,{className:"max-w-48",children:i?`${n.label} · ${i}`:n.label})]}),(0,t.jsx)(_je,{"aria-label":`Download ${s.filename}`,render:(0,t.jsx)("a",{href:s.url,download:s.filename,rel:"noreferrer"})})]},s.id)})})}r(e4e,"AttachmentList");function Qrs({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)(Wi,{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:Krs[e.relation]}),e.navigable?(0,t.jsx)(rd,{to:n?D8(s,e.id):D8(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(Qrs,"RelatedIssueRow");function Yrs({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)(L8,{actor:e.author}),(0,t.jsx)($8,{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)(L8,{actor:e.author}),(0,t.jsx)($8,{value:e.createdAt})]}),(0,t.jsx)(Rn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:s,children:e.body}),e.attachments.length>0?(0,t.jsx)(e4e,{attachments:e.attachments}):null]})}r(Yrs,"TimelineEntry");function Jrs({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)(Wa,{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)($8,{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)(oo,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download PDF"]}),(0,t.jsx)(Rn,{className:"text-sm",linkIssueReferences:!1,resolveImageSrc:s,children:e.body})]})]})}r(Jrs,"DocumentCard");function Xrs({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)(qn,{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)(oo,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Download"]}):null]})}r(Xrs,"WorkProductRow");function Zhe({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(Zhe,"CenteredNotice");function Zrs({view:e,token:s}){const{company:n,issue:a}=e,i=(0,m.useCallback)(o=>Hrs(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)(GN,{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)(rd,{to:D8(s),className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground",children:[(0,t.jsx)(gl,{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)(Zh,{status:a.status}),(0,t.jsx)(Rfe,{priority:a.priority,showLabel:!0}),a.assignee?(0,t.jsx)(L8,{actor:a.assignee}):null,e.activeRun?(0,t.jsx)(Grs,{agentName:e.activeRun.agentName}):null]}),(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Created ",Lr(a.createdAt)," · Updated ",or(a.updatedAt),a.completedAt?` · Completed ${Lr(a.completedAt)}`:""]})]}),a.description?(0,t.jsx)(Rn,{className:"text-sm",softBreaks:!0,linkIssueReferences:!1,resolveImageSrc:i,children:a.description}):null,e.related.length>0?(0,t.jsx)(TC,{title:"Related tasks",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.related.map(o=>(0,t.jsx)(Qrs,{related:o,token:s,isSharedRoot:e.isSharedRoot},`${o.relation}:${o.id}`))})}):null,e.documents.length>0?(0,t.jsx)(TC,{title:"Documents",children:(0,t.jsx)("div",{className:"space-y-2",children:e.documents.map(o=>(0,t.jsx)(Jrs,{document:o,resolveImageSrc:i},o.key))})}):null,e.attachments.length>0?(0,t.jsx)(TC,{title:"Attachments",children:(0,t.jsx)(e4e,{attachments:e.attachments})}):null,e.workProducts.length>0?(0,t.jsx)(TC,{title:"Work products",children:(0,t.jsx)("ul",{className:"space-y-2",children:e.workProducts.map(o=>(0,t.jsx)(Xrs,{product:o},o.id))})}):null,(0,t.jsx)(TC,{title:"Activity",children:e.comments.length>0?(0,t.jsx)("ol",{className:"space-y-3",children:e.comments.map(o=>(0,t.jsx)(Yrs,{comment:o,resolveImageSrc:i},o.id))}):(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:"No updates yet."})})]})]})}r(Zrs,"PublicIssueShareContent");function epe(){const{token:e="",issueId:s}=ga();Wrs();const n=NBe.test(e),a=X({queryKey:P.publicShare.view(e,s??null),queryFn:r(()=>s?_k.getPublicShareIssue(e,s):_k.getPublicShare(e),"queryFn"),enabled:n,retry:!1,refetchOnWindowFocus:!0,refetchInterval:r(i=>i.state.data?.activeRun?Urs:!1,"refetchInterval")});return!n||a.data===null?(0,t.jsx)(Zhe,{title:"This link is not available",body:"It may have been revoked, or the address is incomplete."}):a.data?(0,t.jsx)(Zrs,{view:a.data,token:e}):a.isError?(0,t.jsx)(Zhe,{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)(gn,{className:"h-6 w-1/2"}),(0,t.jsx)(gn,{className:"h-4 w-1/3"}),(0,t.jsx)(gn,{className:"h-24 w-full"})]})})}r(epe,"PublicIssueSharePage");function eas(){const{selectedCompany:e,selectedCompanyId:s}=gs(),{setBreadcrumbs:n}=Fn(),{pushToast:a}=pi(),i=Mt(),[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=X({queryKey:P.access.joinRequests(s??"",`${o}:${c}`),queryFn:r(()=>hr.listJoinRequests(s,o,c==="all"?void 0:c),"queryFn"),enabled:!!s}),h=je({mutationFn:r(f=>hr.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=>hr.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 un&&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)(Yze,{className:"h-5 w-5 text-muted-foreground"}),(0,t.jsx)("h1",{className:"text-lg font-semibold",children:"Join Request Queue"})]}),(0,t.jsx)("p",{className:"max-w-3xl text-sm text-muted-foreground",children:"Review human and agent join requests outside the mixed inbox feed. This queue uses the same approval mutations as the inline inbox cards."})]}),(0,t.jsxs)(sn,{className:"flex-row flex-wrap gap-3 p-4",children:[(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Status"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:o,onChange:r(f=>l(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"pending_approval",children:"Pending approval"}),(0,t.jsx)("option",{value:"approved",children:"Approved"}),(0,t.jsx)("option",{value:"rejected",children:"Rejected"})]})]}),(0,t.jsxs)("label",{className:"space-y-2 text-sm",children:[(0,t.jsx)("span",{className:"font-medium",children:"Request type"}),(0,t.jsxs)("select",{className:"rounded-md border border-border bg-background px-3 py-2",value:c,onChange:r(f=>d(f.target.value),"onChange"),children:[(0,t.jsx)("option",{value:"all",children:"All"}),(0,t.jsx)("option",{value:"human",children:"Human"}),(0,t.jsx)("option",{value:"agent",children:"Agent"})]})]})]}),(0,t.jsx)("div",{className:"space-y-4",children:(u.data??[]).length===0?(0,t.jsx)("div",{className:"rounded-xl border border-dashed border-border px-4 py-8 text-sm text-muted-foreground",children:"No join requests match the current filters."}):u.data.map(f=>(0,t.jsxs)(sn,{className:"block p-4",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(lt,{variant:f.status==="pending_approval"?"secondary":f.status==="approved"?"outline":"destructive",children:f.status.replace("_"," ")}),(0,t.jsx)(lt,{variant:"outline",children:f.requestType}),f.adapterType?(0,t.jsx)(lt,{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(eas,"JoinRequestQueue");var tas=(0,m.lazy)(()=>Wc(()=>import("./CompanyExport-D6Hn27B_.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]))),sas=(0,m.lazy)(()=>Wc(()=>import("./Agents.production-DonAKR8K.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]))),nas=(0,m.lazy)(()=>Wc(()=>import("./Routines.production-BxvC3L7v.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]))),tpe=(0,m.lazy)(()=>Wc(()=>import("./RoutineDetail.production-Qq6ShQm5.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]))),ras=(0,m.lazy)(()=>Wc(()=>import("./CompanySkills.production-NS3jGhDW.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]))),aas=(0,m.lazy)(()=>Wc(()=>import("./CompanyActivity.production-DSbPGLZv.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]))),ias=(0,m.lazy)(()=>Wc(()=>import("./Costs.production-Dv0d-Z6H.js").then(e=>({default:e.Costs})),__vite__mapDeps([58,5,7,27,28,13,12,44,41,50,26,51,23,24]))),oas=(0,m.lazy)(()=>Wc(()=>import("./OrgChart.production-DieTRMth.js").then(e=>({default:e.OrgChart})),__vite__mapDeps([59,5,7,8,9,10,11,12,13,26,45,46,51,23,24])));function u0({children:e}){return(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(Dm,{}),children:e})}r(u0,"ProductionSurface");function las(e,s){const n=e&&s;return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{index:!0,element:(0,t.jsx)(Nn,{to:"dashboard",replace:!0})}),(0,t.jsx)(st,{path:"dashboard",element:(0,t.jsx)(ONt,{})}),(0,t.jsx)(st,{path:"dashboard/live",element:(0,t.jsx)(FNt,{})}),(0,t.jsx)(st,{path:"timeline",element:e?(0,t.jsx)(Zp,{to:"/activity/timeline"}):(0,t.jsx)(b2e,{})}),(0,t.jsx)(st,{path:"onboarding",element:(0,t.jsx)(n4e,{})}),(0,t.jsx)(st,{path:"companies",element:(0,t.jsx)(SSt,{})}),(0,t.jsx)(st,{path:"company/settings",element:(0,t.jsx)(JKt,{})}),(0,t.jsx)(st,{path:"company/settings/environments",element:(0,t.jsx)(Nn,{to:"/company/settings/instance/environments",replace:!0})}),(0,t.jsx)(st,{path:"company/settings/cloud-upstream",element:(0,t.jsx)(Nn,{to:"/company/export",replace:!0})}),(0,t.jsxs)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.members"}),children:[(0,t.jsx)(st,{path:"company/settings/members",element:(0,t.jsx)(vVt,{})}),(0,t.jsx)(st,{path:"company/settings/access",element:(0,t.jsx)(yVt,{})})]}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.invites"}),children:(0,t.jsx)(st,{path:"company/settings/invites",element:(0,t.jsx)(Nn,{to:"/company/settings/members?tab=invites",replace:!0})})}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.export"}),children:(0,t.jsx)(st,{path:"company/export/*",element:(0,t.jsx)(m.Suspense,{fallback:(0,t.jsx)(Dm,{}),children:(0,t.jsx)(tas,{})})})}),(0,t.jsx)(st,{element:(0,t.jsx)(Ydt,{}),children:(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.import"}),children:(0,t.jsx)(st,{path:"company/import",element:(0,t.jsx)(ens,{})})})}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"company.secrets"}),children:(0,t.jsx)(st,{path:"company/settings/secrets",element:(0,t.jsx)(Qts,{})})}),(0,t.jsx)(st,{path:"company/settings/tools",element:(0,t.jsx)(rpe,{})}),(0,t.jsx)(st,{path:"company/settings/tools/:tab",element:(0,t.jsx)(rpe,{})}),(0,t.jsx)(st,{path:"tools",element:(0,t.jsx)(ape,{})}),(0,t.jsx)(st,{path:"tools/:tab",element:(0,t.jsx)(ape,{})}),(0,t.jsx)(st,{path:"apps",element:(0,t.jsx)(hGt,{})}),(0,t.jsx)(st,{path:"apps/browse",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/connections",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/byo",element:(0,t.jsx)(SPe,{byoOnly:!0})}),(0,t.jsx)(st,{path:"apps/vercel-connect",element:(0,t.jsx)(spe,{credentialSource:"vercel_connect"})}),(0,t.jsx)(st,{path:"apps/connect",element:(0,t.jsx)(spe,{})}),(0,t.jsx)(st,{path:"apps/chat/connect",element:(0,t.jsx)(LB,{children:(0,t.jsx)(CQt,{})})}),(0,t.jsx)(st,{path:"apps/chat/:endpointId",element:(0,t.jsx)(LB,{children:(0,t.jsx)(Nn,{to:"settings",replace:!0})})}),(0,t.jsx)(st,{path:"apps/chat/:endpointId/:tab",element:(0,t.jsx)(LB,{children:(0,t.jsx)(PYt,{})})}),(0,t.jsx)(st,{path:"apps/connect/:appKey",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/connect/:appKey/:stage",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/review",element:(0,t.jsx)(zYt,{})}),(0,t.jsx)(st,{path:"apps/attention",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/gateways",element:(0,t.jsx)(ame,{})}),(0,t.jsx)(st,{path:"apps/gateways/:gatewayId",element:(0,t.jsx)(Nn,{to:"overview",replace:!0})}),(0,t.jsx)(st,{path:"apps/gateways/:gatewayId/:tab",element:(0,t.jsx)(gJt,{})}),(0,t.jsx)(st,{path:"apps/advanced",element:(0,t.jsx)(Aue,{})}),(0,t.jsx)(st,{path:"apps/advanced/gateways",element:(0,t.jsx)(ame,{})}),(0,t.jsx)(st,{path:"apps/advanced/profiles/new",element:(0,t.jsx)(Mue,{mode:"new"})}),(0,t.jsx)(st,{path:"apps/advanced/profiles/:profileId/edit",element:(0,t.jsx)(Mue,{mode:"edit"})}),(0,t.jsx)(st,{path:"apps/advanced/profiles/:profileId",element:(0,t.jsx)(FHt,{})}),(0,t.jsx)(st,{path:"apps/advanced/audit",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/advanced/run-your-own",element:(0,t.jsx)(Nn,{to:"/apps",replace:!0})}),(0,t.jsx)(st,{path:"apps/advanced/:tab",element:(0,t.jsx)(Aue,{})}),(0,t.jsx)(st,{path:"apps/app/:applicationId",element:(0,t.jsx)(sme,{})}),(0,t.jsx)(st,{path:"apps/app/:applicationId/:tab",element:(0,t.jsx)(sme,{})}),(0,t.jsx)(st,{path:"apps/:connectionId",element:(0,t.jsx)(Nn,{to:"permissions",replace:!0})}),(0,t.jsx)(st,{path:"apps/:connectionId/:tab",element:(0,t.jsx)(BGt,{})}),(0,t.jsx)(st,{path:"company/settings/instance",element:(0,t.jsx)(Nn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.profile"}),children:(0,t.jsx)(st,{path:"company/settings/instance/profile",element:(0,t.jsx)(irs,{})})}),(0,t.jsx)(st,{path:"company/settings/instance/general",element:(0,t.jsx)(Nn,{to:"/company/settings",replace:!0})}),(0,t.jsx)(st,{path:"company/settings/instance/heartbeats",element:(0,t.jsx)(Nn,{to:"/company/settings",replace:!0})}),(0,t.jsxs)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.environments"}),children:[(0,t.jsx)(st,{path:"company/settings/instance/environments",element:(0,t.jsx)(kB,{})}),(0,t.jsx)(st,{path:"company/settings/instance/environments/new",element:(0,t.jsx)(kB,{mode:"create"})}),(0,t.jsx)(st,{path:"company/settings/instance/environments/:environmentId/edit",element:(0,t.jsx)(kB,{mode:"edit"})})]}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.access"}),children:(0,t.jsx)(st,{path:"company/settings/instance/access",element:(0,t.jsx)(Xns,{})})}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.experimental"}),children:(0,t.jsx)(st,{path:"company/settings/instance/experimental",element:(0,t.jsx)(Jns,{})})}),(0,t.jsxs)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.plugins"}),children:[(0,t.jsx)(st,{path:"company/settings/instance/plugins",element:(0,t.jsx)(lrs,{})}),(0,t.jsx)(st,{path:"company/settings/instance/plugins/:pluginId",element:(0,t.jsx)(crs,{})})]}),(0,t.jsx)(st,{element:(0,t.jsx)(Kh,{pageKey:"instance.adapters"}),children:(0,t.jsx)(st,{path:"company/settings/instance/adapters",element:(0,t.jsx)(zhe,{})})}),(0,t.jsx)(st,{path:"company/settings/:settingsRoutePath/*",element:(0,t.jsx)(mVt,{})}),(0,t.jsx)(st,{path:"skills/sources",element:(0,t.jsx)(Rme,{})}),(0,t.jsx)(st,{path:"skills/sources/:sourceId",element:(0,t.jsx)(Rme,{})}),(0,t.jsx)(st,{path:"skills/studio",element:(0,t.jsx)(QB,{})}),(0,t.jsx)(st,{path:"skills/studio/new",element:(0,t.jsx)(QB,{})}),(0,t.jsx)(st,{path:"skills/studio/:skillId",element:(0,t.jsx)(QB,{})}),(0,t.jsx)(st,{path:"skills/:skillId/studio",element:(0,t.jsx)(t4e,{})}),(0,t.jsx)(st,{path:"skills/*",element:e?(0,t.jsx)(EXt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(ras,{})})}),(0,t.jsx)(st,{path:"settings",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"settings/*",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"plugins/:pluginId",element:(0,t.jsx)(qhe,{})}),(0,t.jsx)(st,{path:"org",element:e?(0,t.jsx)(Nn,{to:"/agents/all",replace:!0}):(0,t.jsx)(u0,{children:(0,t.jsx)(oas,{})})}),(0,t.jsx)(st,{path:"agents",element:(0,t.jsx)(Nn,{to:"/agents/all",replace:!0})}),UV.map(a=>(0,t.jsx)(st,{path:`agents/${a}`,element:e?(0,t.jsx)(XSt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(sas,{})})},a)),(0,t.jsx)(st,{path:"agents/new",element:(0,t.jsx)(_rs,{})}),(0,t.jsx)(st,{path:"agents/:agentId",element:(0,t.jsx)(ZO,{})}),(0,t.jsx)(st,{path:"agents/:agentId/:tab",element:(0,t.jsx)(ZO,{})}),(0,t.jsx)(st,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(ZO,{})}),(0,t.jsx)(st,{path:"projects",element:(0,t.jsx)(mIt,{})}),(0,t.jsx)(st,{path:"projects/:projectId",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/overview",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/issues",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{element:(0,t.jsx)(nO,{}),children:(0,t.jsx)(st,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(W2t,{})})}),(0,t.jsx)(st,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/configuration",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{path:"projects/:projectId/budget",element:(0,t.jsx)(Qb,{})}),(0,t.jsx)(st,{element:(0,t.jsx)(nO,{}),children:(0,t.jsx)(st,{path:"workspaces",element:(0,t.jsx)(G2t,{})})}),(0,t.jsx)(st,{path:"issues",element:(0,t.jsx)(ZTt,{})}),(0,t.jsx)(st,{path:"tasks",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"search",element:(0,t.jsx)(CRt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"issues/all",element:(0,t.jsx)(ah,{view:"all"})}),(0,t.jsx)(st,{path:"issues/active",element:(0,t.jsx)(ah,{view:"active"})}),(0,t.jsx)(st,{path:"issues/backlog",element:(0,t.jsx)(ah,{view:"backlog"})}),(0,t.jsx)(st,{path:"issues/done",element:(0,t.jsx)(ah,{view:"done"})}),(0,t.jsx)(st,{path:"issues/recent",element:(0,t.jsx)(ah,{view:"recent"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"issues/all",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"issues/active",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"issues/backlog",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"issues/done",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})}),(0,t.jsx)(st,{path:"issues/recent",element:(0,t.jsx)(Nn,{to:"/issues",replace:!0})})]}),(0,t.jsx)(st,{path:"chats",element:(0,t.jsx)(fMt,{})}),(0,t.jsx)(st,{path:"chats/:agentRef",element:(0,t.jsx)(gMt,{})}),(0,t.jsx)(st,{path:"issues/:issueId",element:(0,t.jsx)(dMt,{})}),null,(0,t.jsx)(st,{path:"routines",element:e?(0,t.jsx)(YMt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(nas,{})})}),(0,t.jsx)(st,{path:"cases",element:(0,t.jsx)(Ose,{children:(0,t.jsx)(xut,{})})}),(0,t.jsx)(st,{path:"cases/:caseIdentifier",element:(0,t.jsx)(Ose,{children:(0,t.jsx)(Zht,{})})}),(0,t.jsx)(st,{path:"pixels-office",element:(0,t.jsx)(Qdt,{children:(0,t.jsx)(_zt,{})})}),(0,t.jsx)(st,{path:"status",element:(0,t.jsx)(Fse,{children:(0,t.jsx)(Ile,{})})}),(0,t.jsx)(st,{path:"status/:cardId",element:(0,t.jsx)(Fse,{children:(0,t.jsx)(Ile,{})})}),(0,t.jsx)(st,{path:"status-cards",element:(0,t.jsx)(ipe,{})}),(0,t.jsx)(st,{path:"status-cards/:cardId",element:(0,t.jsx)(ipe,{})}),(0,t.jsx)(st,{path:"review-queue",element:(0,t.jsx)(e0,{children:(0,t.jsx)(pLt,{})})}),(0,t.jsx)(st,{path:"learnings",element:(0,t.jsx)(e0,{children:(0,t.jsx)(xLt,{})})}),(0,t.jsx)(st,{path:"pipelines",element:(0,t.jsx)(e0,{children:(0,t.jsx)(FF,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(FF,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(e0,{children:(0,t.jsx)(FF,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(e0,{children:(0,t.jsx)(c$t,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(MDt,{})})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(e0,{children:(0,t.jsx)(RDt,{})})}),(0,t.jsx)(st,{path:"routines/:routineId",element:e?(0,t.jsx)(Tce,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(tpe,{})})}),(0,t.jsx)(st,{path:"routines/:routineId/:section",element:e?(0,t.jsx)(Tce,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(tpe,{})})}),(0,t.jsx)(st,{element:(0,t.jsx)(nO,{}),children:(0,t.jsxs)(st,{element:(0,t.jsx)(Xdt,{}),children:[(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(hw,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(hw,{})})]})}),(0,t.jsx)(st,{path:"goals",element:(0,t.jsx)(k6t,{})}),(0,t.jsx)(st,{path:"goals/:goalId",element:(0,t.jsx)(M6t,{})}),(0,t.jsx)(st,{path:"artifacts",element:(0,t.jsx)(Mce,{})}),(0,t.jsx)(st,{path:"approvals",element:(0,t.jsx)(Nn,{to:"/approvals/pending",replace:!0})}),(0,t.jsx)(st,{path:"approvals/pending",element:(0,t.jsx)(Lce,{})}),(0,t.jsx)(st,{path:"approvals/all",element:(0,t.jsx)(Lce,{})}),(0,t.jsx)(st,{path:"approvals/:approvalId",element:(0,t.jsx)(D6t,{})}),(0,t.jsx)(st,{path:"activity",element:e?(0,t.jsx)(wUt,{}):(0,t.jsx)(u0,{children:(0,t.jsx)(aas,{})})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"activity/runs",element:(0,t.jsx)(JC,{section:"runs"})}),(0,t.jsx)(st,{path:"activity/costs",element:(0,t.jsx)(JC,{section:"costs"})}),(0,t.jsx)(st,{path:"activity/budgets",element:(0,t.jsx)(JC,{section:"budgets"})}),(0,t.jsx)(st,{path:"activity/timeline",element:(0,t.jsx)(JC,{section:"timeline"})}),(0,t.jsx)(st,{path:"audit",element:(0,t.jsx)(Zp,{to:"/activity",forceAgentMode:!0})}),(0,t.jsx)(st,{path:"audit/activity",element:(0,t.jsx)(Zp,{to:"/activity"})}),(0,t.jsx)(st,{path:"audit/runs",element:(0,t.jsx)(Zp,{to:"/activity/runs"})}),(0,t.jsx)(st,{path:"audit/costs",element:(0,t.jsx)(Zp,{to:"/activity/costs"})}),(0,t.jsx)(st,{path:"audit/budgets",element:(0,t.jsx)(Zp,{to:"/activity/budgets"})}),(0,t.jsx)(st,{path:"audit/timeline",element:(0,t.jsx)(Zp,{to:"/activity/timeline"})}),(0,t.jsx)(st,{path:"runs",element:(0,t.jsx)(Zp,{to:"/activity/runs"})}),(0,t.jsx)(st,{path:"costs",element:(0,t.jsx)(Zp,{to:"/activity/costs"})}),(0,t.jsx)(st,{path:"budgets",element:(0,t.jsx)(Zp,{to:"/activity/budgets"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"costs",element:(0,t.jsx)(u0,{children:(0,t.jsx)(ias,{})})}),(0,t.jsx)(st,{path:"audit",element:(0,t.jsx)(Nn,{to:"/activity?mode=agents",replace:!0})})]}),(0,t.jsxs)(st,{element:(0,t.jsx)(flt,{}),children:[(0,t.jsx)(st,{path:"board-chat",element:(0,t.jsx)(OKt,{})}),(0,t.jsx)(st,{path:"artifacts",element:(0,t.jsx)(Mce,{})})]}),null,(0,t.jsx)(st,{path:"decisions",element:(0,t.jsx)(cKt,{})}),(0,t.jsx)(st,{path:"decisions/queues/:key",element:(0,t.jsx)(hKt,{})}),n?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"inbox",element:(0,t.jsx)(npe,{})}),(0,t.jsx)(st,{path:"inbox/mine",element:(0,t.jsx)(ah,{view:"mine"})}),(0,t.jsx)(st,{path:"inbox/recent",element:(0,t.jsx)(ah,{view:"recent"})}),(0,t.jsx)(st,{path:"inbox/unread",element:(0,t.jsx)(ah,{view:"unread"})}),(0,t.jsx)(st,{path:"inbox/blocked",element:(0,t.jsx)(ah,{view:"blocked"})}),(0,t.jsx)(st,{path:"inbox/all",element:(0,t.jsx)(ah,{view:"everything"})}),(0,t.jsx)(st,{path:"inbox/new",element:(0,t.jsx)(ah,{view:"mine"})})]}):(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"inbox",element:(0,t.jsx)(npe,{})}),(0,t.jsx)(st,{path:"inbox/mine",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/recent",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/unread",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/blocked",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/all",element:(0,t.jsx)(_w,{})}),(0,t.jsx)(st,{path:"inbox/new",element:(0,t.jsx)(Nn,{to:"/inbox/mine",replace:!0})})]}),(0,t.jsx)(st,{path:"inbox/requests",element:(0,t.jsx)(eas,{})}),(0,t.jsx)(st,{path:"u/:userSlug",element:(0,t.jsx)(Jqt,{})}),(0,t.jsx)(st,{path:"design-guide",element:(0,t.jsx)(Hns,{})}),(0,t.jsx)(st,{path:"instance/settings/adapters",element:(0,t.jsx)(zhe,{})}),(0,t.jsx)(st,{path:":pluginRoutePath/*",element:(0,t.jsx)(qhe,{})}),(0,t.jsx)(st,{path:"*",element:(0,t.jsx)(Eu,{scope:"board"})})]})}r(las,"boardRoutes");function spe({credentialSource:e="paperclip_vault"}={}){const s=ra(),n=new URLSearchParams(s.search),{enabled:a}=sS();return wat(n,{chatConnectorsEnabled:a})?(0,t.jsx)(SPe,{credentialSource:e}):(0,t.jsx)(Nn,{to:"/apps",replace:!0})}r(spe,"AppsConnectEntryRoute");function npe(){const{enabled:e}=fc(),{enabled:s}=VI();return e&&s?(0,t.jsx)(ah,{view:v$e(TJ())}):(0,t.jsx)(Nn,{to:`/inbox/${TJ()}`,replace:!0})}r(npe,"InboxRootRedirect");function ah({view:e}){const s=ra(),n=new URLSearchParams(s.search);return n.set(OR,e),(0,t.jsx)(Nn,{to:`/issues?${n.toString()}${s.hash}`,replace:!0})}r(ah,"TaskViewRedirect");function t4e(){const e=ra(),{companies:s,selectedCompany:n,loading:a}=gs(),{companyPrefix:i,skillId:o}=ga();if(a)return null;const l=(i?s.find(c=>c.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;return!l||!o?(0,t.jsx)(Nn,{to:"/skills/studio",replace:!0}):(0,t.jsx)(Nn,{to:`/${l.issuePrefix}/skills/studio/${encodeURIComponent(o)}${e.search}${e.hash}`,replace:!0})}r(t4e,"LegacySkillStudioRedirect");function Iv(){const e=ra(),{companies:s,selectedCompany:n,loading:a}=gs(),{companyPrefix:i}=ga(),{hidden:o}=tu();if(a)return(0,t.jsx)(Dm,{});const l=(i?s.find(d=>d.issuePrefix.toUpperCase()===i.toUpperCase()):null)??n??s[0]??null;if(!l)return IW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(Nn,{to:"/onboarding",replace:!0}):(0,t.jsx)(CG,{});const c=IKe(nye(`${e.pathname}${e.search}${e.hash}`),o);return(0,t.jsx)(Nn,{to:`/${l.issuePrefix}${c}`,replace:!0})}r(Iv,"LegacySettingsRedirect");function rpe(){const{tab:e}=ga();return(0,t.jsx)(Nn,{to:s4e(e),replace:!0})}r(rpe,"LegacyToolsSettingsRedirect");function ape(){const{tab:e}=ga();return(0,t.jsx)(Nn,{to:s4e(e),replace:!0})}r(ape,"LegacyToolsRedirect");function s4e(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(s4e,"legacyToolsRedirectTarget");function n4e(){const{companies:e}=gs(),{openOnboarding:s}=Do(),{t:n}=Rve(),a=Ac(),i=XSe(a?.cloudBaseUrl??null),{onboardingOpen:o,onboardingRouteDismissed:l}=mM(),{companyPrefix:c}=ga(),d=c?e.find(p=>p.issuePrefix.toUpperCase()===c.toUpperCase())??null:null;if(_it({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:N5(),companyId:d.id}):a&&i?Mm(i):s(),"onClick"),children:d?"Add Agent":"Start Onboarding"})})]})})}r(n4e,"OnboardingRoutePage");function cas(){const{companies:e,selectedCompany:s,loading:n}=gs(),a=ra();if(n)return(0,t.jsx)(Dm,{});const i=s??e[0]??null;return i?(0,t.jsx)(Nn,{to:`/${i.issuePrefix}/dashboard`,replace:!0}):IW({pathname:a.pathname,hasCompanies:!1})?(0,t.jsx)(Nn,{to:"/onboarding",replace:!0}):(0,t.jsx)(CG,{})}r(cas,"CompanyRootRedirect");function ipe(){const{cardId:e}=ga(),s=b$e(),n=s?`/${s}`:"";return(0,t.jsx)(Nn,{to:`${n}/status${e?`/${e}`:""}`,replace:!0})}r(ipe,"StatusCardsLegacyRedirect");function Zp({to:e,forceAgentMode:s=!1}){const n=ra(),a=new URLSearchParams(n.search);s&&a.set("mode","agents");const i=a.toString();return(0,t.jsx)(Nn,{to:`${e}${i?`?${i}`:""}${n.hash}`,replace:!0})}r(Zp,"AuditCompatibilityRedirect");function va(){const e=ra(),{companies:s,selectedCompany:n,loading:a}=gs();if(a)return(0,t.jsx)(Dm,{});const i=n??s[0]??null;return i?(0,t.jsx)(Nn,{to:`/${i.issuePrefix}${e.pathname}${e.search}${e.hash}`,replace:!0}):IW({pathname:e.pathname,hasCompanies:!1})?(0,t.jsx)(Nn,{to:"/onboarding",replace:!0}):(0,t.jsx)(CG,{})}r(va,"UnprefixedBoardRedirect");function CG(){const{openOnboarding:e}=Do(),{t:s}=Rve(),n=Ac(),a=XSe(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?Mm(a):e(),"onClick"),children:s("app.noCompanies.newCompany",{defaultValue:"New Organization"})})})]})})}r(CG,"NoCompaniesStartPage");function das(){const{enabled:e,loaded:s}=fc(),{enabled:n}=VI();return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(i$e,{children:[(0,t.jsx)(st,{path:"oauth-handoff",element:(0,t.jsx)(QYt,{})}),(0,t.jsx)(st,{path:"auth",element:(0,t.jsx)(Prs,{})}),(0,t.jsx)(st,{path:"board-claim/:token",element:(0,t.jsx)(Mrs,{})}),(0,t.jsx)(st,{path:"cli-auth/:id",element:(0,t.jsx)(Drs,{})}),(0,t.jsx)(st,{path:"invite/:token",element:(0,t.jsx)(qrs,{})}),(0,t.jsx)(st,{path:"s/:token",element:(0,t.jsx)(epe,{})}),(0,t.jsx)(st,{path:"s/:token/issues/:issueId",element:(0,t.jsx)(epe,{})}),(0,t.jsx)(st,{element:s?(0,t.jsx)(Ene,{allowMembershipRequest:!0}):(0,t.jsx)(Dm,{}),children:(0,t.jsx)(st,{path:"chat-identity/confirm",element:(0,t.jsx)(FYt,{})})}),(0,t.jsx)(st,{path:"tests/perf/long-thread",element:(0,t.jsx)(IMt,{})}),(0,t.jsx)(st,{path:"ux-lab/bootstrap-setup",element:(0,t.jsx)(lVt,{})}),(0,t.jsx)(st,{path:"ux-lab/responsible-user-denial",element:(0,t.jsx)(cVt,{})}),(0,t.jsx)(st,{path:"ux-lab/cross-issue-collaboration",element:(0,t.jsx)(uVt,{})}),(0,t.jsxs)(st,{element:s?(0,t.jsx)(Ene,{}):(0,t.jsx)(Dm,{}),children:[(0,t.jsx)(st,{index:!0,element:(0,t.jsx)(cas,{})}),(0,t.jsx)(st,{path:"onboarding",element:(0,t.jsx)(n4e,{})}),(0,t.jsx)(st,{path:"instance",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"instance/settings",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"instance/settings/*",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"companies",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"dashboard",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"inbox/*",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"issues",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"tasks",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"issues/:issueId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"routines",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"routines/:routineId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"review-queue",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"learnings",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"cases",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"cases/:caseIdentifier",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pixels-office",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"status",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"status/:cardId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"status-cards",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"status-cards/:cardId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/add",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/settings",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/items/:caseId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"pipelines/:pipelineId/cases/:caseId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"artifacts",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"audit",element:(0,t.jsx)(va,{})}),e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(st,{path:"audit/*",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"activity",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"activity/*",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"runs",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"costs",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"budgets",element:(0,t.jsx)(va,{})})]}):null,(0,t.jsx)(st,{path:"decisions",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"u/:userSlug",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"skills/studio",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"skills/studio/new",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"skills/studio/:skillId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"skills/:skillId/studio",element:(0,t.jsx)(t4e,{})}),(0,t.jsx)(st,{path:"skills/*",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"settings",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"settings/*",element:(0,t.jsx)(Iv,{})}),(0,t.jsx)(st,{path:"agents",element:(0,t.jsx)(va,{})}),UV.map(a=>(0,t.jsx)(st,{path:`agents/${a}`,element:(0,t.jsx)(va,{})},a)),(0,t.jsx)(st,{path:"agents/new",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"agents/:agentId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"agents/:agentId/:tab",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"agents/:agentId/runs/:runId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/overview",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/issues",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/issues/:filter",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/workspaces",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/workspaces/:workspaceId",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"projects/:projectId/configuration",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"workspaces",element:(0,t.jsx)(va,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/services",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/configuration",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/runtime-logs",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/issues",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:"execution-workspaces/:workspaceId/routines",element:(0,t.jsx)(Hj,{})}),(0,t.jsx)(st,{path:":companyPrefix",element:e?(0,t.jsx)(Pot,{}):(0,t.jsx)(mlt,{}),children:las(e,n)}),(0,t.jsx)(st,{path:"*",element:(0,t.jsx)(Eu,{scope:"global"})})]})]}),(0,t.jsx)(Ipt,{}),(0,t.jsx)(hot,{})]})}r(das,"App");var uas=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){VSe(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 mas(){const{data:e}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),retry:!1}),s=e?.sentryDsn,n=e?.sentryEnvironment??void 0;return(0,m.useEffect)(()=>{if(s)return Wit(s,n),()=>{Vit()}},[s,n]),null}r(mas,"SentryGate");function has(e){let s=gg();tie(s),CU(s,e.userId);const n=STe(()=>{const o=gg();o!==s&&(s=o,tie(o),CU(o,e.userId))}),a=typeof navigator<"u"&&"serviceWorker"in navigator?navigator.serviceWorker:null,i=r(o=>{const l=gAt(o.data);l&&(l.type==="navigate"?e.navigate(l.url):fAt(l.notification))},"onMessage");return a?.addEventListener("message",i),a?.startMessages(),()=>{n(),a?.removeEventListener("message",i)}}r(has,"startNotificationRuntime");function pas(){const e=Ln(),s=(0,m.useRef)(e),{data:n}=X({queryKey:P.auth.session,queryFn:r(()=>La.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 has({userId:a,navigate:r(i=>s.current(i),"navigate")})},[a]),null}r(pas,"NotificationRuntime");function fas(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(fas,"managedRoutineToRow");function xas({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=fas(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)(lEe,{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(xas,"ManagedRoutinesList");function ope(e){return new Set(e??[])}r(ope,"toPathSet");function gas({expandedPaths:e,checkedPaths:s,selectedFile:n=null,showCheckboxes:a=!1,onToggleDir:i,onSelectFile:o,...l}){return(0,m.createElement)(cj,{...l,selectedFile:n,expandedDirs:ope(e),checkedFiles:s?ope(s):void 0,showCheckboxes:a,onToggleDir:i??(()=>{}),onSelectFile:o??(()=>{})})}r(gas,"PluginSdkFileTree");function bas(e){const[s,n]=(0,m.useState)(null);return(0,m.useEffect)(()=>{let a=!1;return Wc(()=>import("./MarkdownEditor-BOTosEGR.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(bas,"PluginSdkMarkdownEditor");function vas(e){return Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null&&s!==""&&s!==!1))}r(vas,"compactIssueFilters");function yas({companyId:e,projectId:s=null,filters:n,viewStateKey:a="paperclip:plugin-issues-view",initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l=!0}){const c=Mt(),d=(0,m.useMemo)(()=>vas({...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}=X({queryKey:P.agents.list(e??"__no-company__"),queryFn:r(()=>Lt.list(e),"queryFn"),enabled:!!e}),{data:x}=X({queryKey:P.projects.list(e??"__no-company__",{includeArchived:!0}),queryFn:r(()=>ma.list(e,{includeArchived:!0}),"queryFn"),enabled:!!e}),b=P.liveRuns(e??"__no-company__"),v=bo({companyId:e,resourceKey:"live-runs",queryKey:b,enabled:!!e,refetchInterval:!1,leaderOnly:!0}),{data:j,dataUpdatedAt:N}=X({queryKey:b,queryFn:r(()=>Zr.liveRunsForCompany(e),"queryFn"),enabled:v.enabled,refetchInterval:v.refetchInterval});vo(v,j,N);const{data:w,isLoading:k,error:S}=X({queryKey:p,queryFn:r(()=>At.list(e,d),"queryFn"),enabled:!!e}),C=(0,m.useMemo)(()=>yg(j,w),[w,j]),I=je({mutationFn:r(({id:T,data:R})=>At.update(T,R),"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)(cg,{issues:w??[],isLoading:k,error:S,agents:f,projects:x,liveIssueIds:C,projectId:h??void 0,viewStateKey:a,initialSearch:i,createIssueLabel:o,searchWithinLoadedIssues:l,onUpdateIssue:r((T,R)=>I.mutate({id:T,data:R}),"onUpdateIssue")}):(0,m.createElement)("div",{className:"text-sm text-muted-foreground"},"Select an organization to view tasks.")}r(yas,"PluginSdkIssuesList");function jas({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=z7(),f=e??p.companyId??null,{data:x}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn"),enabled:c}),b=x?.user?.id??x?.session?.userId??null,{data:v}=X({queryKey:P.agents.list(f??"__no-company__"),queryFn:r(()=>Lt.list(f),"queryFn"),enabled:!!f}),{data:j}=X({queryKey:P.access.companyUserDirectory(f??"__no-company__"),queryFn:r(()=>hr.listUserDirectory(f),"queryFn"),enabled:!!f&&c}),N=(0,m.useMemo)(()=>pz(),[]),w=(0,m.useMemo)(()=>N.map(T=>T.startsWith("agent:")?T.slice(6):null).filter(T=>!!T),[N]),k=(0,m.useMemo)(()=>cy((v??[]).filter(T=>d||T.status!=="terminated"),w),[v,d,w]),S=(0,m.useMemo)(()=>[...c?Cfe(b):[],...c?BN(j?.users,{excludeUserIds:[b]}):[],...k.map(T=>({id:ph({assigneeAgentId:T.id}),label:T.name,searchText:`${T.name} ${T.role} ${T.title??""}`}))],[j?.users,b,c,k]),C=Bv(s),I=C.assigneeAgentId?k.find(T=>T.id===C.assigneeAgentId):null;return(0,m.createElement)(Au,{value:s,options:S,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:u,onConfirm:h,onChange:r(T=>{const R=Bv(T);R.assigneeAgentId&&ly(R.assigneeAgentId),R.assigneeUserId&&Z1(R.assigneeUserId),n(T,R)},"onChange"),renderTriggerValue:r(T=>T?I?(0,m.createElement)(QP,null,(0,m.createElement)(S5,{icon:I.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},T.label)):(0,m.createElement)("span",{className:"truncate"},T.label):(0,m.createElement)("span",{className:"text-muted-foreground"},a),"renderTriggerValue"),renderOption:r(T=>{if(!T.id)return(0,m.createElement)("span",{className:"truncate"},T.label);const R=Bv(T.id),A=R.assigneeAgentId?k.find(D=>D.id===R.assigneeAgentId):null;return(0,m.createElement)(QP,null,A?(0,m.createElement)(S5,{icon:A.icon,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):(0,m.createElement)(Uc,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,m.createElement)("span",{className:"truncate"},T.label))},"renderOption")})}r(jas,"PluginSdkAssigneePicker");function was({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=z7(),p=e??h.companyId??null,{data:f}=X({queryKey:P.auth.session,queryFn:r(()=>La.getSession(),"queryFn")}),x=f?.user?.id??f?.session?.userId??null,{data:b}=X({queryKey:P.projects.list(p??"__no-company__",{includeArchived:c}),queryFn:r(()=>ma.list(p,{includeArchived:c}),"queryFn"),enabled:!!p}),v=(0,m.useMemo)(()=>(b??[]).filter(S=>c||!S.archivedAt),[c,b]),{orderedProjects:j}=Gy({projects:v,companyId:p,userId:x}),N=(0,m.useMemo)(()=>dy(),[]),w=(0,m.useMemo)(()=>j.map(S=>({id:S.id,label:S.name,searchText:S.description??""})),[j]),k=j.find(S=>S.id===s)??null;return(0,m.createElement)(Au,{value:s,options:w,recentOptionIds:N,placeholder:a,noneLabel:i,searchPlaceholder:o,emptyMessage:l,className:d,onConfirm:u,onChange:r(S=>{S&&H0(S),n(S)},"onChange"),renderTriggerValue:r(S=>!S||!k?(0,m.createElement)("span",{className:"text-muted-foreground"},a):(0,m.createElement)(QP,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)(QP,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(was,"PluginSdkProjectPicker");function QP({children:e}){return(0,m.createElement)("span",{className:"contents"},e)}r(QP,"FragmentSafe");function kas({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(kas,"PluginSdkStatusBadge");function Nas({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(Nas,"PluginSdkDataTable");function Sas({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(Sas,"PluginSdkKeyValueList");function Cas({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(Cas,"PluginSdkMetricCard");function _as({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(_as,"PluginSdkJsonTree");function Ias({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(Ias,"PluginSdkSpinner");var Aas=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 Tas(e,s){globalThis.__paperclipPluginBridge__={react:e,reactJsxRuntime:t,reactDom:s,sdkUi:{usePluginData:$Ke,usePluginAction:OKe,useHostContext:z7,useHostLocation:BKe,useHostNavigation:FKe,usePluginStream:qKe,usePluginToast:zKe,copyTextToClipboard:ha,MarkdownBlock:r(({content:n,className:a,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l})=>(0,m.createElement)(Rn,{className:a,softBreaks:!1,enableWikiLinks:i,wikiLinkRoot:o,resolveWikiLinkHref:l,children:n}),"MarkdownBlock"),MetricCard:Cas,StatusBadge:kas,DataTable:Nas,KeyValueList:Sas,JsonTree:_as,Spinner:Ias,ErrorBoundary:Aas,MarkdownEditor:bas,FileTree:gas,IssuesList:yas,AssigneePicker:jas,ProjectPicker:was,ManagedRoutinesList:xas}}}r(Tas,"initPluginBridge");var Ras=1e4;function Eas(e=Ras){if(typeof performance>"u"||typeof performance.clearMeasures!="function")return()=>{};const n=setInterval(r(()=>{globalThis.__paperclipKeepPerfMeasures||performance.clearMeasures()},"reap"),e);return()=>clearInterval(n)}r(Eas,"startPerfMeasureReaper");var Pas=Oy((e=>{function s(q,U){var F=q.length;q.push(U);e:for(;0<F;){var K=F-1>>>1,G=q[K];if(0<i(G,U))q[K]=U,q[F]=G,F=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],F=q.pop();if(F!==U){q[0]=F;e:for(var K=0,G=q.length,se=G>>>1;K<se;){var ee=2*(K+1)-1,ne=q[ee],he=ee+1,Z=q[he];if(0>i(ne,F))he<G&&0>i(Z,ne)?(q[K]=Z,q[he]=F,K=he):(q[K]=ne,q[ee]=F,K=ee);else if(he<G&&0>i(Z,F))q[K]=Z,q[he]=F,K=he;else break e}}return U}r(a,"pop");function i(q,U){var F=q.sortIndex-U.sortIndex;return F!==0?F: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,$());else{var U=n(u);U!==null&&z(C,U.startTime-q)}}r(C,"handleTimeout");var I=!1,T=-1,R=5,A=-1;function D(){return j?!0:!(e.unstable_now()-A<R)}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(T),T=-1),x=!0;var F=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 G=K(p.expirationTime<=q);if(q=e.unstable_now(),typeof G=="function"){p.callback=G,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 se=n(u);se!==null&&z(C,se.startTime-q),U=!1}}break e}finally{p=null,f=F,x=!1}U=void 0}}finally{U?$():I=!1}}}r(M,"performWorkUntilDeadline");var $;if(typeof k=="function")$=r(function(){k(M)},"schedulePerformWorkUntilDeadline");else if(typeof MessageChannel<"u"){var E=new MessageChannel,B=E.port2;E.port1.onmessage=M,$=r(function(){B.postMessage(null)},"schedulePerformWorkUntilDeadline")}else $=r(function(){N(M,0)},"schedulePerformWorkUntilDeadline");function z(q,U){T=N(function(){q(e.unstable_now())},U)}r(z,"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||(R=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 F=f;f=U;try{return q()}finally{f=F}},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 F=f;f=q;try{return U()}finally{f=F}},e.unstable_scheduleCallback=function(q,U,F){var K=e.unstable_now();switch(typeof F=="object"&&F!==null?(F=F.delay,F=typeof F=="number"&&0<F?K+F:K):F=K,q){case 1:var G=-1;break;case 2:G=250;break;case 5:G=1073741823;break;case 4:G=1e4;break;default:G=5e3}return G=F+G,q={id:h++,callback:U,priorityLevel:q,startTime:F,expirationTime:G,sortIndex:-1},F>K?(q.sortIndex=F,s(u,q),n(d)===null&&q===n(u)&&(v?(w(T),T=-1):v=!0,z(C,F-K))):(q.sortIndex=G,s(d,q),b||x||(b=!0,I||(I=!0,$()))),q},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(q){var U=f;return function(){var F=f;f=U;try{return q.apply(this,arguments)}finally{f=F}}}})),Mas=Oy(((e,s)=>{s.exports=Pas()})),Das=Oy((e=>{var s=Mas(),n=O8(),a=Ipe();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,O=y;;){var V=_.return;if(V===null)break;var J=V.alternate;if(J===null){if(O=V.return,O!==null){_=O;continue}break}if(V.child===J.child){for(J=V.child;J;){if(J===_)return u(V),g;if(J===O)return u(V),y;J=J.sibling}throw Error(i(188))}if(_.return!==O.return)_=V,O=J;else{for(var ve=!1,Be=V.child;Be;){if(Be===_){ve=!0,_=V,O=J;break}if(Be===O){ve=!0,O=V,_=J;break}Be=Be.sibling}if(!ve){for(Be=J.child;Be;){if(Be===_){ve=!0,_=J,O=V;break}if(Be===O){ve=!0,O=J,_=V;break}Be=Be.sibling}if(!ve)throw Error(i(189))}}if(_.alternate!==O)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"),T=Symbol.for("react.suspense_list"),R=Symbol.for("react.memo"),A=Symbol.for("react.lazy"),D=Symbol.for("react.activity"),M=Symbol.for("react.memo_cache_sentinel"),$=Symbol.iterator;function E(g){return g===null||typeof g!="object"?null:(g=$&&g[$]||g["@@iterator"],typeof g=="function"?g:null)}r(E,"getIteratorFn");var B=Symbol.for("react.client.reference");function z(g){if(g==null)return null;if(typeof g=="function")return g.$$typeof===B?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 T: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 R:return y=g.displayName||null,y!==null?y:z(g.type)||"Memo";case A:y=g._payload,g=g._init;try{return z(g(y))}catch{}}return null}r(z,"getComponentNameFromType");var q=Array.isArray,U=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,F=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K={pending:!1,data:null,method:null,action:null},G=[],se=-1;function ee(g){return{current:g}}r(ee,"createCursor");function ne(g){0>se||(g.current=G[se],G[se]=null,se--)}r(ne,"pop");function he(g,y){se++,G[se]=g.current,g.current=y}r(he,"push");var Z=ee(null),re=ee(null),ce=ee(null),H=ee(null);function Q(g,y){switch(he(ce,y),he(re,g),he(Z,null),y.nodeType){case 9:case 11:g=(g=y.documentElement)&&(g=g.namespaceURI)?TY(g):0;break;default:if(g=y.tagName,y=y.namespaceURI)y=TY(y),g=RY(y,g);else switch(g){case"svg":g=1;break;case"math":g=2;break;default:g=0}}ne(Z),he(Z,g)}r(Q,"pushHostContainer");function Y(){ne(Z),ne(re),ne(ce)}r(Y,"popHostContainer");function te(g){g.memoizedState!==null&&he(H,g);var y=Z.current,_=RY(y,g.type);y!==_&&(he(re,g),he(Z,_))}r(te,"pushHostContext");function ae(g){re.current===g&&(ne(Z),ne(re)),H.current===g&&(ne(H),LS._currentValue=K)}r(ae,"popHostContext");var me,oe;function ie(g){if(me===void 0)try{throw Error()}catch(_){var y=_.stack.trim().match(/\n( *(at )?)/);me=y&&y[1]||"",oe=-1<_.stack.indexOf(`
|
|
772
772
|
at`)?" (<anonymous>)":-1<_.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
773
773
|
`+me+g+oe}r(ie,"describeBuiltInComponentFrame");var ge=!1;function be(g,y){if(!g||ge)return"";ge=!0;var _=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var O={DetermineComponentFrameRoot:r(function(){try{if(y){var zs=r(function(){throw Error()},"Fake");if(Object.defineProperty(zs.prototype,"props",{set:r(function(){throw Error()},"set")}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(zs,[])}catch(fs){var is=fs}Reflect.construct(g,[],zs)}else{try{zs.call()}catch(fs){is=fs}g.call(zs.prototype)}}else{try{throw Error()}catch(fs){is=fs}(zs=g())&&typeof zs.catch=="function"&&zs.catch(function(){})}}catch(fs){if(fs&&is&&typeof fs.stack=="string")return[fs.stack,is.stack]}return[null,null]},"DetermineComponentFrameRoot")};O.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var V=Object.getOwnPropertyDescriptor(O.DetermineComponentFrameRoot,"name");V&&V.configurable&&Object.defineProperty(O.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var J=O.DetermineComponentFrameRoot(),ve=J[0],Be=J[1];if(ve&&Be){var jt=ve.split(`
|
|
774
774
|
`),ss=Be.split(`
|