@tickernelz/paperclip-pro-ui 2026.1014.1 → 2026.1015.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-D6WtpzBM.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/agent-avatar-url-BnmqahQ7.js","assets/preload-helper-CceJXRIF.js","assets/BreadcrumbContext-Bxr1TyKN.js","assets/label-YjU0jMtG.js","assets/mention-chips-ClRmijVb.js","assets/dist-CvM0_U_m.js","assets/dist-BrRwU9U9.js","assets/checkbox-5wFlZdZn.js","assets/check-BiXfODpl.js","assets/clipboard-CTmezHYG.js","assets/RoutineRunVariablesDialog-DMTFaEse.js","assets/alert-dialog-BxpRolrb.js","assets/AgentAvatar-DZh8tNnK.js","assets/MarkdownEditor-D7suACD6.js","assets/dist-CMegW-DS.js","assets/dist-BhxPxuMy.js","assets/StatusIcon-YdJnE47W.js","assets/badge-D5aOL1Ll.js","assets/bot-DpNd1tv2.js","assets/select-DRgGQ-iP.js","assets/ToastContext-Dh8dPdr5.js","assets/sheet-CACWxbsc.js","assets/heartbeats-Dae6h2SU.js","assets/useHiddenSettings-Dz7GWNDr.js","assets/health-D8T5Zr74.js","assets/rotate-ccw-2WnWy1fs.js","assets/environments-Bj-4l7Ol.js","assets/input-CtLHwxEw.js","assets/company-members-Dd6xBf6K.js","assets/card-PCL2aF_L.js","assets/EmptyState-DliXLd04.js","assets/PageSkeleton-BZF4K6Hf.js","assets/skeleton-DCrngTtF.js","assets/tabs-BfOtoFWj.js","assets/use-adapter-capabilities-JhD0-FlQ.js","assets/use-copy-action-qHyHFl14.js","assets/arrow-right-bnOoaiPg.js","assets/external-link-LnxJtUIq.js","assets/MarkdownBody-B5ygzgk6.js","assets/file-text-Ba5Wddur.js","assets/index-BM-RkEuH.css"])))=>i.map(i=>d[i]);
2
- var Ie=Object.defineProperty;var a=(e,n)=>Ie(e,"name",{value:n,configurable:!0});import{i as ae}from"./rolldown-runtime-ZpX3ckPj.js";import{B as re,G as T,St as b,Va as Ae,_i as Ce,aa as j,ht as Se,ut as _e,z as $,za as Ee}from"./agent-avatar-url-BnmqahQ7.js";import{t as Le}from"./preload-helper-CceJXRIF.js";import{Ln as Me,ct as Te,f as ke,i as K,n as qe,r as ee,s as ie,yt as Pe}from"./BreadcrumbContext-Bxr1TyKN.js";import{m as le}from"./alert-dialog-BxpRolrb.js";import{t as oe}from"./AgentAvatar-DZh8tNnK.js";import{t as Be}from"./tabs-BfOtoFWj.js";import{t as te}from"./bot-DpNd1tv2.js";import{i as Fe,o as Re,t as $e}from"./heartbeats-Dae6h2SU.js";import{i as Ke,n as De,t as se}from"./environments-Bj-4l7Ol.js";import{t as ne}from"./EmptyState-DliXLd04.js";import{t as Oe}from"./PageSkeleton-BZF4K6Hf.js";import{Dt as ze,Ft as D,Gt as Ve,Kt as ce,Lt as Ge,Rt as Ue,Vt as He,Wt as Qe,Xt as We,Yt as ue,Zt as Xe,qt as Ye}from"./index-D6WtpzBM.js";var d=ae(Ae(),1),t=ae(Ee(),1),de=Ce,Ze=(0,d.lazy)(()=>Le(()=>import("./index-D6WtpzBM.js").then(e=>e.gt).then(e=>({default:e.ConfigureBuiltInAgentModal})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42]))),Je=["all","active","paused","error","builtin"],et=[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"paused",label:"Paused"},{value:"error",label:"Error"},{value:"builtin",label:"Built-in"}];function tt(e){return Je.includes(e)}a(tt,"isFilterTab");var z={label:"Local",detail:"Paperclip host",title:"Local - Paperclip host"},me={label:"—",detail:"Loading environment",title:"Loading environment"},pe=new Set(["terminated","pending_approval"]);function ge(e,n){return n==="all"?!0:n==="active"?e==="active"||e==="running"||e==="idle":n==="paused"?e==="paused":n==="error"?e==="error":!0}a(ge,"matchesFilter");function st(e,n,i){return e.filter(r=>pe.has(r.status)?!1:n==="builtin"?i.has(r.id):ge(r.status,n)).sort((r,o)=>r.name.localeCompare(o.name))}a(st,"filterAgents");function nt(e){const n=e.adapterConfig?.model;if(typeof n!="string")return null;const i=n.trim();return i.length>0?i:null}a(nt,"getConfiguredModel");function at(e){return e==="ssh"?"SSH":e.charAt(0).toUpperCase()+e.slice(1)}a(at,"formatEnvironmentDriver");function rt(e,n){const i=typeof e.config.provider=="string"?e.config.provider.trim():"";return i?n?.sandboxProviders?.[i]?.displayName??i:"Sandbox"}a(rt,"getSandboxProviderLabel");function it(e,n){const i=Ge(e)?"Managed by Paperclip":e.driver==="sandbox"?`${rt(e,n)} sandbox provider`:e.driver==="local"?"Paperclip host":at(e.driver);return{label:e.name,detail:i,title:`${e.name} - ${i}`}}a(it,"describeEnvironment");function lt(e){return{label:"Unknown environment",detail:e.slice(0,8),title:`Unknown environment - ${e}`}}a(lt,"describeMissingEnvironment");function ot(e,n,i,r){const o=e.defaultEnvironmentId??i;if(!o)return z;const m=n.get(o);return m?it(m,r):lt(o)}a(ot,"resolveAgentEnvironment");function xe(e,n,i){return e.reduce((r,o)=>{const m=xe(o.reports,n,i);return pe.has(o.status)?(r.push(...m),r):(((n==="builtin"?i.has(o.id):ge(o.status,n))||m.length>0)&&r.push({...o,reports:m}),r)},[]).sort((r,o)=>r.name.localeCompare(o.name))}a(xe,"filterOrgTree");function wt(){const{selectedCompanyId:e}=Se(),{openNewAgent:n}=Fe(),{setBreadcrumbs:i}=qe(),r=ke(),o=Me(),{isMobile:m}=Ke(),N=o.pathname.split("/").pop()??"all",v=tt(N)?N:"all",[S,w]=(0,d.useState)("org"),I=m,l=I?"list":S,{data:u}=j({queryKey:b.instance.settings,queryFn:a(()=>De.get(),"queryFn"),enabled:!!e}),p=u?.experimental.enableBuiltInAgents===!0,f=v==="builtin"&&!p?"all":v,k=(0,d.useMemo)(()=>et.filter(s=>s.value!=="builtin"||p),[p]),{data:h}=j({queryKey:b.builtInAgents.list(e),queryFn:a(()=>We.list(e),"queryFn"),enabled:!!e&&p}),_=(0,d.useMemo)(()=>{const s=new Map;if(!p)return s;for(const c of h??[])c.agentId&&s.set(c.agentId,c);return s},[h,p]),V=(0,d.useMemo)(()=>new Set(_.keys()),[_]),[q,P]=(0,d.useState)(null),{data:g,isLoading:ve,error:G}=j({queryKey:b.agents.list(e),queryFn:a(()=>ee.list(e),"queryFn"),enabled:!!e}),{data:A}=j({queryKey:b.org(e),queryFn:a(()=>ee.org(e),"queryFn"),enabled:!!e&&l==="org"}),E=u?.experimental.enableEnvironments===!0,{data:C}=j({queryKey:b.environments.list(e),queryFn:a(()=>se.list(e),"queryFn"),enabled:!!e&&E}),{data:U}=j({queryKey:b.environments.capabilities(e),queryFn:a(()=>se.capabilities(e),"queryFn"),enabled:!!e&&E}),H=[...b.liveRuns(e),"agents-page"],B=Ve({companyId:e,resourceKey:"live-runs:agents-page",queryKey:H,enabled:!!e,refetchInterval:15e3,leaderOnly:!0}),{data:F,dataUpdatedAt:be}=j({queryKey:H,queryFn:a(()=>$e.liveRunsForCompany(e),"queryFn"),enabled:B.enabled,refetchInterval:B.refetchInterval});Qe(B,F,be);const Q=Ye(e),L=(0,d.useMemo)(()=>{const s=new Map;for(const c of F??[]){if(c.status!=="running"&&c.status!=="queued")continue;const x=s.get(c.agentId);if(x){x.liveCount+=1;continue}s.set(c.agentId,{runId:c.id,liveCount:1})}return s},[F]),je=(0,d.useMemo)(()=>{const s=new Map;for(const c of g??[])s.set(c.id,c);return s},[g]),W=(0,d.useMemo)(()=>{const s=new Map;for(const c of C??[])s.set(c.id,c);return s},[C]),X=(0,d.useMemo)(()=>{const s=new Map;for(const c of g??[])s.set(c.id,ot(c,W,u?.defaultEnvironmentId??null,U));return s},[g,W,U,u?.defaultEnvironmentId]);if((0,d.useEffect)(()=>{i([{label:"Agents"}])},[i]),(0,d.useEffect)(()=>{e&&v==="builtin"&&u&&!p&&r("/agents/all",{replace:!0})},[p,u,r,v,e]),!e)return(0,t.jsx)(ne,{icon:te,message:"Select a company to view agents."});if(ve)return(0,t.jsx)(Oe,{variant:"list"});const y=st(g??[],f,V),R=xe(A??[],f,V),Y=E&&C===void 0,Z=E&&(C===void 0||C.length>1),ye=a(s=>Y?me:X.get(s)??z,"resolveRenderedEnvironment"),Ne=a(s=>{const c=s.orgChainHealth?.status==="invalid_org_chain",x=_.get(s.id),we=x?.status==="needs_setup"||x?.status==="pending_approval",M=x&&we?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ue,{status:x.status}),x.status==="needs_setup"&&(0,t.jsx)("span",{onClick:a(J=>{J.preventDefault(),J.stopPropagation()},"onClick"),children:(0,t.jsx)(K,{size:"xs",variant:"outline",onClick:a(()=>P(x),"onClick"),children:"Set up"})})]}):null;return(0,t.jsx)(ze,{title:s.name,titleAccessory:(0,t.jsx)(Xe,{agentId:s.id,companyId:s.companyId}),titleClassName:"flex-1 xl:flex-none xl:w-56",titleTextClassName:"whitespace-normal break-words xl:truncate xl:whitespace-nowrap",subtitleClassName:"whitespace-normal break-words xl:truncate xl:whitespace-nowrap",subtitle:`${de[s.role]??s.role}${s.title?` - ${s.title}`:""}`,to:re(s),className:T("group",s.pausedAt&&f!=="paused"?"opacity-50":"",ce(Q.data,"agent",s.id)==="left"?"sm:text-foreground/55":""),leading:c?(0,t.jsx)(le,{className:"h-3.5 w-3.5 text-amber-500","aria-label":"Invalid reporting chain"}):(0,t.jsx)(oe,{agent:s,size:32}),secondaryRow:M?(0,t.jsx)("div",{className:"xl:hidden flex flex-wrap items-center gap-1.5",children:M}):void 0,meta:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[M&&(0,t.jsx)("div",{className:"hidden xl:flex items-center gap-1.5",children:M}),(0,t.jsx)("div",{className:"hidden xl:flex items-center gap-3",children:(0,t.jsx)(he,{agent:s,environment:ye(s.id),showEnvironment:Z})})]}),metaSpacerClassName:"hidden xl:block",trailing:(0,t.jsx)("div",{className:"flex items-center gap-3",children:(0,t.jsxs)("div",{className:"hidden sm:flex items-center gap-3",children:[L.has(s.id)&&(0,t.jsx)(O,{agentRef:$(s),runId:L.get(s.id).runId,liveCount:L.get(s.id).liveCount}),(0,t.jsx)("span",{className:"w-20 flex justify-end",children:(0,t.jsx)(D,{status:s.status})})]})})},s.id)},"renderAgentRow");return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[(0,t.jsx)(Be,{value:f,onValueChange:a(s=>r(`/agents/${s}`),"onValueChange"),children:(0,t.jsx)(He,{items:k,value:f,onValueChange:a(s=>r(`/agents/${s}`),"onValueChange")})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[!I&&(0,t.jsxs)("div",{className:"flex items-center border border-border",role:"group","aria-label":"View mode",children:[(0,t.jsx)("button",{className:T("p-1.5 transition-colors",l==="list"?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:a(()=>w("list"),"onClick"),title:"List view","aria-label":"List view","aria-pressed":l==="list",children:(0,t.jsx)(Re,{className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{className:T("p-1.5 transition-colors",l==="org"?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:a(()=>w("org"),"onClick"),title:"Org chart view","aria-label":"Org chart view","aria-pressed":l==="org",children:(0,t.jsx)(Pe,{className:"h-3.5 w-3.5"})})]}),(0,t.jsxs)(K,{size:"sm",variant:"outline",onClick:n,children:[(0,t.jsx)(Te,{className:"h-3.5 w-3.5 mr-1.5"}),"New Agent"]})]})]}),y.length>0&&(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:[y.length," agent",y.length!==1?"s":""]}),G&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:G.message}),g&&g.length===0&&(0,t.jsx)(ne,{icon:te,message:"Create your first agent to get started.",action:"New Agent",onAction:n}),l==="list"&&y.length>0&&(0,t.jsx)("div",{children:y.map(Ne)}),l==="list"&&g&&g.length>0&&y.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No agents match the selected status."}),l==="org"&&R.length>0&&(0,t.jsx)("div",{className:"py-1",children:R.map(s=>(0,t.jsx)(fe,{node:s,depth:0,agentMap:je,liveRunByAgent:L,environmentByAgentId:X,environmentDataLoading:Y,showEnvironment:Z,tab:f,memberships:Q.data,builtInByAgentId:_,onConfigureBuiltIn:P},s.id))}),l==="org"&&A&&A.length>0&&R.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No agents match the selected status."}),l==="org"&&A&&A.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No organizational hierarchy defined."}),q&&e&&(0,t.jsx)(d.Suspense,{fallback:null,children:(0,t.jsx)(Ze,{companyId:e,state:q,open:q!==null,onOpenChange:a(s=>{s||P(null)},"onOpenChange")})})]})}a(wt,"Agents");function fe({node:e,depth:n,agentMap:i,liveRunByAgent:r,environmentByAgentId:o,environmentDataLoading:m,showEnvironment:N,tab:v,memberships:S,builtInByAgentId:w,onConfigureBuiltIn:I}){const l=i.get(e.id),u=w.get(e.id),p=u?.status==="needs_setup"||u?.status==="pending_approval",f=!!(l&&l.orgChainHealth?.status==="invalid_org_chain"),k=ce(S,"agent",e.id);return(0,t.jsxs)("div",{style:{paddingLeft:n*24},children:[(0,t.jsxs)(ie,{to:l?re(l):`/agents/${e.id}`,className:T("group flex items-center gap-3 rounded-lg px-3 py-2 hover:bg-accent/50 transition-colors w-full text-left no-underline text-inherit",l?.pausedAt&&v!=="paused"&&"opacity-50",k==="left"&&"sm:text-foreground/55"),children:[f?(0,t.jsx)(le,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):(0,t.jsx)(oe,{agent:l??e,size:24}),(0,t.jsxs)("div",{className:"flex-1 min-w-0 flex flex-wrap items-center gap-2",children:[(0,t.jsxs)("div",{className:"min-w-(--sz-7rem) truncate",children:[(0,t.jsx)("span",{className:"text-sm font-medium",children:e.name}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground ml-2",children:[de[e.role]??e.role,l?.title?` - ${l.title}`:""]})]}),u&&p&&(0,t.jsxs)("div",{className:"flex items-center gap-1.5 shrink-0",children:[(0,t.jsx)(ue,{status:u.status}),u.status==="needs_setup"&&(0,t.jsx)("span",{onClick:a(h=>{h.preventDefault(),h.stopPropagation()},"onClick"),children:(0,t.jsx)(K,{size:"xs",variant:"outline",onClick:a(()=>I(u),"onClick"),children:"Set up"})})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3 shrink-0",children:[(0,t.jsx)("span",{className:"sm:hidden",children:r.has(e.id)?(0,t.jsx)(O,{agentRef:l?$(l):e.id,runId:r.get(e.id).runId,liveCount:r.get(e.id).liveCount}):(0,t.jsx)(D,{status:e.status})}),(0,t.jsxs)("div",{className:"hidden sm:flex items-center gap-3",children:[r.has(e.id)&&(0,t.jsx)(O,{agentRef:l?$(l):e.id,runId:r.get(e.id).runId,liveCount:r.get(e.id).liveCount}),l&&(0,t.jsx)("div",{className:"hidden xl:flex items-center gap-3",children:(0,t.jsx)(he,{agent:l,environment:m?me:o.get(l.id)??z,showEnvironment:N})}),(0,t.jsx)("span",{className:"w-20 flex justify-end",children:(0,t.jsx)(D,{status:e.status})})]})]})]}),e.reports&&e.reports.length>0&&(0,t.jsx)("div",{className:"border-l border-border ml-4",children:e.reports.map(h=>(0,t.jsx)(fe,{node:h,depth:n+1,agentMap:i,liveRunByAgent:r,environmentByAgentId:o,environmentDataLoading:m,showEnvironment:N,tab:v,memberships:S,builtInByAgentId:w,onConfigureBuiltIn:I},h.id))})]})}a(fe,"OrgTreeNode");function he({agent:e,environment:n,showEnvironment:i}){const r=nt(e),o=Ue(e.adapterType);return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"w-44 min-w-0 leading-tight",children:[(0,t.jsx)("div",{className:"truncate font-mono text-xs text-muted-foreground",title:r??void 0,children:r??"—"}),(0,t.jsx)("div",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground/70",title:o,children:o})]}),i&&(0,t.jsxs)("div",{className:"w-44 min-w-0 leading-tight",children:[(0,t.jsx)("div",{className:"truncate text-xs text-muted-foreground",title:n.title,children:n.label}),(0,t.jsx)("div",{className:"truncate text-(length:--text-micro) text-muted-foreground/70",children:n.detail})]}),(0,t.jsx)("span",{className:"w-24 whitespace-nowrap text-right text-xs text-muted-foreground",children:e.lastHeartbeatAt?_e(e.lastHeartbeatAt):"—"})]})}a(he,"AgentMetaColumns");function O({agentRef:e,runId:n,liveCount:i}){return(0,t.jsxs)(ie,{to:`/agents/${e}/runs/${n}`,className:"flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-blue-500/10 hover:bg-blue-500/20 transition-colors no-underline",onClick:a(r=>r.stopPropagation(),"onClick"),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-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]}),(0,t.jsxs)("span",{className:"text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400",children:["Live",i>1?` (${i})`:""]})]})}a(O,"LiveRunIndicator");export{wt as Agents};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DvHeLBFO.js","assets/rolldown-runtime-ZpX3ckPj.js","assets/agent-avatar-url-BnmqahQ7.js","assets/preload-helper-CceJXRIF.js","assets/BreadcrumbContext-Bxr1TyKN.js","assets/label-YjU0jMtG.js","assets/mention-chips-ClRmijVb.js","assets/dist-CvM0_U_m.js","assets/dist-BrRwU9U9.js","assets/checkbox-5wFlZdZn.js","assets/check-BiXfODpl.js","assets/clipboard-CTmezHYG.js","assets/RoutineRunVariablesDialog-DMTFaEse.js","assets/alert-dialog-BxpRolrb.js","assets/AgentAvatar-DZh8tNnK.js","assets/MarkdownEditor-D7suACD6.js","assets/dist-CMegW-DS.js","assets/dist-BhxPxuMy.js","assets/StatusIcon-YdJnE47W.js","assets/badge-D5aOL1Ll.js","assets/bot-DpNd1tv2.js","assets/select-DRgGQ-iP.js","assets/ToastContext-Dh8dPdr5.js","assets/sheet-CACWxbsc.js","assets/heartbeats-Dae6h2SU.js","assets/useHiddenSettings-Dz7GWNDr.js","assets/health-D8T5Zr74.js","assets/rotate-ccw-2WnWy1fs.js","assets/environments-Bj-4l7Ol.js","assets/input-CtLHwxEw.js","assets/company-members-Dd6xBf6K.js","assets/card-PCL2aF_L.js","assets/EmptyState-DliXLd04.js","assets/PageSkeleton-BZF4K6Hf.js","assets/skeleton-DCrngTtF.js","assets/tabs-BfOtoFWj.js","assets/use-adapter-capabilities-JhD0-FlQ.js","assets/use-copy-action-qHyHFl14.js","assets/arrow-right-bnOoaiPg.js","assets/external-link-LnxJtUIq.js","assets/MarkdownBody-B5ygzgk6.js","assets/file-text-Ba5Wddur.js","assets/index-BM-RkEuH.css"])))=>i.map(i=>d[i]);
2
+ var Ie=Object.defineProperty;var a=(e,n)=>Ie(e,"name",{value:n,configurable:!0});import{i as ae}from"./rolldown-runtime-ZpX3ckPj.js";import{B as re,G as T,St as b,Va as Ae,_i as Ce,aa as j,ht as Se,ut as _e,z as $,za as Ee}from"./agent-avatar-url-BnmqahQ7.js";import{t as Le}from"./preload-helper-CceJXRIF.js";import{Ln as Me,ct as Te,f as ke,i as K,n as qe,r as ee,s as ie,yt as Pe}from"./BreadcrumbContext-Bxr1TyKN.js";import{m as le}from"./alert-dialog-BxpRolrb.js";import{t as oe}from"./AgentAvatar-DZh8tNnK.js";import{t as Be}from"./tabs-BfOtoFWj.js";import{t as te}from"./bot-DpNd1tv2.js";import{i as Fe,o as Re,t as $e}from"./heartbeats-Dae6h2SU.js";import{i as Ke,n as De,t as se}from"./environments-Bj-4l7Ol.js";import{t as ne}from"./EmptyState-DliXLd04.js";import{t as Oe}from"./PageSkeleton-BZF4K6Hf.js";import{Dt as ze,Ft as D,Gt as Ve,Kt as ce,Lt as Ge,Rt as Ue,Vt as He,Wt as Qe,Xt as We,Yt as ue,Zt as Xe,qt as Ye}from"./index-DvHeLBFO.js";var d=ae(Ae(),1),t=ae(Ee(),1),de=Ce,Ze=(0,d.lazy)(()=>Le(()=>import("./index-DvHeLBFO.js").then(e=>e.gt).then(e=>({default:e.ConfigureBuiltInAgentModal})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42]))),Je=["all","active","paused","error","builtin"],et=[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"paused",label:"Paused"},{value:"error",label:"Error"},{value:"builtin",label:"Built-in"}];function tt(e){return Je.includes(e)}a(tt,"isFilterTab");var z={label:"Local",detail:"Paperclip host",title:"Local - Paperclip host"},me={label:"—",detail:"Loading environment",title:"Loading environment"},pe=new Set(["terminated","pending_approval"]);function ge(e,n){return n==="all"?!0:n==="active"?e==="active"||e==="running"||e==="idle":n==="paused"?e==="paused":n==="error"?e==="error":!0}a(ge,"matchesFilter");function st(e,n,i){return e.filter(r=>pe.has(r.status)?!1:n==="builtin"?i.has(r.id):ge(r.status,n)).sort((r,o)=>r.name.localeCompare(o.name))}a(st,"filterAgents");function nt(e){const n=e.adapterConfig?.model;if(typeof n!="string")return null;const i=n.trim();return i.length>0?i:null}a(nt,"getConfiguredModel");function at(e){return e==="ssh"?"SSH":e.charAt(0).toUpperCase()+e.slice(1)}a(at,"formatEnvironmentDriver");function rt(e,n){const i=typeof e.config.provider=="string"?e.config.provider.trim():"";return i?n?.sandboxProviders?.[i]?.displayName??i:"Sandbox"}a(rt,"getSandboxProviderLabel");function it(e,n){const i=Ge(e)?"Managed by Paperclip":e.driver==="sandbox"?`${rt(e,n)} sandbox provider`:e.driver==="local"?"Paperclip host":at(e.driver);return{label:e.name,detail:i,title:`${e.name} - ${i}`}}a(it,"describeEnvironment");function lt(e){return{label:"Unknown environment",detail:e.slice(0,8),title:`Unknown environment - ${e}`}}a(lt,"describeMissingEnvironment");function ot(e,n,i,r){const o=e.defaultEnvironmentId??i;if(!o)return z;const m=n.get(o);return m?it(m,r):lt(o)}a(ot,"resolveAgentEnvironment");function xe(e,n,i){return e.reduce((r,o)=>{const m=xe(o.reports,n,i);return pe.has(o.status)?(r.push(...m),r):(((n==="builtin"?i.has(o.id):ge(o.status,n))||m.length>0)&&r.push({...o,reports:m}),r)},[]).sort((r,o)=>r.name.localeCompare(o.name))}a(xe,"filterOrgTree");function wt(){const{selectedCompanyId:e}=Se(),{openNewAgent:n}=Fe(),{setBreadcrumbs:i}=qe(),r=ke(),o=Me(),{isMobile:m}=Ke(),N=o.pathname.split("/").pop()??"all",v=tt(N)?N:"all",[S,w]=(0,d.useState)("org"),I=m,l=I?"list":S,{data:u}=j({queryKey:b.instance.settings,queryFn:a(()=>De.get(),"queryFn"),enabled:!!e}),p=u?.experimental.enableBuiltInAgents===!0,f=v==="builtin"&&!p?"all":v,k=(0,d.useMemo)(()=>et.filter(s=>s.value!=="builtin"||p),[p]),{data:h}=j({queryKey:b.builtInAgents.list(e),queryFn:a(()=>We.list(e),"queryFn"),enabled:!!e&&p}),_=(0,d.useMemo)(()=>{const s=new Map;if(!p)return s;for(const c of h??[])c.agentId&&s.set(c.agentId,c);return s},[h,p]),V=(0,d.useMemo)(()=>new Set(_.keys()),[_]),[q,P]=(0,d.useState)(null),{data:g,isLoading:ve,error:G}=j({queryKey:b.agents.list(e),queryFn:a(()=>ee.list(e),"queryFn"),enabled:!!e}),{data:A}=j({queryKey:b.org(e),queryFn:a(()=>ee.org(e),"queryFn"),enabled:!!e&&l==="org"}),E=u?.experimental.enableEnvironments===!0,{data:C}=j({queryKey:b.environments.list(e),queryFn:a(()=>se.list(e),"queryFn"),enabled:!!e&&E}),{data:U}=j({queryKey:b.environments.capabilities(e),queryFn:a(()=>se.capabilities(e),"queryFn"),enabled:!!e&&E}),H=[...b.liveRuns(e),"agents-page"],B=Ve({companyId:e,resourceKey:"live-runs:agents-page",queryKey:H,enabled:!!e,refetchInterval:15e3,leaderOnly:!0}),{data:F,dataUpdatedAt:be}=j({queryKey:H,queryFn:a(()=>$e.liveRunsForCompany(e),"queryFn"),enabled:B.enabled,refetchInterval:B.refetchInterval});Qe(B,F,be);const Q=Ye(e),L=(0,d.useMemo)(()=>{const s=new Map;for(const c of F??[]){if(c.status!=="running"&&c.status!=="queued")continue;const x=s.get(c.agentId);if(x){x.liveCount+=1;continue}s.set(c.agentId,{runId:c.id,liveCount:1})}return s},[F]),je=(0,d.useMemo)(()=>{const s=new Map;for(const c of g??[])s.set(c.id,c);return s},[g]),W=(0,d.useMemo)(()=>{const s=new Map;for(const c of C??[])s.set(c.id,c);return s},[C]),X=(0,d.useMemo)(()=>{const s=new Map;for(const c of g??[])s.set(c.id,ot(c,W,u?.defaultEnvironmentId??null,U));return s},[g,W,U,u?.defaultEnvironmentId]);if((0,d.useEffect)(()=>{i([{label:"Agents"}])},[i]),(0,d.useEffect)(()=>{e&&v==="builtin"&&u&&!p&&r("/agents/all",{replace:!0})},[p,u,r,v,e]),!e)return(0,t.jsx)(ne,{icon:te,message:"Select a company to view agents."});if(ve)return(0,t.jsx)(Oe,{variant:"list"});const y=st(g??[],f,V),R=xe(A??[],f,V),Y=E&&C===void 0,Z=E&&(C===void 0||C.length>1),ye=a(s=>Y?me:X.get(s)??z,"resolveRenderedEnvironment"),Ne=a(s=>{const c=s.orgChainHealth?.status==="invalid_org_chain",x=_.get(s.id),we=x?.status==="needs_setup"||x?.status==="pending_approval",M=x&&we?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(ue,{status:x.status}),x.status==="needs_setup"&&(0,t.jsx)("span",{onClick:a(J=>{J.preventDefault(),J.stopPropagation()},"onClick"),children:(0,t.jsx)(K,{size:"xs",variant:"outline",onClick:a(()=>P(x),"onClick"),children:"Set up"})})]}):null;return(0,t.jsx)(ze,{title:s.name,titleAccessory:(0,t.jsx)(Xe,{agentId:s.id,companyId:s.companyId}),titleClassName:"flex-1 xl:flex-none xl:w-56",titleTextClassName:"whitespace-normal break-words xl:truncate xl:whitespace-nowrap",subtitleClassName:"whitespace-normal break-words xl:truncate xl:whitespace-nowrap",subtitle:`${de[s.role]??s.role}${s.title?` - ${s.title}`:""}`,to:re(s),className:T("group",s.pausedAt&&f!=="paused"?"opacity-50":"",ce(Q.data,"agent",s.id)==="left"?"sm:text-foreground/55":""),leading:c?(0,t.jsx)(le,{className:"h-3.5 w-3.5 text-amber-500","aria-label":"Invalid reporting chain"}):(0,t.jsx)(oe,{agent:s,size:32}),secondaryRow:M?(0,t.jsx)("div",{className:"xl:hidden flex flex-wrap items-center gap-1.5",children:M}):void 0,meta:(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[M&&(0,t.jsx)("div",{className:"hidden xl:flex items-center gap-1.5",children:M}),(0,t.jsx)("div",{className:"hidden xl:flex items-center gap-3",children:(0,t.jsx)(he,{agent:s,environment:ye(s.id),showEnvironment:Z})})]}),metaSpacerClassName:"hidden xl:block",trailing:(0,t.jsx)("div",{className:"flex items-center gap-3",children:(0,t.jsxs)("div",{className:"hidden sm:flex items-center gap-3",children:[L.has(s.id)&&(0,t.jsx)(O,{agentRef:$(s),runId:L.get(s.id).runId,liveCount:L.get(s.id).liveCount}),(0,t.jsx)("span",{className:"w-20 flex justify-end",children:(0,t.jsx)(D,{status:s.status})})]})})},s.id)},"renderAgentRow");return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[(0,t.jsx)(Be,{value:f,onValueChange:a(s=>r(`/agents/${s}`),"onValueChange"),children:(0,t.jsx)(He,{items:k,value:f,onValueChange:a(s=>r(`/agents/${s}`),"onValueChange")})}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[!I&&(0,t.jsxs)("div",{className:"flex items-center border border-border",role:"group","aria-label":"View mode",children:[(0,t.jsx)("button",{className:T("p-1.5 transition-colors",l==="list"?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:a(()=>w("list"),"onClick"),title:"List view","aria-label":"List view","aria-pressed":l==="list",children:(0,t.jsx)(Re,{className:"h-3.5 w-3.5"})}),(0,t.jsx)("button",{className:T("p-1.5 transition-colors",l==="org"?"bg-accent text-foreground":"text-muted-foreground hover:bg-accent/50"),onClick:a(()=>w("org"),"onClick"),title:"Org chart view","aria-label":"Org chart view","aria-pressed":l==="org",children:(0,t.jsx)(Pe,{className:"h-3.5 w-3.5"})})]}),(0,t.jsxs)(K,{size:"sm",variant:"outline",onClick:n,children:[(0,t.jsx)(Te,{className:"h-3.5 w-3.5 mr-1.5"}),"New Agent"]})]})]}),y.length>0&&(0,t.jsxs)("p",{className:"text-xs text-muted-foreground",children:[y.length," agent",y.length!==1?"s":""]}),G&&(0,t.jsx)("p",{className:"text-sm text-destructive",children:G.message}),g&&g.length===0&&(0,t.jsx)(ne,{icon:te,message:"Create your first agent to get started.",action:"New Agent",onAction:n}),l==="list"&&y.length>0&&(0,t.jsx)("div",{children:y.map(Ne)}),l==="list"&&g&&g.length>0&&y.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No agents match the selected status."}),l==="org"&&R.length>0&&(0,t.jsx)("div",{className:"py-1",children:R.map(s=>(0,t.jsx)(fe,{node:s,depth:0,agentMap:je,liveRunByAgent:L,environmentByAgentId:X,environmentDataLoading:Y,showEnvironment:Z,tab:f,memberships:Q.data,builtInByAgentId:_,onConfigureBuiltIn:P},s.id))}),l==="org"&&A&&A.length>0&&R.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No agents match the selected status."}),l==="org"&&A&&A.length===0&&(0,t.jsx)("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No organizational hierarchy defined."}),q&&e&&(0,t.jsx)(d.Suspense,{fallback:null,children:(0,t.jsx)(Ze,{companyId:e,state:q,open:q!==null,onOpenChange:a(s=>{s||P(null)},"onOpenChange")})})]})}a(wt,"Agents");function fe({node:e,depth:n,agentMap:i,liveRunByAgent:r,environmentByAgentId:o,environmentDataLoading:m,showEnvironment:N,tab:v,memberships:S,builtInByAgentId:w,onConfigureBuiltIn:I}){const l=i.get(e.id),u=w.get(e.id),p=u?.status==="needs_setup"||u?.status==="pending_approval",f=!!(l&&l.orgChainHealth?.status==="invalid_org_chain"),k=ce(S,"agent",e.id);return(0,t.jsxs)("div",{style:{paddingLeft:n*24},children:[(0,t.jsxs)(ie,{to:l?re(l):`/agents/${e.id}`,className:T("group flex items-center gap-3 rounded-lg px-3 py-2 hover:bg-accent/50 transition-colors w-full text-left no-underline text-inherit",l?.pausedAt&&v!=="paused"&&"opacity-50",k==="left"&&"sm:text-foreground/55"),children:[f?(0,t.jsx)(le,{className:"h-3.5 w-3.5 shrink-0 text-amber-500","aria-label":"Invalid reporting chain"}):(0,t.jsx)(oe,{agent:l??e,size:24}),(0,t.jsxs)("div",{className:"flex-1 min-w-0 flex flex-wrap items-center gap-2",children:[(0,t.jsxs)("div",{className:"min-w-(--sz-7rem) truncate",children:[(0,t.jsx)("span",{className:"text-sm font-medium",children:e.name}),(0,t.jsxs)("span",{className:"text-xs text-muted-foreground ml-2",children:[de[e.role]??e.role,l?.title?` - ${l.title}`:""]})]}),u&&p&&(0,t.jsxs)("div",{className:"flex items-center gap-1.5 shrink-0",children:[(0,t.jsx)(ue,{status:u.status}),u.status==="needs_setup"&&(0,t.jsx)("span",{onClick:a(h=>{h.preventDefault(),h.stopPropagation()},"onClick"),children:(0,t.jsx)(K,{size:"xs",variant:"outline",onClick:a(()=>I(u),"onClick"),children:"Set up"})})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-3 shrink-0",children:[(0,t.jsx)("span",{className:"sm:hidden",children:r.has(e.id)?(0,t.jsx)(O,{agentRef:l?$(l):e.id,runId:r.get(e.id).runId,liveCount:r.get(e.id).liveCount}):(0,t.jsx)(D,{status:e.status})}),(0,t.jsxs)("div",{className:"hidden sm:flex items-center gap-3",children:[r.has(e.id)&&(0,t.jsx)(O,{agentRef:l?$(l):e.id,runId:r.get(e.id).runId,liveCount:r.get(e.id).liveCount}),l&&(0,t.jsx)("div",{className:"hidden xl:flex items-center gap-3",children:(0,t.jsx)(he,{agent:l,environment:m?me:o.get(l.id)??z,showEnvironment:N})}),(0,t.jsx)("span",{className:"w-20 flex justify-end",children:(0,t.jsx)(D,{status:e.status})})]})]})]}),e.reports&&e.reports.length>0&&(0,t.jsx)("div",{className:"border-l border-border ml-4",children:e.reports.map(h=>(0,t.jsx)(fe,{node:h,depth:n+1,agentMap:i,liveRunByAgent:r,environmentByAgentId:o,environmentDataLoading:m,showEnvironment:N,tab:v,memberships:S,builtInByAgentId:w,onConfigureBuiltIn:I},h.id))})]})}a(fe,"OrgTreeNode");function he({agent:e,environment:n,showEnvironment:i}){const r=nt(e),o=Ue(e.adapterType);return(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"w-44 min-w-0 leading-tight",children:[(0,t.jsx)("div",{className:"truncate font-mono text-xs text-muted-foreground",title:r??void 0,children:r??"—"}),(0,t.jsx)("div",{className:"truncate font-mono text-(length:--text-micro) text-muted-foreground/70",title:o,children:o})]}),i&&(0,t.jsxs)("div",{className:"w-44 min-w-0 leading-tight",children:[(0,t.jsx)("div",{className:"truncate text-xs text-muted-foreground",title:n.title,children:n.label}),(0,t.jsx)("div",{className:"truncate text-(length:--text-micro) text-muted-foreground/70",children:n.detail})]}),(0,t.jsx)("span",{className:"w-24 whitespace-nowrap text-right text-xs text-muted-foreground",children:e.lastHeartbeatAt?_e(e.lastHeartbeatAt):"—"})]})}a(he,"AgentMetaColumns");function O({agentRef:e,runId:n,liveCount:i}){return(0,t.jsxs)(ie,{to:`/agents/${e}/runs/${n}`,className:"flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-blue-500/10 hover:bg-blue-500/20 transition-colors no-underline",onClick:a(r=>r.stopPropagation(),"onClick"),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-400 opacity-75"}),(0,t.jsx)("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]}),(0,t.jsxs)("span",{className:"text-(length:--text-micro) font-medium text-blue-600 dark:text-blue-400",children:["Live",i>1?` (${i})`:""]})]})}a(O,"LiveRunIndicator");export{wt as Agents};
@@ -1 +1 @@
1
- var xe=Object.defineProperty;var r=(t,a)=>xe(t,"name",{value:a,configurable:!0});import{i as ne}from"./rolldown-runtime-ZpX3ckPj.js";import{G as pe,St as Y,Va as he,Wi as J,aa as X,ht as ge,ut as fe,za as ye}from"./agent-avatar-url-BnmqahQ7.js";import{Vn as ve,i as T,n as je,r as be,s as re}from"./BreadcrumbContext-Bxr1TyKN.js";import{r as ee,t as Ne}from"./AgentAvatar-DZh8tNnK.js";import{i as te,r as we,t as Ae}from"./tabs-BfOtoFWj.js";import{a as Te}from"./ToastContext-Dh8dPdr5.js";import{a as y,c as R,l as _,n as F,r as k}from"./select-DRgGQ-iP.js";import{t as se}from"./input-CtLHwxEw.js";import{o as Se,r as Ce}from"./company-members-Dd6xBf6K.js";import{r as v,t as j}from"./card-PCL2aF_L.js";import{t as Ee}from"./EmptyState-DliXLd04.js";import{Ot as Ie,b as ae,hn as Ue,in as Pe,rn as De,tn as Le,xn as Re}from"./index-D6WtpzBM.js";var l=ne(he(),1),e=ne(ye(),1),_e=50,n="__all",Fe=[{value:n,label:"All actions"},{value:"issue.",label:"Tasks"},{value:"agent.",label:"Agents"},{value:"heartbeat.",label:"Runs"},{value:"approval.",label:"Approvals"},{value:"project.",label:"Projects"},{value:"goal.",label:"Goals"},{value:"tool_gateway.",label:"Tools"},{value:"cost.",label:"Costs"},{value:"company.",label:"Company"}],ke=[{value:n,label:"All entities"},{value:"issue",label:"Task"},{value:"agent",label:"Agent"},{value:"project",label:"Project"},{value:"goal",label:"Goal"},{value:"company",label:"Company"}];function Be(t){if(!t)return;const a=new Date(`${t}T00:00:00.000Z`);return Number.isNaN(a.getTime())?void 0:a.toISOString()}r(Be,"toStartIso");function Ve(t){if(!t)return;const a=new Date(`${t}T23:59:59.999Z`);return Number.isNaN(a.getTime())?void 0:a.toISOString()}r(Ve,"toEndIso");function $e({record:t,agentMap:a,userProfileMap:d}){const u=t.agentId??(t.actorType==="agent"?t.actorId:null),c=u?a.get(u):null;if(c)return(0,e.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:c.name,children:[(0,e.jsx)("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground",children:(0,e.jsx)(Ne,{agent:c,size:16,className:"h-3 w-3"})}),(0,e.jsx)("span",{className:"truncate font-medium text-foreground",children:c.name})]});if(t.actorType==="user"&&t.actorId){const m=d.get(t.actorId);return(0,e.jsx)(ee,{name:m?.label??"User",avatarUrl:m?.image??null,size:"sm",className:"font-medium text-foreground"})}const h=t.actorType==="plugin"?"Plugin":t.actorType==="agent"?"Agent":t.actorType==="user"?"User":"System";return(0,e.jsx)(ee,{name:h,size:"sm",className:"font-medium text-foreground"})}r($e,"AuditActor");function qe({record:t}){const{issue:a,document:d}=t.entity,u=a?.identifier??a?.id??null;return u?(0,e.jsx)(re,{to:`/issues/${u}`,className:"font-medium text-primary hover:underline",children:a?.identifier?`${a.identifier}${a.title?` · ${a.title}`:""}`:"the task"}):d?(0,e.jsx)("span",{className:"font-medium text-foreground",children:d.key}):(0,e.jsx)("span",{className:"text-muted-foreground",children:t.entityType})}r(qe,"AuditEntityNode");function ze({record:t,agentMap:a,userProfileMap:d}){const u=Ie(t.action,t.details,{agentMap:a,userProfileMap:d}),c=t.responsibleUserId?d.get(t.responsibleUserId):null,h=!!(t.responsibleUserId&&!(t.actorType==="user"&&t.actorId===t.responsibleUserId)),m=c?.label??(t.responsibleUserId?"a user":null),g=t.entity.comment?.excerpt?.trim(),x=t.entity.issue&&t.entity.document?t.entity.document.key:null;return(0,e.jsx)("li",{className:"px-4 py-3 text-sm",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-1 text-foreground",children:[(0,e.jsx)($e,{record:t,agentMap:a,userProfileMap:d}),(0,e.jsx)("span",{className:"text-muted-foreground",children:u}),(0,e.jsx)(qe,{record:t})]}),g?(0,e.jsxs)("p",{className:"line-clamp-2 border-l-2 border-border pl-2 text-muted-foreground",children:["“",g,"”"]}):null,x?(0,e.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Document ",(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro)",children:x})]}):null,(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[h&&m?(0,e.jsxs)("span",{className:"inline-flex items-center rounded-full bg-muted px-2 py-0.5",children:["on behalf of ",m]}):null,t.runId&&t.agentId?(0,e.jsx)(re,{to:`/agents/${t.agentId}/runs/${t.runId}`,className:"text-primary hover:underline",children:"View run"}):null,(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro) opacity-70",children:t.action})]})]}),(0,e.jsx)("time",{className:"shrink-0 whitespace-nowrap text-xs text-muted-foreground",dateTime:t.createdAt,title:new Date(t.createdAt).toLocaleString(),children:fe(t.createdAt)})]})})}r(ze,"AuditRow");function Me(){return(0,e.jsx)(j,{children:(0,e.jsxs)(v,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)(Le,{className:"h-10 w-10 text-muted-foreground/50"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-sm font-medium text-foreground",children:"Agent audit is a Paperclip Enterprise view"}),(0,e.jsxs)("p",{className:"mx-auto mt-1 max-w-md text-sm text-muted-foreground",children:["The agent audit log gives you a searchable, exportable record of everything your agents did — every comment, task change, approval, and run — with the responsible person for each action. Ask an administrator to grant you the"," ",(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro)",children:"audit:view_agent_actions"})," ","permission to view it."]})]})]})})}r(Me,"AuditUpsell");function Oe({companyId:t,lockedAgentId:a,hideHeader:d,mode:u,onModeChange:c}){const{pushToast:h}=Te(),[m,g]=(0,l.useState)(n),[x,B]=(0,l.useState)(n),[S,V]=(0,l.useState)(n),[C,$]=(0,l.useState)(n),[E,q]=(0,l.useState)(""),[I,z]=(0,l.useState)(""),[Z,Q]=(0,l.useState)(!1),[U,W]=(0,l.useState)(!1),M=X({queryKey:Y.agents.list(t),queryFn:r(()=>be.list(t),"queryFn")}),O=X({queryKey:Y.access.companyUserDirectory(t),queryFn:r(()=>Se.listUserDirectory(t),"queryFn"),retry:!1}),ie=(0,l.useMemo)(()=>new Map((M.data??[]).map(s=>[s.id,s])),[M.data]),le=(0,l.useMemo)(()=>Ce(O.data?.users),[O.data]),f=a?"agents":u??"all",o={actorScope:f,agentId:a??(m===n?void 0:m),responsibleUserId:x===n?void 0:x,action:S===n?void 0:S,entityType:C===n?void 0:C,from:Be(E),to:Ve(I)},b=!!(!a&&m!==n||x!==n||S!==n||C!==n||E||I),i=Re({queryKey:Y.audit.agentActions(t,{actorScope:o.actorScope,agentId:o.agentId,responsibleUserId:o.responsibleUserId,action:o.action,entityType:o.entityType,from:o.from,to:o.to}),queryFn:r(({pageParam:s})=>ae.listAgentActions(t,{...o,limit:_e,cursor:s??void 0}),"queryFn"),initialPageParam:null,getNextPageParam:r(s=>s.nextCursor??void 0,"getNextPageParam"),retry:r((s,p)=>!(p instanceof J&&p.status===403)&&s<2,"retry")}),K=i.error instanceof J&&i.error.status===403,P=i.data?.pages.some(s=>s.accessTier==="basic")??!1,oe=i.data?.pages.some(s=>s.accessTier==="full")??!1,G=(0,l.useMemo)(()=>{const s=i.data?.pages??[];return(P?s.filter(p=>p.accessTier!=="full"):s).flatMap(p=>p.items)},[i.data,P]),D=P?"basic":i.data?.pages[0]?.accessTier,N=P&&oe,ce=a?!0:D==="full",de=!!(N&&U&&!i.isFetching),L=!!(!a&&!de&&(K&&b||N)),w=!!(K&&!a&&f==="agents"&&c),ue=!!(!a&&c&&!w&&(f==="agents"||D==="full"));(0,l.useEffect)(()=>{w&&c?.("all")},[w,c]),(0,l.useEffect)(()=>{!a&&(D==="basic"||L)&&(g(n),B(n),V(n),$(n),q(""),z(""))},[D,N,a,L]),(0,l.useEffect)(()=>{if(!N){U&&W(!1);return}U||(W(!0),i.refetch())},[U,i,N]);const H=r(()=>{g(n),B(n),V(n),$(n),q(""),z("")},"clearFilters"),me=r(async()=>{Q(!0);try{const s=await ae.exportAgentActionsCsv(t,{actorScope:o.actorScope,agentId:o.agentId,responsibleUserId:o.responsibleUserId,action:o.action,entityType:o.entityType,from:o.from,to:o.to}),p=URL.createObjectURL(s),A=document.createElement("a");A.href=p,A.download=`${f==="agents"?"agent-audit":"activity"}-${t}.csv`,document.body.appendChild(A),A.click(),A.remove(),window.setTimeout(()=>URL.revokeObjectURL(p),5e3),h({title:"Audit exported",body:"Your CSV download has started.",tone:"success"})}catch(s){h({title:"Export failed",body:s instanceof Error?s.message:"Could not export the audit log.",tone:"error"})}finally{Q(!1)}},"handleExport");return K&&!L&&!w?(0,e.jsx)(Me,{}):(0,e.jsxs)("div",{className:"space-y-4",children:[d?null:(0,e.jsx)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:(0,e.jsxs)("div",{children:[(0,e.jsx)("h1",{className:"text-lg font-semibold text-foreground",children:"Activity"}),(0,e.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:f==="agents"?"Every recorded agent action, newest first — with the responsible person and run behind each one.":"Everything happening in your company, newest first — people, agents, and the system. Each line is one recorded action."})]})}),ue?(0,e.jsx)(Ae,{value:f,onValueChange:r(s=>c?.(s),"onValueChange"),children:(0,e.jsxs)(we,{"aria-label":"Activity scope",children:[(0,e.jsx)(te,{value:"all",children:"All activity"}),(0,e.jsx)(te,{value:"agents",children:"Agent actions"})]})}):null,ce?(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[a?null:(0,e.jsxs)(F,{value:m,onValueChange:g,children:[(0,e.jsx)(R,{className:"w-40",children:(0,e.jsx)(_,{placeholder:"Agent"})}),(0,e.jsxs)(k,{children:[(0,e.jsx)(y,{value:n,children:"All agents"}),(M.data??[]).map(s=>(0,e.jsx)(y,{value:s.id,children:s.name},s.id))]})]}),(0,e.jsxs)(F,{value:x,onValueChange:B,children:[(0,e.jsx)(R,{className:"w-52",children:(0,e.jsx)(_,{placeholder:"Responsible user"})}),(0,e.jsxs)(k,{children:[(0,e.jsx)(y,{value:n,children:"All responsible users"}),(O.data?.users??[]).map(s=>(0,e.jsx)(y,{value:s.principalId,children:s.user?.name??s.user?.email??s.principalId.slice(0,8)},s.principalId))]})]}),(0,e.jsxs)(F,{value:S,onValueChange:V,children:[(0,e.jsx)(R,{className:"w-36",children:(0,e.jsx)(_,{placeholder:"Action"})}),(0,e.jsx)(k,{children:Fe.map(s=>(0,e.jsx)(y,{value:s.value,children:s.label},s.value))})]}),(0,e.jsxs)(F,{value:C,onValueChange:$,children:[(0,e.jsx)(R,{className:"w-36",children:(0,e.jsx)(_,{placeholder:"Entity"})}),(0,e.jsx)(k,{children:ke.map(s=>(0,e.jsx)(y,{value:s.value,children:s.label},s.value))})]}),(0,e.jsx)(se,{type:"date","aria-label":"From date",value:E,max:I||void 0,onChange:r(s=>q(s.target.value),"onChange"),className:"w-36"}),(0,e.jsx)(se,{type:"date","aria-label":"To date",value:I,min:E||void 0,onChange:r(s=>z(s.target.value),"onChange"),className:"w-36"}),b?(0,e.jsx)(T,{variant:"ghost",size:"sm",onClick:H,children:"Clear filters"}):null,(0,e.jsxs)(T,{variant:"outline",size:"sm",className:"ml-auto",onClick:me,disabled:Z||i.isLoading||G.length===0,children:[(0,e.jsx)(Ue,{className:"mr-1.5 h-4 w-4"}),Z?"Exporting…":"Export CSV"]})]}):null,L||w?(0,e.jsx)(j,{children:(0,e.jsx)(v,{className:"py-14 text-center text-sm text-muted-foreground",children:"Refreshing audit access…"})}):i.isLoading?(0,e.jsx)(j,{children:(0,e.jsx)(v,{className:"py-14 text-center text-sm text-muted-foreground",children:"Loading…"})}):i.error?(0,e.jsx)(j,{children:(0,e.jsxs)(v,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:i.error instanceof Error?i.error.message:"Failed to load the audit log."}),(0,e.jsx)(T,{variant:"outline",size:"sm",onClick:r(()=>i.refetch(),"onClick"),children:"Try again"})]})}):G.length===0?(0,e.jsx)(j,{children:(0,e.jsxs)(v,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)(De,{className:"h-10 w-10 text-muted-foreground/40"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-sm font-medium text-foreground",children:b?"No actions match these filters":"Nothing here yet"}),(0,e.jsx)("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:b?"Try a wider date range or different filters.":f==="agents"?"As soon as your agents start doing things, their actions show up here.":"As soon as anyone in your company does something, it shows up here."})]}),b?(0,e.jsx)(T,{variant:"outline",size:"sm",onClick:H,children:"Clear filters"}):null]})}):(0,e.jsx)(j,{children:(0,e.jsx)(v,{className:"px-0 py-0",children:(0,e.jsx)("ul",{className:pe("divide-y divide-border"),children:G.map(s=>(0,e.jsx)(ze,{record:s,agentMap:ie,userProfileMap:le},s.id))})})}),i.hasNextPage?(0,e.jsx)("div",{className:"flex justify-center",children:(0,e.jsx)(T,{variant:"outline",size:"sm",onClick:r(()=>i.fetchNextPage(),"onClick"),disabled:i.isFetchingNextPage,children:i.isFetchingNextPage?"Loading…":"Load more"})}):null,(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Recorded by Paperclip — entries can't be edited. Sensitive values are never stored."})]})}r(Oe,"AuditFeed");function nt(){const{selectedCompanyId:t}=ge(),{setBreadcrumbs:a}=je(),[d,u]=ve(),c=d.get("mode")==="agents"?"agents":"all";(0,l.useEffect)(()=>{a([{label:"Activity"}])},[a]);const h=(0,l.useCallback)(m=>{u(g=>{const x=new URLSearchParams(g);return m==="agents"?x.set("mode","agents"):x.delete("mode"),x},{replace:!0})},[u]);return t?(0,e.jsx)(Oe,{companyId:t,mode:c,onModeChange:h}):(0,e.jsx)(Ee,{icon:Pe,message:"Select a company to view activity."})}r(nt,"CompanyActivity");export{nt as CompanyActivity};
1
+ var xe=Object.defineProperty;var r=(t,a)=>xe(t,"name",{value:a,configurable:!0});import{i as ne}from"./rolldown-runtime-ZpX3ckPj.js";import{G as pe,St as Y,Va as he,Wi as J,aa as X,ht as ge,ut as fe,za as ye}from"./agent-avatar-url-BnmqahQ7.js";import{Vn as ve,i as T,n as je,r as be,s as re}from"./BreadcrumbContext-Bxr1TyKN.js";import{r as ee,t as Ne}from"./AgentAvatar-DZh8tNnK.js";import{i as te,r as we,t as Ae}from"./tabs-BfOtoFWj.js";import{a as Te}from"./ToastContext-Dh8dPdr5.js";import{a as y,c as R,l as _,n as F,r as k}from"./select-DRgGQ-iP.js";import{t as se}from"./input-CtLHwxEw.js";import{o as Se,r as Ce}from"./company-members-Dd6xBf6K.js";import{r as v,t as j}from"./card-PCL2aF_L.js";import{t as Ee}from"./EmptyState-DliXLd04.js";import{Ot as Ie,b as ae,hn as Ue,in as Pe,rn as De,tn as Le,xn as Re}from"./index-DvHeLBFO.js";var l=ne(he(),1),e=ne(ye(),1),_e=50,n="__all",Fe=[{value:n,label:"All actions"},{value:"issue.",label:"Tasks"},{value:"agent.",label:"Agents"},{value:"heartbeat.",label:"Runs"},{value:"approval.",label:"Approvals"},{value:"project.",label:"Projects"},{value:"goal.",label:"Goals"},{value:"tool_gateway.",label:"Tools"},{value:"cost.",label:"Costs"},{value:"company.",label:"Company"}],ke=[{value:n,label:"All entities"},{value:"issue",label:"Task"},{value:"agent",label:"Agent"},{value:"project",label:"Project"},{value:"goal",label:"Goal"},{value:"company",label:"Company"}];function Be(t){if(!t)return;const a=new Date(`${t}T00:00:00.000Z`);return Number.isNaN(a.getTime())?void 0:a.toISOString()}r(Be,"toStartIso");function Ve(t){if(!t)return;const a=new Date(`${t}T23:59:59.999Z`);return Number.isNaN(a.getTime())?void 0:a.toISOString()}r(Ve,"toEndIso");function $e({record:t,agentMap:a,userProfileMap:d}){const u=t.agentId??(t.actorType==="agent"?t.actorId:null),c=u?a.get(u):null;if(c)return(0,e.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:c.name,children:[(0,e.jsx)("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground",children:(0,e.jsx)(Ne,{agent:c,size:16,className:"h-3 w-3"})}),(0,e.jsx)("span",{className:"truncate font-medium text-foreground",children:c.name})]});if(t.actorType==="user"&&t.actorId){const m=d.get(t.actorId);return(0,e.jsx)(ee,{name:m?.label??"User",avatarUrl:m?.image??null,size:"sm",className:"font-medium text-foreground"})}const h=t.actorType==="plugin"?"Plugin":t.actorType==="agent"?"Agent":t.actorType==="user"?"User":"System";return(0,e.jsx)(ee,{name:h,size:"sm",className:"font-medium text-foreground"})}r($e,"AuditActor");function qe({record:t}){const{issue:a,document:d}=t.entity,u=a?.identifier??a?.id??null;return u?(0,e.jsx)(re,{to:`/issues/${u}`,className:"font-medium text-primary hover:underline",children:a?.identifier?`${a.identifier}${a.title?` · ${a.title}`:""}`:"the task"}):d?(0,e.jsx)("span",{className:"font-medium text-foreground",children:d.key}):(0,e.jsx)("span",{className:"text-muted-foreground",children:t.entityType})}r(qe,"AuditEntityNode");function ze({record:t,agentMap:a,userProfileMap:d}){const u=Ie(t.action,t.details,{agentMap:a,userProfileMap:d}),c=t.responsibleUserId?d.get(t.responsibleUserId):null,h=!!(t.responsibleUserId&&!(t.actorType==="user"&&t.actorId===t.responsibleUserId)),m=c?.label??(t.responsibleUserId?"a user":null),g=t.entity.comment?.excerpt?.trim(),x=t.entity.issue&&t.entity.document?t.entity.document.key:null;return(0,e.jsx)("li",{className:"px-4 py-3 text-sm",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-1 text-foreground",children:[(0,e.jsx)($e,{record:t,agentMap:a,userProfileMap:d}),(0,e.jsx)("span",{className:"text-muted-foreground",children:u}),(0,e.jsx)(qe,{record:t})]}),g?(0,e.jsxs)("p",{className:"line-clamp-2 border-l-2 border-border pl-2 text-muted-foreground",children:["“",g,"”"]}):null,x?(0,e.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Document ",(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro)",children:x})]}):null,(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[h&&m?(0,e.jsxs)("span",{className:"inline-flex items-center rounded-full bg-muted px-2 py-0.5",children:["on behalf of ",m]}):null,t.runId&&t.agentId?(0,e.jsx)(re,{to:`/agents/${t.agentId}/runs/${t.runId}`,className:"text-primary hover:underline",children:"View run"}):null,(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro) opacity-70",children:t.action})]})]}),(0,e.jsx)("time",{className:"shrink-0 whitespace-nowrap text-xs text-muted-foreground",dateTime:t.createdAt,title:new Date(t.createdAt).toLocaleString(),children:fe(t.createdAt)})]})})}r(ze,"AuditRow");function Me(){return(0,e.jsx)(j,{children:(0,e.jsxs)(v,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)(Le,{className:"h-10 w-10 text-muted-foreground/50"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-sm font-medium text-foreground",children:"Agent audit is a Paperclip Enterprise view"}),(0,e.jsxs)("p",{className:"mx-auto mt-1 max-w-md text-sm text-muted-foreground",children:["The agent audit log gives you a searchable, exportable record of everything your agents did — every comment, task change, approval, and run — with the responsible person for each action. Ask an administrator to grant you the"," ",(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro)",children:"audit:view_agent_actions"})," ","permission to view it."]})]})]})})}r(Me,"AuditUpsell");function Oe({companyId:t,lockedAgentId:a,hideHeader:d,mode:u,onModeChange:c}){const{pushToast:h}=Te(),[m,g]=(0,l.useState)(n),[x,B]=(0,l.useState)(n),[S,V]=(0,l.useState)(n),[C,$]=(0,l.useState)(n),[E,q]=(0,l.useState)(""),[I,z]=(0,l.useState)(""),[Z,Q]=(0,l.useState)(!1),[U,W]=(0,l.useState)(!1),M=X({queryKey:Y.agents.list(t),queryFn:r(()=>be.list(t),"queryFn")}),O=X({queryKey:Y.access.companyUserDirectory(t),queryFn:r(()=>Se.listUserDirectory(t),"queryFn"),retry:!1}),ie=(0,l.useMemo)(()=>new Map((M.data??[]).map(s=>[s.id,s])),[M.data]),le=(0,l.useMemo)(()=>Ce(O.data?.users),[O.data]),f=a?"agents":u??"all",o={actorScope:f,agentId:a??(m===n?void 0:m),responsibleUserId:x===n?void 0:x,action:S===n?void 0:S,entityType:C===n?void 0:C,from:Be(E),to:Ve(I)},b=!!(!a&&m!==n||x!==n||S!==n||C!==n||E||I),i=Re({queryKey:Y.audit.agentActions(t,{actorScope:o.actorScope,agentId:o.agentId,responsibleUserId:o.responsibleUserId,action:o.action,entityType:o.entityType,from:o.from,to:o.to}),queryFn:r(({pageParam:s})=>ae.listAgentActions(t,{...o,limit:_e,cursor:s??void 0}),"queryFn"),initialPageParam:null,getNextPageParam:r(s=>s.nextCursor??void 0,"getNextPageParam"),retry:r((s,p)=>!(p instanceof J&&p.status===403)&&s<2,"retry")}),K=i.error instanceof J&&i.error.status===403,P=i.data?.pages.some(s=>s.accessTier==="basic")??!1,oe=i.data?.pages.some(s=>s.accessTier==="full")??!1,G=(0,l.useMemo)(()=>{const s=i.data?.pages??[];return(P?s.filter(p=>p.accessTier!=="full"):s).flatMap(p=>p.items)},[i.data,P]),D=P?"basic":i.data?.pages[0]?.accessTier,N=P&&oe,ce=a?!0:D==="full",de=!!(N&&U&&!i.isFetching),L=!!(!a&&!de&&(K&&b||N)),w=!!(K&&!a&&f==="agents"&&c),ue=!!(!a&&c&&!w&&(f==="agents"||D==="full"));(0,l.useEffect)(()=>{w&&c?.("all")},[w,c]),(0,l.useEffect)(()=>{!a&&(D==="basic"||L)&&(g(n),B(n),V(n),$(n),q(""),z(""))},[D,N,a,L]),(0,l.useEffect)(()=>{if(!N){U&&W(!1);return}U||(W(!0),i.refetch())},[U,i,N]);const H=r(()=>{g(n),B(n),V(n),$(n),q(""),z("")},"clearFilters"),me=r(async()=>{Q(!0);try{const s=await ae.exportAgentActionsCsv(t,{actorScope:o.actorScope,agentId:o.agentId,responsibleUserId:o.responsibleUserId,action:o.action,entityType:o.entityType,from:o.from,to:o.to}),p=URL.createObjectURL(s),A=document.createElement("a");A.href=p,A.download=`${f==="agents"?"agent-audit":"activity"}-${t}.csv`,document.body.appendChild(A),A.click(),A.remove(),window.setTimeout(()=>URL.revokeObjectURL(p),5e3),h({title:"Audit exported",body:"Your CSV download has started.",tone:"success"})}catch(s){h({title:"Export failed",body:s instanceof Error?s.message:"Could not export the audit log.",tone:"error"})}finally{Q(!1)}},"handleExport");return K&&!L&&!w?(0,e.jsx)(Me,{}):(0,e.jsxs)("div",{className:"space-y-4",children:[d?null:(0,e.jsx)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:(0,e.jsxs)("div",{children:[(0,e.jsx)("h1",{className:"text-lg font-semibold text-foreground",children:"Activity"}),(0,e.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:f==="agents"?"Every recorded agent action, newest first — with the responsible person and run behind each one.":"Everything happening in your company, newest first — people, agents, and the system. Each line is one recorded action."})]})}),ue?(0,e.jsx)(Ae,{value:f,onValueChange:r(s=>c?.(s),"onValueChange"),children:(0,e.jsxs)(we,{"aria-label":"Activity scope",children:[(0,e.jsx)(te,{value:"all",children:"All activity"}),(0,e.jsx)(te,{value:"agents",children:"Agent actions"})]})}):null,ce?(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[a?null:(0,e.jsxs)(F,{value:m,onValueChange:g,children:[(0,e.jsx)(R,{className:"w-40",children:(0,e.jsx)(_,{placeholder:"Agent"})}),(0,e.jsxs)(k,{children:[(0,e.jsx)(y,{value:n,children:"All agents"}),(M.data??[]).map(s=>(0,e.jsx)(y,{value:s.id,children:s.name},s.id))]})]}),(0,e.jsxs)(F,{value:x,onValueChange:B,children:[(0,e.jsx)(R,{className:"w-52",children:(0,e.jsx)(_,{placeholder:"Responsible user"})}),(0,e.jsxs)(k,{children:[(0,e.jsx)(y,{value:n,children:"All responsible users"}),(O.data?.users??[]).map(s=>(0,e.jsx)(y,{value:s.principalId,children:s.user?.name??s.user?.email??s.principalId.slice(0,8)},s.principalId))]})]}),(0,e.jsxs)(F,{value:S,onValueChange:V,children:[(0,e.jsx)(R,{className:"w-36",children:(0,e.jsx)(_,{placeholder:"Action"})}),(0,e.jsx)(k,{children:Fe.map(s=>(0,e.jsx)(y,{value:s.value,children:s.label},s.value))})]}),(0,e.jsxs)(F,{value:C,onValueChange:$,children:[(0,e.jsx)(R,{className:"w-36",children:(0,e.jsx)(_,{placeholder:"Entity"})}),(0,e.jsx)(k,{children:ke.map(s=>(0,e.jsx)(y,{value:s.value,children:s.label},s.value))})]}),(0,e.jsx)(se,{type:"date","aria-label":"From date",value:E,max:I||void 0,onChange:r(s=>q(s.target.value),"onChange"),className:"w-36"}),(0,e.jsx)(se,{type:"date","aria-label":"To date",value:I,min:E||void 0,onChange:r(s=>z(s.target.value),"onChange"),className:"w-36"}),b?(0,e.jsx)(T,{variant:"ghost",size:"sm",onClick:H,children:"Clear filters"}):null,(0,e.jsxs)(T,{variant:"outline",size:"sm",className:"ml-auto",onClick:me,disabled:Z||i.isLoading||G.length===0,children:[(0,e.jsx)(Ue,{className:"mr-1.5 h-4 w-4"}),Z?"Exporting…":"Export CSV"]})]}):null,L||w?(0,e.jsx)(j,{children:(0,e.jsx)(v,{className:"py-14 text-center text-sm text-muted-foreground",children:"Refreshing audit access…"})}):i.isLoading?(0,e.jsx)(j,{children:(0,e.jsx)(v,{className:"py-14 text-center text-sm text-muted-foreground",children:"Loading…"})}):i.error?(0,e.jsx)(j,{children:(0,e.jsxs)(v,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:i.error instanceof Error?i.error.message:"Failed to load the audit log."}),(0,e.jsx)(T,{variant:"outline",size:"sm",onClick:r(()=>i.refetch(),"onClick"),children:"Try again"})]})}):G.length===0?(0,e.jsx)(j,{children:(0,e.jsxs)(v,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)(De,{className:"h-10 w-10 text-muted-foreground/40"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-sm font-medium text-foreground",children:b?"No actions match these filters":"Nothing here yet"}),(0,e.jsx)("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:b?"Try a wider date range or different filters.":f==="agents"?"As soon as your agents start doing things, their actions show up here.":"As soon as anyone in your company does something, it shows up here."})]}),b?(0,e.jsx)(T,{variant:"outline",size:"sm",onClick:H,children:"Clear filters"}):null]})}):(0,e.jsx)(j,{children:(0,e.jsx)(v,{className:"px-0 py-0",children:(0,e.jsx)("ul",{className:pe("divide-y divide-border"),children:G.map(s=>(0,e.jsx)(ze,{record:s,agentMap:ie,userProfileMap:le},s.id))})})}),i.hasNextPage?(0,e.jsx)("div",{className:"flex justify-center",children:(0,e.jsx)(T,{variant:"outline",size:"sm",onClick:r(()=>i.fetchNextPage(),"onClick"),disabled:i.isFetchingNextPage,children:i.isFetchingNextPage?"Loading…":"Load more"})}):null,(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Recorded by Paperclip — entries can't be edited. Sensitive values are never stored."})]})}r(Oe,"AuditFeed");function nt(){const{selectedCompanyId:t}=ge(),{setBreadcrumbs:a}=je(),[d,u]=ve(),c=d.get("mode")==="agents"?"agents":"all";(0,l.useEffect)(()=>{a([{label:"Activity"}])},[a]);const h=(0,l.useCallback)(m=>{u(g=>{const x=new URLSearchParams(g);return m==="agents"?x.set("mode","agents"):x.delete("mode"),x},{replace:!0})},[u]);return t?(0,e.jsx)(Oe,{companyId:t,mode:c,onModeChange:h}):(0,e.jsx)(Ee,{icon:Pe,message:"Select a company to view activity."})}r(nt,"CompanyActivity");export{nt as CompanyActivity};
@@ -1,4 +1,4 @@
1
- var Be=Object.defineProperty;var d=(e,r)=>Be(e,"name",{value:r,configurable:!0});import{i as we}from"./rolldown-runtime-ZpX3ckPj.js";import{$t as De,Ct as _e,G as ne,St as G,Ui as te,Va as Ue,aa as X,ht as We,ia as pe,kr as qe,za as Ke}from"./agent-avatar-url-BnmqahQ7.js";import{Ln as Ye,f as Ze,i as H,it as Ge,lt as B,n as Xe,r as He,y as Ve}from"./BreadcrumbContext-Bxr1TyKN.js";import{Z as Je}from"./mention-chips-ClRmijVb.js";import{h as Qe}from"./StatusIcon-YdJnE47W.js";import{a as et}from"./ToastContext-Dh8dPdr5.js";import{t as fe}from"./MarkdownBody-B5ygzgk6.js";import{r as tt}from"./badge-D5aOL1Ll.js";import{t as me}from"./rotate-ccw-2WnWy1fs.js";import{t as D}from"./EmptyState-DliXLd04.js";import{t as st}from"./PageSkeleton-BZF4K6Hf.js";import{Jt as nt,Pt as rt,Ut as ot,a as at,dt as it,ft as he,hn as ct,ht as lt,i as dt,mt as ut,n as pt,pt as ft,r as mt,t as je,ut as ht}from"./index-D6WtpzBM.js";var h=we(Ue(),1),xt=["agents","projects","skills","routines","tasks","attachments"],gt={agents:"Agents",projects:"Projects",skills:"Skills",routines:"Routines",tasks:"Tasks",attachments:"Attachments"};function bt(){return{agents:!0,projects:!0,skills:!0,routines:!0,tasks:!0,attachments:!0}}d(bt,"buildDefaultExportCategorySelection");function ye(e){return e.tasks||e.routines}d(ye,"isAttachmentsCategoryEnabled");function ve(e){const r=new Set;for(const a of e){if(!a.recurring)continue;const n=a.path.trim();if(!n)continue;r.add(n);const o=n.lastIndexOf("/");o>=0&&r.add(`${n.slice(0,o+1)}`)}return r}d(ve,"buildRecurringTaskPrefixes");function wt(e,r){for(const a of r)if(e===a||e.startsWith(a))return!0;return!1}d(wt,"isRecurringTaskFile");function jt(e){const r=new Set,a=new Set;for(const n of e)for(const o of n.attachments??[]){const c=o.sha256.trim().toLowerCase();c&&(n.recurring?r:a).add(c)}return{recurring:r,oneOff:a}}d(jt,"buildAttachmentShaOwnership");var yt=new Set(["agents","projects","skills","routines","tasks"]);function vt(e){const r=new Map;for(const a of e){const n=a.sha256.trim().toLowerCase();if(!n)continue;const o=r.get(n)??new Set,c=a.ownedBy&&a.ownedBy.length>0?a.ownedBy:["always"];for(const p of c)o.add(p);r.set(n,o)}return r}d(vt,"buildEmbeddedAssetShaOwnership");function kt(e,r){for(const a of e)if(!yt.has(a)||r[a])return!0;return!1}d(kt,"isEmbeddedAssetBlobIncluded");function ke(e,r){return e.startsWith("agents/")?"agents":e.startsWith("projects/")?"projects":e.startsWith("skills/")?"skills":e.startsWith("tasks/")?wt(e,r)?"routines":"tasks":e.startsWith("blobs/")?"attachments":null}d(ke,"categorizeExportFile");function St(e,r){const a=ve(r),n={agents:0,projects:0,skills:0,routines:0,tasks:0,attachments:0};for(const o of e){const c=ke(o,a);c&&(n[c]+=1)}return n}d(St,"countExportFilesByCategory");function Ct(e){const{filePaths:r,issues:a,categories:n}=e,o=ve(a),c=jt(a),p=vt(e.embeddedAssets??[]),f=n.attachments&&ye(n),x=new Set;for(const l of r){const b=ke(l,o);if(b===null){x.add(l);continue}if(b==="attachments"){const i=l.slice(6).trim().toLowerCase(),g=p.get(i);if(g&&kt(g,n)){x.add(l);continue}if(!f)continue;const j=c.recurring.has(i),y=c.oneOff.has(i);!j&&!y?g||x.add(l):(y&&n.tasks||j&&n.routines)&&x.add(l);continue}n[b]&&x.add(l)}return x}d(Ct,"buildExportCheckedFiles");function Se(e,r){if(!r.has(e))return r.add(e),e;let a=2;for(;;){const n=`${e}-${a}`;if(!r.has(n))return r.add(n),n;a+=1}}d(Se,"uniqueSlug");function Et(e){const r=new Set,a=new Map,n=[...e].sort((o,c)=>o.name.localeCompare(c.name));for(const o of n){const c=qe(o.name)??"agent";a.set(o.id,Se(c,r))}return a}d(Et,"buildPortableAgentSlugMap");function Nt(e){const r=new Set,a=new Map,n=[...e].sort((o,c)=>o.name.localeCompare(c.name));for(const o of n){const c=De(o.name,o.name);a.set(o.id,Se(c,r))}return a}d(Nt,"buildPortableProjectSlugMap");function At(e){const r=Et(e.agents),a=Nt(e.projects),n={agents:e.orderedAgents.map(o=>r.get(o.id)).filter(o=>!!o),projects:e.orderedProjects.map(o=>a.get(o.id)).filter(o=>!!o)};return n.agents.length>0||n.projects.length>0?n:void 0}d(At,"buildPortableSidebarOrder");var t=we(Ke(),1);function Ce(e){const r=new Set,a=new Set,n=new Set;for(const o of e){const c=o.match(/^agents\/([^/]+)\//);c&&r.add(c[1]);const p=o.match(/^projects\/([^/]+)\//);p&&a.add(p[1]);const f=o.match(/^tasks\/([^/]+)\//);f&&n.add(f[1])}return{agents:r,projects:a,tasks:n,routines:new Set(n)}}d(Ce,"checkedSlugs");function Pt(e,r){const a=Ce(r),n=e.split(`
1
+ var Be=Object.defineProperty;var d=(e,r)=>Be(e,"name",{value:r,configurable:!0});import{i as we}from"./rolldown-runtime-ZpX3ckPj.js";import{$t as De,Ct as _e,G as ne,St as G,Ui as te,Va as Ue,aa as X,ht as We,ia as pe,kr as qe,za as Ke}from"./agent-avatar-url-BnmqahQ7.js";import{Ln as Ye,f as Ze,i as H,it as Ge,lt as B,n as Xe,r as He,y as Ve}from"./BreadcrumbContext-Bxr1TyKN.js";import{Z as Je}from"./mention-chips-ClRmijVb.js";import{h as Qe}from"./StatusIcon-YdJnE47W.js";import{a as et}from"./ToastContext-Dh8dPdr5.js";import{t as fe}from"./MarkdownBody-B5ygzgk6.js";import{r as tt}from"./badge-D5aOL1Ll.js";import{t as me}from"./rotate-ccw-2WnWy1fs.js";import{t as D}from"./EmptyState-DliXLd04.js";import{t as st}from"./PageSkeleton-BZF4K6Hf.js";import{Jt as nt,Pt as rt,Ut as ot,a as at,dt as it,ft as he,hn as ct,ht as lt,i as dt,mt as ut,n as pt,pt as ft,r as mt,t as je,ut as ht}from"./index-DvHeLBFO.js";var h=we(Ue(),1),xt=["agents","projects","skills","routines","tasks","attachments"],gt={agents:"Agents",projects:"Projects",skills:"Skills",routines:"Routines",tasks:"Tasks",attachments:"Attachments"};function bt(){return{agents:!0,projects:!0,skills:!0,routines:!0,tasks:!0,attachments:!0}}d(bt,"buildDefaultExportCategorySelection");function ye(e){return e.tasks||e.routines}d(ye,"isAttachmentsCategoryEnabled");function ve(e){const r=new Set;for(const a of e){if(!a.recurring)continue;const n=a.path.trim();if(!n)continue;r.add(n);const o=n.lastIndexOf("/");o>=0&&r.add(`${n.slice(0,o+1)}`)}return r}d(ve,"buildRecurringTaskPrefixes");function wt(e,r){for(const a of r)if(e===a||e.startsWith(a))return!0;return!1}d(wt,"isRecurringTaskFile");function jt(e){const r=new Set,a=new Set;for(const n of e)for(const o of n.attachments??[]){const c=o.sha256.trim().toLowerCase();c&&(n.recurring?r:a).add(c)}return{recurring:r,oneOff:a}}d(jt,"buildAttachmentShaOwnership");var yt=new Set(["agents","projects","skills","routines","tasks"]);function vt(e){const r=new Map;for(const a of e){const n=a.sha256.trim().toLowerCase();if(!n)continue;const o=r.get(n)??new Set,c=a.ownedBy&&a.ownedBy.length>0?a.ownedBy:["always"];for(const p of c)o.add(p);r.set(n,o)}return r}d(vt,"buildEmbeddedAssetShaOwnership");function kt(e,r){for(const a of e)if(!yt.has(a)||r[a])return!0;return!1}d(kt,"isEmbeddedAssetBlobIncluded");function ke(e,r){return e.startsWith("agents/")?"agents":e.startsWith("projects/")?"projects":e.startsWith("skills/")?"skills":e.startsWith("tasks/")?wt(e,r)?"routines":"tasks":e.startsWith("blobs/")?"attachments":null}d(ke,"categorizeExportFile");function St(e,r){const a=ve(r),n={agents:0,projects:0,skills:0,routines:0,tasks:0,attachments:0};for(const o of e){const c=ke(o,a);c&&(n[c]+=1)}return n}d(St,"countExportFilesByCategory");function Ct(e){const{filePaths:r,issues:a,categories:n}=e,o=ve(a),c=jt(a),p=vt(e.embeddedAssets??[]),f=n.attachments&&ye(n),x=new Set;for(const l of r){const b=ke(l,o);if(b===null){x.add(l);continue}if(b==="attachments"){const i=l.slice(6).trim().toLowerCase(),g=p.get(i);if(g&&kt(g,n)){x.add(l);continue}if(!f)continue;const j=c.recurring.has(i),y=c.oneOff.has(i);!j&&!y?g||x.add(l):(y&&n.tasks||j&&n.routines)&&x.add(l);continue}n[b]&&x.add(l)}return x}d(Ct,"buildExportCheckedFiles");function Se(e,r){if(!r.has(e))return r.add(e),e;let a=2;for(;;){const n=`${e}-${a}`;if(!r.has(n))return r.add(n),n;a+=1}}d(Se,"uniqueSlug");function Et(e){const r=new Set,a=new Map,n=[...e].sort((o,c)=>o.name.localeCompare(c.name));for(const o of n){const c=qe(o.name)??"agent";a.set(o.id,Se(c,r))}return a}d(Et,"buildPortableAgentSlugMap");function Nt(e){const r=new Set,a=new Map,n=[...e].sort((o,c)=>o.name.localeCompare(c.name));for(const o of n){const c=De(o.name,o.name);a.set(o.id,Se(c,r))}return a}d(Nt,"buildPortableProjectSlugMap");function At(e){const r=Et(e.agents),a=Nt(e.projects),n={agents:e.orderedAgents.map(o=>r.get(o.id)).filter(o=>!!o),projects:e.orderedProjects.map(o=>a.get(o.id)).filter(o=>!!o)};return n.agents.length>0||n.projects.length>0?n:void 0}d(At,"buildPortableSidebarOrder");var t=we(Ke(),1);function Ce(e){const r=new Set,a=new Set,n=new Set;for(const o of e){const c=o.match(/^agents\/([^/]+)\//);c&&r.add(c[1]);const p=o.match(/^projects\/([^/]+)\//);p&&a.add(p[1]);const f=o.match(/^tasks\/([^/]+)\//);f&&n.add(f[1])}return{agents:r,projects:a,tasks:n,routines:new Set(n)}}d(Ce,"checkedSlugs");function Pt(e,r){const a=Ce(r),n=e.split(`
2
2
  `),o=[],c=new Set(["agents","projects","tasks","routines"]),p=new Set(["agents","projects"]);let f=null,x=null,l=!0,b=null,i=null,g=[],j=null,y=[];function T(){i!==null&&g.length>0&&(y.push(i),y.push(...g)),i=null,g=[]}d(T,"flushSidebarSection");function N(){T(),j!==null&&y.length>0&&(o.push(j),o.push(...y)),j=null,y=[]}d(N,"flushSection");for(const w of n){const U=w.match(/^([a-zA-Z_][\w-]*):\s*(.*)$/);if(U&&!w.startsWith(" ")){N(),x=null,l=!0;const E=U[0].split(":")[0];if(c.has(E)){f=E,j=w;continue}else if(E==="sidebar"){f=E,b=null,j=w;continue}else{f=null,o.push(w);continue}}if(f==="sidebar"){const E=w.match(/^ ([\w-]+):\s*$/);if(E&&!w.startsWith(" ")){T();const A=E[1];b=A&&p.has(A)?A:null,i=b?w:null;continue}const L=w.match(/^ - ["']?([^"'\n]+)["']?\s*$/);if(L&&b){const A=L[1],W=a[b];A&&W.has(A)&&g.push(w);continue}if(b){g.push(w);continue}}if(f&&c.has(f)){const E=w.match(/^ ([\w][\w-]*):\s*(.*)$/);if(E&&!w.startsWith(" ")){const L=E[1];x=L,l=a[f].has(L),l&&y.push(w);continue}if(x!==null){l&&y.push(w);continue}y.push(w);continue}o.push(w)}N();let C=o.join(`
3
3
  `);const _=C.match(/^\s{2}logoPath:\s*["']?([^"'\n]+)["']?\s*$/m);return _&&!r.has(_[1])&&(C=C.replace(/^\s{2}logoPath:\s*["']?([^"'\n]+)["']?\s*\n?/m,"")),C}d(Pt,"filterPaperclipYaml");function Ee(e,r){if(!r)return e;const a=r.toLowerCase();return e.map(n=>{if(n.kind==="file")return n.name.toLowerCase().includes(a)||n.path.toLowerCase().includes(a)?n:null;const o=Ee(n.children,r);return o.length>0?{...n,children:o}:null}).filter(n=>n!==null)}d(Ee,"filterTree");function Rt(e,r){const a=new Set,n=r.toLowerCase();function o(c,p){if(c.kind==="file"){if(c.name.toLowerCase().includes(n)||c.path.toLowerCase().includes(n))for(const f of p)a.add(f)}else for(const f of c.children)o(f,[...p,c.path])}d(o,"walk");for(const c of e)o(c,[]);return a}d(Rt,"collectMatchedParentDirs");var xe=10;function Tt(e,r,a,n){let o=0,c=0;return{nodes:e.map(p=>{if(p.kind==="dir"&&p.name==="tasks"){o=p.children.length;const f=[],x=[],l=a.toLowerCase();for(const g of p.children){const j=ft([g],"file"),y=n!==null&&j.has(n),T=a&&(g.name.toLowerCase().includes(l)||g.path.toLowerCase().includes(l)||[...j].some(N=>N.toLowerCase().includes(l)));y||T?f.push(g):x.push(g)}const b=Math.max(0,r-f.length),i=[...f,...x.slice(0,b)];return c=i.length,{...p,children:i}}return p}),totalTaskChildren:o,visibleTaskChildren:c}}d(Tt,"paginateTaskNodes");function Ne(e,r,a){const n={};for(const o of Object.keys(e))r.has(o)&&(n[o]=a[o]??e[o]);return n}d(Ne,"filterExportForDownload");function Lt(e,r,a){const n=Ne(e.files,r,a),o=dt(n,e.rootPath),c=new ArrayBuffer(o.byteLength);new Uint8Array(c).set(o);const p=new Blob([c],{type:"application/zip"}),f=URL.createObjectURL(p),x=document.createElement("a");x.href=f,x.download=`${e.rootPath}.zip`,document.body.appendChild(x),x.click(),x.remove(),window.setTimeout(()=>URL.revokeObjectURL(f),1e3)}d(Lt,"downloadZip");function Ot({data:e,onSkillClick:r}){return(0,t.jsx)("div",{className:"rounded-md border border-border bg-accent/20 px-4 py-3 mb-4",children:(0,t.jsx)("dl",{className:"grid grid-cols-(--gtc-5) gap-x-4 gap-y-1.5 text-sm",children:Object.entries(e).map(([a,n])=>(0,t.jsxs)("div",{className:"contents",children:[(0,t.jsx)("dt",{className:"text-muted-foreground whitespace-nowrap py-0.5",children:ht[a]??a}),(0,t.jsx)("dd",{className:"py-0.5",children:Array.isArray(n)?(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:n.map(o=>(0,t.jsx)("button",{type:"button",className:ne("inline-flex items-center rounded-md border border-border bg-background px-2 py-0.5 text-xs",a==="skills"&&r&&"cursor-pointer hover:bg-accent/50 hover:border-foreground/30 transition-colors"),onClick:d(()=>a==="skills"&&r?.(o),"onClick"),children:o},o))}):(0,t.jsx)("span",{children:n})})]},a))})})}d(Ot,"FrontmatterCard");var Mt={ceo:"CEO",cto:"CTO",cmo:"CMO",cfo:"CFO",coo:"COO",vp:"VP",manager:"Manager",engineer:"Engineer",agent:"Agent"};function Ft(e,r,a,n){const o=Ce(r),c=e.agents.filter(i=>o.agents.has(i.slug)),p=e.projects.filter(i=>o.projects.has(i.slug)),f=e.issues.filter(i=>o.tasks.has(i.slug)),x=e.skills.filter(i=>[...r].some(g=>g.startsWith(`skills/${i.key}/`)||g.startsWith("skills/")&&g.includes(`/${i.slug}/`))),l=[];l.push(`# ${a}`),l.push(""),n&&(l.push(`> ${n}`),l.push("")),c.length>0&&(l.push("![Org Chart](images/org-chart.png)"),l.push("")),l.push("## What's Inside"),l.push(""),l.push("This is an [Agent Company](https://paperclip.ing) package."),l.push("");const b=[];if(c.length>0&&b.push(["Agents",c.length]),p.length>0&&b.push(["Projects",p.length]),x.length>0&&b.push(["Skills",x.length]),f.length>0&&b.push(["Tasks",f.length]),b.length>0){l.push("| Content | Count |"),l.push("|---------|-------|");for(const[i,g]of b)l.push(`| ${i} | ${g} |`);l.push("")}if(c.length>0){l.push("### Agents"),l.push(""),l.push("| Agent | Role | Reports To |"),l.push("|-------|------|------------|");for(const i of c){const g=Mt[i.role]??i.role,j=i.reportsToSlug??"—";l.push(`| ${i.name} | ${g} | ${j} |`)}l.push("")}if(p.length>0){l.push("### Projects"),l.push("");for(const i of p){const g=i.description?` — ${i.description}`:"";l.push(`- **${i.name}**${g}`)}l.push("")}return l.push("## Getting Started"),l.push(""),l.push("```bash"),l.push("npx @tickernelz/paperclip-pro company import this-github-url-or-folder"),l.push("```"),l.push(""),l.push("See [Paperclip](https://paperclip.ing) for more information."),l.push(""),l.push("---"),l.push(`Exported from [Paperclip](https://paperclip.ing) on ${new Date().toISOString().split("T")[0]}`),l.push(""),l.join(`
4
4
  `)}d(Ft,"generateReadmeFromSelection");function It(e){const{src:r,selectedFile:a,allFiles:n,orgChartPreviewUrl:o}=e;if(/^(?:https?:|data:)/i.test(r))return null;if(r.replace(/^\.\//,"")==="images/org-chart.png"&&o)return o;const c=(a.includes("/")?a.slice(0,a.lastIndexOf("/")+1):"")+r,p=n[c]??n[r];return p?je(c in n?c:r,p):null}d(It,"resolveExportPreviewImageSrc");function $t({selectedFile:e,content:r,allFiles:a,orgChartPreviewUrl:n,onSkillClick:o}){if(!e||r===null)return(0,t.jsx)(D,{icon:B,message:"Select a file to preview its contents."});const c=pt(r),p=e.endsWith(".md")&&c!==null,f=p&&c?lt(c):null,x=mt(e,r)?je(e,r):null,l=p?b=>It({src:b,selectedFile:e,allFiles:a,orgChartPreviewUrl:n}):void 0;return(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"border-b border-border px-5 py-3",children:(0,t.jsx)("div",{className:"truncate font-mono text-sm",children:e})}),(0,t.jsx)("div",{className:"min-h-(--sz-560px) px-5 py-5",children:f?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ot,{data:f.data,onSkillClick:o}),f.body.trim()&&(0,t.jsx)(fe,{resolveImageSrc:l,softBreaks:!1,linkIssueReferences:!1,children:f.body})]}):p?(0,t.jsx)(fe,{resolveImageSrc:l,softBreaks:!1,linkIssueReferences:!1,children:c??""}):x?(0,t.jsx)("div",{className:"flex min-h-(--sz-520px) items-center justify-center rounded-lg border border-border bg-accent/10 p-6",children:(0,t.jsx)("img",{src:x,alt:e,className:"max-h-(--sz-480px) max-w-full object-contain"})}):c!==null?(0,t.jsx)("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground",children:(0,t.jsx)("code",{children:c})}):(0,t.jsx)("div",{className:"rounded-lg border border-border bg-accent/10 px-4 py-3 text-sm text-muted-foreground",children:"Binary asset preview is not available for this file type."})})]})}d($t,"ExportPreviewPane");function ge(e){const r="/company/export/files/",a=Ve(e),n=a.indexOf(r);return n===-1?null:decodeURIComponent(a.slice(n+22))||null}d(ge,"filePathFromLocation");function be(e){const r=e.split("/").slice(0,-1),a=[];let n="";for(const o of r)n=n?`${n}/${o}`:o,a.push(n);return a}d(be,"expandAncestors");function zt(e){return(e instanceof DOMException||e instanceof Error)&&e.name==="AbortError"}d(zt,"isAbortError");function se(e){return e instanceof Error?e.message:"Failed to load export data."}d(se,"previewErrorMessage");function Jt(){const{selectedCompanyId:e,selectedCompany:r}=We(),{setBreadcrumbs:a}=Xe(),{pushToast:n}=et(),o=Ze(),c=Ye(),p=(0,h.useRef)(ge(c.pathname)),{data:f}=X({queryKey:G.auth.session,queryFn:d(()=>_e.getSession(),"queryFn")}),{data:x=[]}=X({queryKey:G.agents.list(e),queryFn:d(()=>He.list(e),"queryFn"),enabled:!!e}),{data:l=[]}=X({queryKey:G.projects.list(e),queryFn:d(()=>Qe.list(e),"queryFn"),enabled:!!e}),{data:b}=X({queryKey:G.companies.exportFidelity(e),queryFn:d(()=>te.exportFidelity(e),"queryFn"),enabled:!!e}),[i,g]=(0,h.useState)(null),[j,y]=(0,h.useState)(null),[T,N]=(0,h.useState)(new Set),[C,_]=(0,h.useState)(()=>({...bt(),tasks:!1,routines:!1,attachments:!1})),[w,U]=(0,h.useState)(""),[E,L]=(0,h.useState)(xe),[A,W]=(0,h.useState)(!1),q=(0,h.useRef)(null),I=(0,h.useRef)(null),M=(0,h.useRef)(0),re=(0,h.useRef)(null),oe=f?.user?.id??f?.session?.userId??null,V=(0,h.useMemo)(()=>x.filter(s=>s.status!=="terminated"),[x]),J=(0,h.useMemo)(()=>l,[l]),{orderedAgents:ae}=nt({agents:V,companyId:e,userId:oe}),{orderedProjects:ie}=ot({projects:J,companyId:e,userId:oe}),ce=(0,h.useMemo)(()=>At({agents:V,orderedAgents:ae,projects:J,orderedProjects:ie}),[ae,ie,V,J]),Q=C.tasks||C.routines,ee=(0,h.useCallback)((s,u=!1)=>{y(s),s?o(`/company/export/files/${encodeURI(s)}`,{replace:u}):o("/company/export",{replace:u})},[o]);(0,h.useEffect)(()=>{if(!i)return;const s=ge(c.pathname);s&&s in i.files&&s!==j?(y(s),N(u=>{const m=new Set(u);for(const v of be(s))m.add(v);return m})):!s&&j&&y(null)},[c.pathname,i]),(0,h.useEffect)(()=>{a([{label:r?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Export"}])},[r?.name,a]);const P=pe({mutationFn:d(({includeIssues:s,includeSkills:u,signal:m})=>te.exportPreview(e,{include:{company:!0,agents:!0,projects:!0,issues:s,skills:u},sidebarOrder:ce},{signal:m}),"mutationFn"),onSuccess:d((s,u)=>{if(u.requestId!==M.current)return;g(s);const m=he(s.files),v=new Set;for(const k of m)k.kind==="dir"&&k.name!=="tasks"&&v.add(k.path);const S=p.current;if(S&&S in s.files){y(S);const k=be(S);N(new Set([...v,...k]))}else{const k="README.md"in s.files?"README.md":Object.keys(s.files)[0];k&&ee(k,!0),N(v)}},"onSuccess"),onError:d((s,u)=>{u.requestId!==M.current||zt(s)||n({tone:"error",title:"Export failed",body:se(s)})},"onError")});function F(){if(!e)return;I.current?.abort();const s=new AbortController,u=M.current+1;M.current=u,I.current=s,W(!1),P.mutate({includeIssues:Q,includeSkills:C.skills,requestId:u,signal:s.signal})}d(F,"startPreviewRequest");const K=pe({mutationFn:d(()=>te.exportBundle(e,{include:{company:!0,agents:!0,projects:!0,issues:Q,skills:C.skills},selectedFiles:Array.from(R).sort(),sidebarOrder:ce}),"mutationFn"),onSuccess:d(s=>{const u=new Set(Object.keys(s.files));Lt(s,u,s.files),n({tone:"success",title:"Export downloaded",body:`${u.size} file${u.size===1?"":"s"} exported as ${s.rootPath}.zip`})},"onSuccess"),onError:d(s=>{n({tone:"error",title:"Export failed",body:s instanceof Error?s.message:"Failed to build export package."})},"onError")});(0,h.useEffect)(()=>{e&&(re.current!==e&&(re.current=e,g(null),y(null)),F())},[e,Q,C.skills]),(0,h.useEffect)(()=>()=>{M.current+=1,I.current?.abort()},[]);const O=(0,h.useMemo)(()=>i?he(i.files):[],[i]),R=(0,h.useMemo)(()=>i?Ct({filePaths:Object.keys(i.files),issues:i.manifest.issues,categories:C,embeddedAssets:i.manifest.embeddedAssets??[]}):new Set,[i,C]),Ae=(0,h.useMemo)(()=>i?St(Object.keys(i.files),i.manifest.issues):null,[i]),{displayTree:Pe,totalTaskChildren:le,visibleTaskChildren:de}=(0,h.useMemo)(()=>{let s=O;w&&(s=Ee(s,w));const u=Tt(s,E,w,j);return{displayTree:u.nodes,totalTaskChildren:u.totalTaskChildren,visibleTaskChildren:u.visibleTaskChildren}},[O,w,E,j]),Re=(0,h.useMemo)(()=>{const s={};function u(m){if(m.kind==="file"){const S=R.has(m.path);return S||(s[m.path]="muted"),S}let v=!1;for(const S of m.children)u(S)&&(v=!0);return v||(s[m.path]="muted"),v}d(u,"walk");for(const m of O)u(m);return s},[O,R]),Y=(0,h.useMemo)(()=>{if(!i)return{};const s={...i.files},u=i.paperclipExtensionPath;if(u&&typeof i.files[u]=="string"&&(s[u]=Pt(i.files[u],R)),typeof i.files["README.md"]=="string"){const m=i.manifest.company?.name??r?.name??"Company",v=i.manifest.company?.description??null;s["README.md"]=Ft(i.manifest,R,m,v)}return s},[i,R,r?.name]),Te=(0,h.useMemo)(()=>i?at(Ne(i.files,R,Y),i.rootPath):0,[i,R,Y]),ue=(0,h.useMemo)(()=>ut(O),[O]),$=R.size,z=(0,h.useMemo)(()=>i?i.warnings.filter(s=>!/terminated agent/i.test(s)):[],[i]);function Le(s){N(u=>{const m=new Set(u);return m.has(s)?m.delete(s):m.add(s),m})}d(Le,"handleToggleDir");function Oe(s){_(u=>({...u,[s]:!u[s]}))}d(Oe,"handleToggleCategory");function Me(s){const u=w.length>0,m=s.length>0;if(m&&!u&&(q.current=new Set(T)),U(s),m){const v=Rt(O,s);N(S=>{const k=new Set(S);for(const Z of v)k.add(Z);return k})}else u&&q.current&&(N(q.current),q.current=null)}d(Me,"handleSearchChange");function Fe(s){if(!i)return;const u=i.manifest.skills.find(m=>m.key===s||m.slug===s)?.path??`skills/${s}/SKILL.md`;u in i.files&&(ee(u),N(m=>{const v=new Set(m);v.add("skills");const S=u.split("/").slice(0,-1);let k="";for(const Z of S)k=k?`${k}/${Z}`:Z,v.add(k);return v}))}d(Fe,"handleSkillClick");function Ie(){!i||R.size===0||K.isPending||K.mutate()}d(Ie,"handleDownload");function $e(){M.current+=1,I.current?.abort(),I.current=null,P.reset(),W(!0)}if(d($e,"handleCancelPreview"),!e)return(0,t.jsx)(D,{icon:B,message:"Select an organization to export."});if(P.isPending&&!i)return(0,t.jsx)(st,{variant:"detail"});if(A&&!i)return(0,t.jsx)(D,{icon:B,title:"Export preview cancelled",message:"The preview request was cancelled. Your export settings are unchanged.",action:"Retry preview",onAction:F,hideActionIcon:!0});if(P.isError&&!i)return(0,t.jsx)(D,{icon:B,title:"Export preview failed",message:se(P.error),description:"Retry the preview. You do not need to reload this page.",action:"Retry preview",onAction:F,hideActionIcon:!0});if(!i)return(0,t.jsx)(D,{icon:B,title:"Export preview unavailable",message:"No export preview is loaded.",action:"Load preview",onAction:F,hideActionIcon:!0});const ze=j?Y[j]??null:null;return(0,t.jsxs)("div",{className:"max-w-6xl",children:[(0,t.jsx)("div",{className:"sticky top-0 z-10 border-b border-border bg-background px-5 py-3",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[(0,t.jsxs)("span",{className:"font-medium",children:[r?.name??"Organization"," export"]}),(0,t.jsxs)("span",{className:"text-muted-foreground",children:["Exporting ",$.toLocaleString()," of ",ue.toLocaleString()," file",ue===1?"":"s",$>0&&` (~${rt(Te)})`]}),z.length>0&&(0,t.jsxs)("span",{className:"text-amber-500",children:[z.length," warning",z.length===1?"":"s"]})]}),(0,t.jsxs)(H,{size:"sm",onClick:Ie,disabled:$===0||K.isPending||P.isPending||P.isError||A,children:[(0,t.jsx)(ct,{className:"mr-1.5 h-3.5 w-3.5"}),K.isPending?"Building export...":`Export ${$.toLocaleString()} file${$===1?"":"s"}`]})]})}),z.length>0&&(0,t.jsx)("div",{className:"mx-5 mt-3 rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:z.map(s=>(0,t.jsx)("div",{className:"text-xs text-amber-500",children:s},s))}),b&&b.warnings.length>0&&(0,t.jsxs)("div",{className:"mx-5 mt-3 rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:[(0,t.jsx)("h3",{className:"mb-1.5 text-xs font-medium",children:"Not included in this export"}),b.warnings.map(s=>(0,t.jsx)("div",{className:ne("text-xs",s.severity==="blocker"?"font-medium text-destructive":"text-amber-500"),children:s.message},s.code))]}),(0,t.jsxs)("div",{className:"grid gap-4 xl:h-(--sz-calc-30) xl:grid-cols-(--gtc-25) xl:gap-0",children:[(0,t.jsxs)("aside",{className:"flex max-h-(--sz-24rem) flex-col overflow-hidden border-b border-border xl:max-h-none xl:border-b-0 xl:border-r",children:[(0,t.jsx)("div",{className:"border-b border-border px-4 py-3 shrink-0",children:(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Package files"})}),(0,t.jsxs)("div",{className:"border-b border-border px-4 py-3 shrink-0",children:[(0,t.jsx)("h3",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"What to include"}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5",role:"group","aria-label":"What to include",children:xt.map(s=>{const u=s==="attachments"&&!ye(C),m=C[s]&&!u,v=Ae?.[s]??0,S=i.manifest.includes.issues||s!=="tasks"&&s!=="routines"&&s!=="attachments";return(0,t.jsxs)("label",{className:ne("flex items-center gap-2 text-sm",u?"cursor-not-allowed opacity-50":"cursor-pointer"),title:u?"Attachments travel with tasks and routines; re-enable one of them to include attachments.":void 0,children:[(0,t.jsx)("input",{type:"checkbox",checked:m,disabled:u,onChange:d(()=>Oe(s),"onChange"),className:"accent-foreground","data-export-category":s}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:gt[s]}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:S?v.toLocaleString():"—"})]},s)})}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Task and routine history is opt-in because it can be large."})]}),(0,t.jsx)("div",{className:"border-b border-border px-3 py-2 shrink-0",children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2 py-1",children:[(0,t.jsx)(Ge,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)("input",{type:"text",value:w,onChange:d(s=>Me(s.target.value),"onChange"),placeholder:"Search files...",className:"w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground","data-page-search-target":"true"})]})}),(0,t.jsxs)("div",{className:"flex-1 overflow-y-auto",children:[(0,t.jsx)(it,{nodes:Pe,selectedFile:j,expandedDirs:T,onToggleDir:Le,onSelectFile:ee,fileTones:Re,showCheckboxes:!1,wrapLabels:!1}),le>de&&!w&&(0,t.jsx)("div",{className:"px-4 py-2",children:(0,t.jsxs)("button",{type:"button",onClick:d(()=>L(s=>s+xe),"onClick"),className:"w-full rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent/30 hover:text-foreground transition-colors",children:["Show more tasks (",de," of ",le,")"]})})]})]}),(0,t.jsxs)("div",{className:"relative min-w-0 overflow-y-auto xl:pl-6",children:[(0,t.jsx)($t,{selectedFile:j,content:ze,allFiles:Y,orgChartPreviewUrl:`/api/companies/${encodeURIComponent(e)}/org.svg`,onSkillClick:Fe}),P.isPending?(0,t.jsx)("div",{className:"absolute inset-0 z-10 flex min-h-(--sz-520px) items-center justify-center bg-background/90 px-6 text-center",role:"status","aria-live":"polite","aria-busy":"true","data-export-preview-state":"loading",children:(0,t.jsxs)("div",{className:"flex max-w-md flex-col items-center gap-3",children:[(0,t.jsx)(tt,{className:"h-6 w-6 animate-spin text-muted-foreground"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:"Updating export preview…"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Large task histories can take a minute. You can untick Tasks or cancel this update."})]}),(0,t.jsxs)(H,{type:"button",variant:"outline",size:"sm",onClick:$e,children:[(0,t.jsx)(Je,{}),"Cancel update"]})]})}):A?(0,t.jsx)("div",{className:"absolute inset-0 z-10 flex min-h-(--sz-520px) items-center justify-center bg-background/90 px-6 text-center","data-export-preview-state":"cancelled",children:(0,t.jsxs)("div",{className:"flex max-w-md flex-col items-center gap-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:"Preview update cancelled"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"The previous preview remains available. Retry when you are ready."})]}),(0,t.jsxs)(H,{type:"button",variant:"outline",size:"sm",onClick:F,children:[(0,t.jsx)(me,{}),"Retry preview"]})]})}):P.isError?(0,t.jsx)("div",{className:"absolute inset-0 z-10 flex min-h-(--sz-520px) items-center justify-center bg-background/90 px-6 text-center",role:"alert","data-export-preview-state":"error",children:(0,t.jsxs)("div",{className:"flex max-w-md flex-col items-center gap-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"text-sm font-medium text-destructive",children:"Export preview failed"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:se(P.error)})]}),(0,t.jsxs)(H,{type:"button",variant:"outline",size:"sm",onClick:F,children:[(0,t.jsx)(me,{}),"Retry preview"]})]})}):null]})]})]})}d(Jt,"CompanyExport");export{Jt as CompanyExport};
@@ -1,4 +1,4 @@
1
- var gr=Object.defineProperty;var n=(t,l)=>gr(t,"name",{value:l,configurable:!0});import{i as yn}from"./rolldown-runtime-ZpX3ckPj.js";import{G as M,Ra as fr,St as f,Va as br,aa as xe,ht as jr,ia as Y,t as ge,ut as vr,za as yr}from"./agent-avatar-url-BnmqahQ7.js";import{Bn as kr,Vn as Nr,ct as jt,f as wr,ft as Sr,i as y,it as Cr,n as Fr,r as Hs,s as pe,tt as kn,vt as Ir,xt as Ft}from"./BreadcrumbContext-Bxr1TyKN.js";import{Z as Dr}from"./mention-chips-ClRmijVb.js";import{d as qe,m as Nn,p as $e,u as ze}from"./alert-dialog-BxpRolrb.js";import{t as rn}from"./AgentAvatar-DZh8tNnK.js";import{D as Lr,E as Ws,O as Br,T as Pr,_ as xt,a as bs,c as js,f as Bs,h as Ze,m as Ps,n as vt,o as As,r as vs,s as yt,t as Er,u as ys,v as Ls,w as Es,y as Tr}from"./checkbox-5wFlZdZn.js";import{c as _,f as Ar,t as Kr}from"./MarkdownEditor-D7suACD6.js";import{i as Ts,r as wn,t as Sn}from"./tabs-BfOtoFWj.js";import{p as It}from"./StatusIcon-YdJnE47W.js";import{l as Cn,o as Mr,r as Fn,s as Rr,t as qr}from"./use-adapter-capabilities-JhD0-FlQ.js";import{t as In}from"./check-BiXfODpl.js";import{a as $r,s as gs}from"./ToastContext-Dh8dPdr5.js";import{a as Dn,i as Dt,s as Ln}from"./clipboard-CTmezHYG.js";import{r as ht,t as zr}from"./use-copy-action-qHyHFl14.js";import{n as _r,t as fs}from"./external-link-LnxJtUIq.js";import{E as Ur,t as kt}from"./MarkdownBody-B5ygzgk6.js";import{t as Lt}from"./file-text-Ba5Wddur.js";import{d as Vr,u as Bn}from"./sheet-CACWxbsc.js";import{t as le}from"./badge-D5aOL1Ll.js";import{t as Re}from"./input-CtLHwxEw.js";import{t as es}from"./EmptyState-DliXLd04.js";import{t as Be}from"./PageSkeleton-BZF4K6Hf.js";import{$t as Or,Ct as pt,Et as Pn,G as Qr,H as Hr,J as Gr,K as Wr,Q as Yr,St as Gs,Tt as En,U as Xr,W as Zr,X as Jr,Y as ea,Z as sa,_ as ta,an as na,at as an,bt as gt,c as ra,cn as aa,d as la,et as ia,f as Ks,fn as oa,g as da,gn as ca,h as ua,hn as Nt,in as Tn,it as An,jt as ma,kt as xa,l as ha,ln as pa,lt as he,m as Kn,mn as Mn,nn as ga,nt as fa,o as ba,ot as Je,p as ft,pn as ks,rt as ja,s as va,sn as wt,tt as ya,u as ka,v as Na,vn as St,vt as Bt,wt as wa,xt as Sa,y as Ca,yn as ln,yt as Fa}from"./index-D6WtpzBM.js";var c=yn(br(),1),e=yn(yr(),1),on=16,dn=24,cn="min-h-9";function un(t){return(0,e.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...t,children:(0,e.jsx)("path",{d:"M12 4 21 19H3z"})})}n(un,"VercelMark");function Rn(t){const l=t.replace(/\r\n/g,`
1
+ var gr=Object.defineProperty;var n=(t,l)=>gr(t,"name",{value:l,configurable:!0});import{i as yn}from"./rolldown-runtime-ZpX3ckPj.js";import{G as M,Ra as fr,St as f,Va as br,aa as xe,ht as jr,ia as Y,t as ge,ut as vr,za as yr}from"./agent-avatar-url-BnmqahQ7.js";import{Bn as kr,Vn as Nr,ct as jt,f as wr,ft as Sr,i as y,it as Cr,n as Fr,r as Hs,s as pe,tt as kn,vt as Ir,xt as Ft}from"./BreadcrumbContext-Bxr1TyKN.js";import{Z as Dr}from"./mention-chips-ClRmijVb.js";import{d as qe,m as Nn,p as $e,u as ze}from"./alert-dialog-BxpRolrb.js";import{t as rn}from"./AgentAvatar-DZh8tNnK.js";import{D as Lr,E as Ws,O as Br,T as Pr,_ as xt,a as bs,c as js,f as Bs,h as Ze,m as Ps,n as vt,o as As,r as vs,s as yt,t as Er,u as ys,v as Ls,w as Es,y as Tr}from"./checkbox-5wFlZdZn.js";import{c as _,f as Ar,t as Kr}from"./MarkdownEditor-D7suACD6.js";import{i as Ts,r as wn,t as Sn}from"./tabs-BfOtoFWj.js";import{p as It}from"./StatusIcon-YdJnE47W.js";import{l as Cn,o as Mr,r as Fn,s as Rr,t as qr}from"./use-adapter-capabilities-JhD0-FlQ.js";import{t as In}from"./check-BiXfODpl.js";import{a as $r,s as gs}from"./ToastContext-Dh8dPdr5.js";import{a as Dn,i as Dt,s as Ln}from"./clipboard-CTmezHYG.js";import{r as ht,t as zr}from"./use-copy-action-qHyHFl14.js";import{n as _r,t as fs}from"./external-link-LnxJtUIq.js";import{E as Ur,t as kt}from"./MarkdownBody-B5ygzgk6.js";import{t as Lt}from"./file-text-Ba5Wddur.js";import{d as Vr,u as Bn}from"./sheet-CACWxbsc.js";import{t as le}from"./badge-D5aOL1Ll.js";import{t as Re}from"./input-CtLHwxEw.js";import{t as es}from"./EmptyState-DliXLd04.js";import{t as Be}from"./PageSkeleton-BZF4K6Hf.js";import{$t as Or,Ct as pt,Et as Pn,G as Qr,H as Hr,J as Gr,K as Wr,Q as Yr,St as Gs,Tt as En,U as Xr,W as Zr,X as Jr,Y as ea,Z as sa,_ as ta,an as na,at as an,bt as gt,c as ra,cn as aa,d as la,et as ia,f as Ks,fn as oa,g as da,gn as ca,h as ua,hn as Nt,in as Tn,it as An,jt as ma,kt as xa,l as ha,ln as pa,lt as he,m as Kn,mn as Mn,nn as ga,nt as fa,o as ba,ot as Je,p as ft,pn as ks,rt as ja,s as va,sn as wt,tt as ya,u as ka,v as Na,vn as St,vt as Bt,wt as wa,xt as Sa,y as Ca,yn as ln,yt as Fa}from"./index-DvHeLBFO.js";var c=yn(br(),1),e=yn(yr(),1),on=16,dn=24,cn="min-h-9";function un(t){return(0,e.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...t,children:(0,e.jsx)("path",{d:"M12 4 21 19H3z"})})}n(un,"VercelMark");function Rn(t){const l=t.replace(/\r\n/g,`
2
2
  `);if(!l.startsWith(`---
3
3
  `))return l.trim();const a=l.indexOf(`
4
4
  ---
@@ -1 +1 @@
1
- var pt=Object.defineProperty;var u=(e,a)=>pt(e,"name",{value:a,configurable:!0});import{i as ot}from"./rolldown-runtime-ZpX3ckPj.js";import{B as yt,St as K,Va as bt,_i as vt,aa as V,ht as wt,za as Ct}from"./agent-avatar-url-BnmqahQ7.js";import{ct as jt,f as Mt,i as Q,n as Nt,r as J,s as tt}from"./BreadcrumbContext-Bxr1TyKN.js";import{t as kt}from"./AgentAvatar-DZh8tNnK.js";import{n as Pt,t as Dt}from"./useHiddenSettings-Dz7GWNDr.js";import{t as Zt}from"./card-PCL2aF_L.js";import{t as et}from"./EmptyState-DliXLd04.js";import{t as Tt}from"./PageSkeleton-BZF4K6Hf.js";import{Ht as Yt,Rt as _t,dn as zt,en as Et,hn as Xt,un as rt}from"./index-D6WtpzBM.js";var o=ot(bt(),1),n=ot(Ct(),1),N=200,S=100,E=32,$t=80,W=60,St=.2,Wt=2,L=6;function T(e){if(e.reports.length===0)return N;const a=e.reports.reduce((i,x)=>i+T(x),0),d=(e.reports.length-1)*E;return Math.max(N,a+d)}u(T,"subtreeWidth");function at(e,a,d){const i=T(e),x=[];if(e.reports.length>0){const C=e.reports.reduce((k,P)=>k+T(P),0),H=(e.reports.length-1)*E;let j=a+(i-C-H)/2;for(const k of e.reports){const P=T(k);x.push(at(k,j,d+S+$t)),j+=P+E}}return{id:e.id,name:e.name,role:e.role,status:e.status,x:a+(i-N)/2,y:d,children:x}}u(at,"layoutTree");function Ht(e){if(e.length===0)return[];e.reduce((x,C)=>x+T(C),0),(e.length-1)*E;let a=W;const d=W,i=[];for(const x of e){const C=T(x);i.push(at(x,a,d)),a+=C+E}return i}u(Ht,"layoutForest");function Rt(e){const a=[];function d(i){a.push(i),i.children.forEach(d)}return u(d,"walk"),e.forEach(d),a}u(Rt,"flattenLayout");function Lt(e){const a=[];function d(i){for(const x of i.children)a.push({parent:i,child:x}),d(x)}return u(d,"walk"),e.forEach(d),a}u(Lt,"collectEdges");function A(e){return Math.min(Math.max(e,St),Wt)}u(A,"clampZoom");function At(e){return{x:e.clientX,y:e.clientY}}u(At,"touchPoint");function nt(e,a){const d=e.clientX-a.clientX,i=e.clientY-a.clientY;return Math.hypot(d,i)}u(nt,"touchDistance");function st(e,a,d){const i=d.getBoundingClientRect();return{x:(e.clientX+a.clientX)/2-i.left,y:(e.clientY+a.clientY)/2-i.top}}u(st,"touchCenter");var Ot={running:"var(--hex-22d3ee)",active:"var(--hex-4ade80)",paused:"var(--hex-facc15)",idle:"var(--hex-facc15)",error:"var(--hex-f87171)",terminated:"var(--hex-a3a3a3)"},Bt="var(--hex-a3a3a3)";function ne(){const{selectedCompanyId:e}=wt(),{setBreadcrumbs:a}=Nt(),d=Mt(),i=!!Yt(),{hidden:x}=Dt(),C=!i&&!x.has("company.import"),H=!x.has("company.export"),{data:j,isLoading:k}=V({queryKey:K.org(e),queryFn:u(()=>J.org(e),"queryFn"),enabled:!!e}),{data:P}=V({queryKey:K.agents.list(e),queryFn:u(()=>J.list(e),"queryFn"),enabled:!!e}),ct=(0,o.useMemo)(()=>{const t=new Map;for(const r of P??[])t.set(r.id,r);return t},[P]);(0,o.useEffect)(()=>{a([{label:"Org Chart"}])},[a]);const X=(0,o.useMemo)(()=>Ht(j??[]),[j]),D=(0,o.useMemo)(()=>Rt(X),[X]),it=(0,o.useMemo)(()=>Lt(X),[X]),v=(0,o.useMemo)(()=>{if(D.length===0)return{width:800,height:600};let t=0,r=0;for(const s of D)t=Math.max(t,s.x+N),r=Math.max(r,s.y+S);return{width:t+W,height:r+W}},[D]),p=(0,o.useRef)(null),[l,M]=(0,o.useState)({x:0,y:0}),[h,Y]=(0,o.useState)(1),[R,O]=(0,o.useState)(!1),_=(0,o.useRef)({x:0,y:0,panX:0,panY:0}),m=(0,o.useRef)({mode:null,startPoint:{x:0,y:0},startPan:{x:0,y:0},startZoom:1,startDistance:0,startCenter:{x:0,y:0},moved:!1}),$=(0,o.useRef)(!1),Z=(0,o.useRef)(null);(0,o.useEffect)(()=>()=>{Z.current!==null&&window.clearTimeout(Z.current)},[]);const B=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(B.current||D.length===0||!p.current)return;B.current=!0;const t=p.current,r=t.clientWidth,s=t.clientHeight,c=(r-40)/v.width,f=(s-40)/v.height,g=Math.min(c,f,1),y=v.width*g,w=v.height*g;Y(g),M({x:(r-y)/2,y:(s-w)/2})},[D,v]);const lt=(0,o.useCallback)(t=>{t.button===0&&(t.target.closest("[data-org-card]")||(O(!0),_.current={x:t.clientX,y:t.clientY,panX:l.x,panY:l.y}))},[l]),ut=(0,o.useCallback)(t=>{if(!R)return;const r=t.clientX-_.current.x,s=t.clientY-_.current.y;M({x:_.current.panX+r,y:_.current.panY+s})},[R]),q=(0,o.useCallback)(()=>{O(!1)},[]),dt=(0,o.useCallback)(t=>{t.preventDefault();const r=p.current;if(!r)return;const s=r.getBoundingClientRect(),c=t.clientX-s.left,f=t.clientY-s.top,g=t.deltaY<0?1.1:.9,y=A(h*g),w=y/h;M({x:c-w*(c-l.x),y:f-w*(f-l.y)}),Y(y)},[h,l]),I=(0,o.useCallback)((t,r)=>{const s=A(t),c=s/h;M({x:r.x-c*(r.x-l.x),y:r.y-c*(r.y-l.y)}),Y(s)},[h,l]),ht=(0,o.useCallback)(()=>{if(!p.current)return;const t=p.current.clientWidth,r=p.current.clientHeight,s=(t-40)/v.width,c=(r-40)/v.height,f=Math.min(s,c,1),g=v.width*f,y=v.height*f;Y(f),M({x:(t-g)/2,y:(r-y)/2})},[v]),mt=(0,o.useCallback)(t=>{if(t.touches.length>=2&&p.current){const[s,c]=[t.touches[0],t.touches[1]];m.current={mode:"pinch",startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:nt(s,c),startCenter:st(s,c,p.current),moved:!1};return}const r=t.touches[0];r&&(m.current={mode:"pan",startPoint:At(r),startPan:l,startZoom:h,startDistance:0,startCenter:{x:0,y:0},moved:!1})},[l,h]),xt=(0,o.useCallback)(t=>{const r=p.current;if(!r||!m.current.mode)return;if(t.touches.length>=2){const[g,y]=[t.touches[0],t.touches[1]],w=nt(g,y),z=st(g,y,r);if(m.current.mode!=="pinch"||m.current.startDistance===0){m.current={mode:"pinch",startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:w,startCenter:z,moved:!1};return}const b=m.current,G=A(b.startZoom*(w/b.startDistance)),U=G/b.startZoom,ft=z.x-b.startCenter.x,gt=z.y-b.startCenter.y;b.moved=b.moved||Math.abs(w-b.startDistance)>L||Math.hypot(ft,gt)>L,Y(G),M({x:z.x-U*(b.startCenter.x-b.startPan.x),y:z.y-U*(b.startCenter.y-b.startPan.y)});return}const s=t.touches[0];if(!s||m.current.mode!=="pan")return;const c=s.clientX-m.current.startPoint.x,f=s.clientY-m.current.startPoint.y;m.current.moved=m.current.moved||Math.hypot(c,f)>L,M({x:m.current.startPan.x+c,y:m.current.startPan.y+f})},[l,h]),F=(0,o.useCallback)(()=>{m.current.moved&&($.current=!0,Z.current!==null&&window.clearTimeout(Z.current),Z.current=window.setTimeout(()=>{$.current=!1,Z.current=null},400)),m.current={mode:null,startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:0,startCenter:{x:0,y:0},moved:!1}},[l,h]);return e?k?(0,n.jsx)(Tt,{variant:"org-chart"}):j&&j.length===0?(0,n.jsx)(et,{icon:rt,message:"No organizational hierarchy defined."}):(0,n.jsxs)("div",{className:"flex h-(--sz-calc-38) min-h-(--sz-420px) flex-col md:h-full md:min-h-0",children:[(0,n.jsxs)("div",{className:"mb-2 flex shrink-0 flex-wrap items-center justify-start gap-2",children:[C&&(0,n.jsx)(tt,{to:"/company/import",children:(0,n.jsxs)(Q,{variant:"outline",size:"sm",children:[(0,n.jsx)(Et,{className:"mr-1.5 h-3.5 w-3.5"}),"Import company"]})}),H&&(0,n.jsx)(tt,{to:"/company/export",children:(0,n.jsxs)(Q,{variant:"outline",size:"sm",children:[(0,n.jsx)(Xt,{className:"mr-1.5 h-3.5 w-3.5"}),"Export company"]})})]}),(0,n.jsxs)("div",{ref:p,"data-testid":"org-chart-viewport",className:"w-full flex-1 min-h-0 overflow-hidden relative bg-muted/20 border border-border rounded-lg",style:{cursor:R?"grabbing":"grab",touchAction:"none",overscrollBehavior:"contain"},onMouseDown:lt,onMouseMove:ut,onMouseUp:q,onMouseLeave:q,onWheel:dt,onTouchStart:mt,onTouchMove:xt,onTouchEnd:F,onTouchCancel:F,children:[(0,n.jsxs)("div",{className:"absolute top-3 right-3 z-10 flex flex-col gap-1.5",children:[(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7",onClick:u(()=>{const t=p.current;t&&I(h*1.2,{x:t.clientWidth/2,y:t.clientHeight/2})},"onClick"),title:"Zoom in","aria-label":"Zoom in",children:(0,n.jsx)(jt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})}),(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7",onClick:u(()=>{const t=p.current;t&&I(h*.8,{x:t.clientWidth/2,y:t.clientHeight/2})},"onClick"),title:"Zoom out","aria-label":"Zoom out",children:(0,n.jsx)(Pt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})}),(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-(length:--text-nano) transition-colors hover:bg-accent sm:size-7",onClick:ht,title:"Fit to screen","aria-label":"Fit chart to screen",children:(0,n.jsx)(zt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})})]}),(0,n.jsx)("svg",{className:"absolute inset-0 pointer-events-none",style:{width:"100%",height:"100%"},children:(0,n.jsx)("g",{transform:`translate(${l.x}, ${l.y}) scale(${h})`,children:it.map(({parent:t,child:r})=>{const s=t.x+N/2,c=t.y+S,f=r.x+N/2,g=r.y,y=(c+g)/2;return(0,n.jsx)("path",{d:`M ${s} ${c} L ${s} ${y} L ${f} ${y} L ${f} ${g}`,fill:"none",stroke:"var(--border)",strokeWidth:1.5},`${t.id}-${r.id}`)})})}),(0,n.jsx)("div",{"data-testid":"org-chart-card-layer",className:"absolute inset-0",style:{transform:`translate(${l.x}px, ${l.y}px) scale(${h})`,transformOrigin:"0 0"},children:D.map(t=>{const r=ct.get(t.id),s=Ot[t.status]??Bt;return(0,n.jsx)(Zt,{"data-org-card":!0,className:"block absolute py-0 hover:shadow-md hover:border-foreground/20 transition-(--tp-box-shadow-border-color) duration-150 cursor-pointer select-none",style:{left:t.x,top:t.y,width:N,minHeight:S},onClick:u(()=>d(r?yt(r):`/agents/${t.id}`),"onClick"),onClickCapture:u(c=>{$.current&&($.current=!1,c.preventDefault(),c.stopPropagation())},"onClickCapture"),children:(0,n.jsxs)("div",{className:"flex items-center px-4 py-3 gap-3",children:[(0,n.jsxs)("div",{className:"relative shrink-0",children:[(0,n.jsx)("div",{className:"w-9 h-9 rounded-full bg-muted flex items-center justify-center",children:(0,n.jsx)(kt,{agent:r,size:16,className:"h-4.5 w-4.5 text-foreground/70"})}),(0,n.jsx)("span",{className:"absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-card",style:{backgroundColor:s}})]}),(0,n.jsxs)("div",{className:"flex flex-col items-start min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-foreground leading-tight",children:t.name}),(0,n.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground leading-tight mt-0.5",children:r?.title??It(t.role)}),r&&(0,n.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground/60 font-mono leading-tight mt-1",children:_t(r.adapterType)}),r&&r.capabilities&&(0,n.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground/80 leading-tight mt-1 line-clamp-2",children:r.capabilities})]})]})},t.id)})})]})]}):(0,n.jsx)(et,{icon:rt,message:"Select a company to view the org chart."})}u(ne,"OrgChart");var qt=vt;function It(e){return qt[e]??e}u(It,"roleLabel");export{ne as OrgChart};
1
+ var pt=Object.defineProperty;var u=(e,a)=>pt(e,"name",{value:a,configurable:!0});import{i as ot}from"./rolldown-runtime-ZpX3ckPj.js";import{B as yt,St as K,Va as bt,_i as vt,aa as V,ht as wt,za as Ct}from"./agent-avatar-url-BnmqahQ7.js";import{ct as jt,f as Mt,i as Q,n as Nt,r as J,s as tt}from"./BreadcrumbContext-Bxr1TyKN.js";import{t as kt}from"./AgentAvatar-DZh8tNnK.js";import{n as Pt,t as Dt}from"./useHiddenSettings-Dz7GWNDr.js";import{t as Zt}from"./card-PCL2aF_L.js";import{t as et}from"./EmptyState-DliXLd04.js";import{t as Tt}from"./PageSkeleton-BZF4K6Hf.js";import{Ht as Yt,Rt as _t,dn as zt,en as Et,hn as Xt,un as rt}from"./index-DvHeLBFO.js";var o=ot(bt(),1),n=ot(Ct(),1),N=200,S=100,E=32,$t=80,W=60,St=.2,Wt=2,L=6;function T(e){if(e.reports.length===0)return N;const a=e.reports.reduce((i,x)=>i+T(x),0),d=(e.reports.length-1)*E;return Math.max(N,a+d)}u(T,"subtreeWidth");function at(e,a,d){const i=T(e),x=[];if(e.reports.length>0){const C=e.reports.reduce((k,P)=>k+T(P),0),H=(e.reports.length-1)*E;let j=a+(i-C-H)/2;for(const k of e.reports){const P=T(k);x.push(at(k,j,d+S+$t)),j+=P+E}}return{id:e.id,name:e.name,role:e.role,status:e.status,x:a+(i-N)/2,y:d,children:x}}u(at,"layoutTree");function Ht(e){if(e.length===0)return[];e.reduce((x,C)=>x+T(C),0),(e.length-1)*E;let a=W;const d=W,i=[];for(const x of e){const C=T(x);i.push(at(x,a,d)),a+=C+E}return i}u(Ht,"layoutForest");function Rt(e){const a=[];function d(i){a.push(i),i.children.forEach(d)}return u(d,"walk"),e.forEach(d),a}u(Rt,"flattenLayout");function Lt(e){const a=[];function d(i){for(const x of i.children)a.push({parent:i,child:x}),d(x)}return u(d,"walk"),e.forEach(d),a}u(Lt,"collectEdges");function A(e){return Math.min(Math.max(e,St),Wt)}u(A,"clampZoom");function At(e){return{x:e.clientX,y:e.clientY}}u(At,"touchPoint");function nt(e,a){const d=e.clientX-a.clientX,i=e.clientY-a.clientY;return Math.hypot(d,i)}u(nt,"touchDistance");function st(e,a,d){const i=d.getBoundingClientRect();return{x:(e.clientX+a.clientX)/2-i.left,y:(e.clientY+a.clientY)/2-i.top}}u(st,"touchCenter");var Ot={running:"var(--hex-22d3ee)",active:"var(--hex-4ade80)",paused:"var(--hex-facc15)",idle:"var(--hex-facc15)",error:"var(--hex-f87171)",terminated:"var(--hex-a3a3a3)"},Bt="var(--hex-a3a3a3)";function ne(){const{selectedCompanyId:e}=wt(),{setBreadcrumbs:a}=Nt(),d=Mt(),i=!!Yt(),{hidden:x}=Dt(),C=!i&&!x.has("company.import"),H=!x.has("company.export"),{data:j,isLoading:k}=V({queryKey:K.org(e),queryFn:u(()=>J.org(e),"queryFn"),enabled:!!e}),{data:P}=V({queryKey:K.agents.list(e),queryFn:u(()=>J.list(e),"queryFn"),enabled:!!e}),ct=(0,o.useMemo)(()=>{const t=new Map;for(const r of P??[])t.set(r.id,r);return t},[P]);(0,o.useEffect)(()=>{a([{label:"Org Chart"}])},[a]);const X=(0,o.useMemo)(()=>Ht(j??[]),[j]),D=(0,o.useMemo)(()=>Rt(X),[X]),it=(0,o.useMemo)(()=>Lt(X),[X]),v=(0,o.useMemo)(()=>{if(D.length===0)return{width:800,height:600};let t=0,r=0;for(const s of D)t=Math.max(t,s.x+N),r=Math.max(r,s.y+S);return{width:t+W,height:r+W}},[D]),p=(0,o.useRef)(null),[l,M]=(0,o.useState)({x:0,y:0}),[h,Y]=(0,o.useState)(1),[R,O]=(0,o.useState)(!1),_=(0,o.useRef)({x:0,y:0,panX:0,panY:0}),m=(0,o.useRef)({mode:null,startPoint:{x:0,y:0},startPan:{x:0,y:0},startZoom:1,startDistance:0,startCenter:{x:0,y:0},moved:!1}),$=(0,o.useRef)(!1),Z=(0,o.useRef)(null);(0,o.useEffect)(()=>()=>{Z.current!==null&&window.clearTimeout(Z.current)},[]);const B=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(B.current||D.length===0||!p.current)return;B.current=!0;const t=p.current,r=t.clientWidth,s=t.clientHeight,c=(r-40)/v.width,f=(s-40)/v.height,g=Math.min(c,f,1),y=v.width*g,w=v.height*g;Y(g),M({x:(r-y)/2,y:(s-w)/2})},[D,v]);const lt=(0,o.useCallback)(t=>{t.button===0&&(t.target.closest("[data-org-card]")||(O(!0),_.current={x:t.clientX,y:t.clientY,panX:l.x,panY:l.y}))},[l]),ut=(0,o.useCallback)(t=>{if(!R)return;const r=t.clientX-_.current.x,s=t.clientY-_.current.y;M({x:_.current.panX+r,y:_.current.panY+s})},[R]),q=(0,o.useCallback)(()=>{O(!1)},[]),dt=(0,o.useCallback)(t=>{t.preventDefault();const r=p.current;if(!r)return;const s=r.getBoundingClientRect(),c=t.clientX-s.left,f=t.clientY-s.top,g=t.deltaY<0?1.1:.9,y=A(h*g),w=y/h;M({x:c-w*(c-l.x),y:f-w*(f-l.y)}),Y(y)},[h,l]),I=(0,o.useCallback)((t,r)=>{const s=A(t),c=s/h;M({x:r.x-c*(r.x-l.x),y:r.y-c*(r.y-l.y)}),Y(s)},[h,l]),ht=(0,o.useCallback)(()=>{if(!p.current)return;const t=p.current.clientWidth,r=p.current.clientHeight,s=(t-40)/v.width,c=(r-40)/v.height,f=Math.min(s,c,1),g=v.width*f,y=v.height*f;Y(f),M({x:(t-g)/2,y:(r-y)/2})},[v]),mt=(0,o.useCallback)(t=>{if(t.touches.length>=2&&p.current){const[s,c]=[t.touches[0],t.touches[1]];m.current={mode:"pinch",startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:nt(s,c),startCenter:st(s,c,p.current),moved:!1};return}const r=t.touches[0];r&&(m.current={mode:"pan",startPoint:At(r),startPan:l,startZoom:h,startDistance:0,startCenter:{x:0,y:0},moved:!1})},[l,h]),xt=(0,o.useCallback)(t=>{const r=p.current;if(!r||!m.current.mode)return;if(t.touches.length>=2){const[g,y]=[t.touches[0],t.touches[1]],w=nt(g,y),z=st(g,y,r);if(m.current.mode!=="pinch"||m.current.startDistance===0){m.current={mode:"pinch",startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:w,startCenter:z,moved:!1};return}const b=m.current,G=A(b.startZoom*(w/b.startDistance)),U=G/b.startZoom,ft=z.x-b.startCenter.x,gt=z.y-b.startCenter.y;b.moved=b.moved||Math.abs(w-b.startDistance)>L||Math.hypot(ft,gt)>L,Y(G),M({x:z.x-U*(b.startCenter.x-b.startPan.x),y:z.y-U*(b.startCenter.y-b.startPan.y)});return}const s=t.touches[0];if(!s||m.current.mode!=="pan")return;const c=s.clientX-m.current.startPoint.x,f=s.clientY-m.current.startPoint.y;m.current.moved=m.current.moved||Math.hypot(c,f)>L,M({x:m.current.startPan.x+c,y:m.current.startPan.y+f})},[l,h]),F=(0,o.useCallback)(()=>{m.current.moved&&($.current=!0,Z.current!==null&&window.clearTimeout(Z.current),Z.current=window.setTimeout(()=>{$.current=!1,Z.current=null},400)),m.current={mode:null,startPoint:{x:0,y:0},startPan:l,startZoom:h,startDistance:0,startCenter:{x:0,y:0},moved:!1}},[l,h]);return e?k?(0,n.jsx)(Tt,{variant:"org-chart"}):j&&j.length===0?(0,n.jsx)(et,{icon:rt,message:"No organizational hierarchy defined."}):(0,n.jsxs)("div",{className:"flex h-(--sz-calc-38) min-h-(--sz-420px) flex-col md:h-full md:min-h-0",children:[(0,n.jsxs)("div",{className:"mb-2 flex shrink-0 flex-wrap items-center justify-start gap-2",children:[C&&(0,n.jsx)(tt,{to:"/company/import",children:(0,n.jsxs)(Q,{variant:"outline",size:"sm",children:[(0,n.jsx)(Et,{className:"mr-1.5 h-3.5 w-3.5"}),"Import company"]})}),H&&(0,n.jsx)(tt,{to:"/company/export",children:(0,n.jsxs)(Q,{variant:"outline",size:"sm",children:[(0,n.jsx)(Xt,{className:"mr-1.5 h-3.5 w-3.5"}),"Export company"]})})]}),(0,n.jsxs)("div",{ref:p,"data-testid":"org-chart-viewport",className:"w-full flex-1 min-h-0 overflow-hidden relative bg-muted/20 border border-border rounded-lg",style:{cursor:R?"grabbing":"grab",touchAction:"none",overscrollBehavior:"contain"},onMouseDown:lt,onMouseMove:ut,onMouseUp:q,onMouseLeave:q,onWheel:dt,onTouchStart:mt,onTouchMove:xt,onTouchEnd:F,onTouchCancel:F,children:[(0,n.jsxs)("div",{className:"absolute top-3 right-3 z-10 flex flex-col gap-1.5",children:[(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7",onClick:u(()=>{const t=p.current;t&&I(h*1.2,{x:t.clientWidth/2,y:t.clientHeight/2})},"onClick"),title:"Zoom in","aria-label":"Zoom in",children:(0,n.jsx)(jt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})}),(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-sm transition-colors hover:bg-accent sm:size-7",onClick:u(()=>{const t=p.current;t&&I(h*.8,{x:t.clientWidth/2,y:t.clientHeight/2})},"onClick"),title:"Zoom out","aria-label":"Zoom out",children:(0,n.jsx)(Pt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})}),(0,n.jsx)("button",{className:"flex size-9 items-center justify-center rounded border border-border bg-background text-(length:--text-nano) transition-colors hover:bg-accent sm:size-7",onClick:ht,title:"Fit to screen","aria-label":"Fit chart to screen",children:(0,n.jsx)(zt,{className:"h-4 w-4 sm:h-3.5 sm:w-3.5"})})]}),(0,n.jsx)("svg",{className:"absolute inset-0 pointer-events-none",style:{width:"100%",height:"100%"},children:(0,n.jsx)("g",{transform:`translate(${l.x}, ${l.y}) scale(${h})`,children:it.map(({parent:t,child:r})=>{const s=t.x+N/2,c=t.y+S,f=r.x+N/2,g=r.y,y=(c+g)/2;return(0,n.jsx)("path",{d:`M ${s} ${c} L ${s} ${y} L ${f} ${y} L ${f} ${g}`,fill:"none",stroke:"var(--border)",strokeWidth:1.5},`${t.id}-${r.id}`)})})}),(0,n.jsx)("div",{"data-testid":"org-chart-card-layer",className:"absolute inset-0",style:{transform:`translate(${l.x}px, ${l.y}px) scale(${h})`,transformOrigin:"0 0"},children:D.map(t=>{const r=ct.get(t.id),s=Ot[t.status]??Bt;return(0,n.jsx)(Zt,{"data-org-card":!0,className:"block absolute py-0 hover:shadow-md hover:border-foreground/20 transition-(--tp-box-shadow-border-color) duration-150 cursor-pointer select-none",style:{left:t.x,top:t.y,width:N,minHeight:S},onClick:u(()=>d(r?yt(r):`/agents/${t.id}`),"onClick"),onClickCapture:u(c=>{$.current&&($.current=!1,c.preventDefault(),c.stopPropagation())},"onClickCapture"),children:(0,n.jsxs)("div",{className:"flex items-center px-4 py-3 gap-3",children:[(0,n.jsxs)("div",{className:"relative shrink-0",children:[(0,n.jsx)("div",{className:"w-9 h-9 rounded-full bg-muted flex items-center justify-center",children:(0,n.jsx)(kt,{agent:r,size:16,className:"h-4.5 w-4.5 text-foreground/70"})}),(0,n.jsx)("span",{className:"absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-card",style:{backgroundColor:s}})]}),(0,n.jsxs)("div",{className:"flex flex-col items-start min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-foreground leading-tight",children:t.name}),(0,n.jsx)("span",{className:"text-(length:--text-micro) text-muted-foreground leading-tight mt-0.5",children:r?.title??It(t.role)}),r&&(0,n.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground/60 font-mono leading-tight mt-1",children:_t(r.adapterType)}),r&&r.capabilities&&(0,n.jsx)("span",{className:"text-(length:--text-nano) text-muted-foreground/80 leading-tight mt-1 line-clamp-2",children:r.capabilities})]})]})},t.id)})})]})]}):(0,n.jsx)(et,{icon:rt,message:"Select a company to view the org chart."})}u(ne,"OrgChart");var qt=vt;function It(e){return qt[e]??e}u(It,"roleLabel");export{ne as OrgChart};
@@ -1 +1 @@
1
- var ot=Object.defineProperty;var i=(s,a)=>ot(s,"name",{value:a,configurable:!0});import{i as Le}from"./rolldown-runtime-ZpX3ckPj.js";import{G as ct,Ra as lt,St as p,Va as dt,Wi as ut,aa as L,ht as mt,ia as W,za as pt}from"./agent-avatar-url-BnmqahQ7.js";import{An as Ee,Bn as ht,X as gt,ct as xt,f as yt,i as E,l as oe,n as vt,nt as ft,r as bt}from"./BreadcrumbContext-Bxr1TyKN.js";import{c as jt,t as O,x as wt}from"./label-YjU0jMtG.js";import{At as Nt,Ct as Oe,Ft as kt,Mr as St,Mt as It,Pt as Ct,jt as At,t as Pt}from"./RoutineRunVariablesDialog-DMTFaEse.js";import{Z as Rt}from"./mention-chips-ClRmijVb.js";import{t as De}from"./AgentAvatar-DZh8tNnK.js";import{E as Tt,T as Et}from"./checkbox-5wFlZdZn.js";import{l as T,t as Me}from"./MarkdownEditor-D7suACD6.js";import{h as Ot}from"./StatusIcon-YdJnE47W.js";import{t as xe}from"./arrow-right-bnOoaiPg.js";import{a as Dt}from"./ToastContext-Dh8dPdr5.js";import{r as Mt,t as _t}from"./clipboard-CTmezHYG.js";import{a as de,c as ue,l as me,n as pe,r as he}from"./select-DRgGQ-iP.js";import{i as qt,r as Ft}from"./use-copy-action-qHyHFl14.js";import{t as Kt}from"./heartbeats-Dae6h2SU.js";import{t as ye}from"./badge-D5aOL1Ll.js";import{t as V}from"./input-CtLHwxEw.js";import{i as Lt,o as Wt}from"./company-members-Dd6xBf6K.js";import{r as Ut,t as $t}from"./card-PCL2aF_L.js";import{t as te}from"./EmptyState-DliXLd04.js";import{t as Vt}from"./PageSkeleton-BZF4K6Hf.js";import{A as zt,B as We,Bt as _e,C as Gt,D as Qt,E as Bt,F as Ht,I as qe,It as Jt,L as Ue,M as Zt,Mt as Xt,N as Yt,Nt as es,O as ts,P as ss,Qt as is,R as G,S as ns,T as as,V as rs,_n as ve,_t as os,bn as cs,j as ls,k as ds,on as us,w as $e,x as ms,z as ps,zt as Y}from"./index-D6WtpzBM.js";var u=Le(dt(),1);function hs(s,a,n){const c={label:a.label.trim()||null};return s.kind==="schedule"&&(c.cronExpression=a.cronExpression.trim(),c.timezone=s.timezone??n),s.kind==="webhook"&&(c.signingMode=a.signingMode,c.replayWindowSec=Number(a.replayWindowSec||"300")),c}i(hs,"buildRoutineTriggerPatch");var e=Le(pt(),1),gs=["app_webhook","bearer","hmac_sha256","github_hmac","none"],xs=new Set(["app_webhook","bearer","github_hmac","fireflies_hmac","none"]);function ys(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}i(ys,"getLocalTimezone$1");function vs({trigger:s,onSave:a,onRotate:n,onDelete:c,disabled:r}){const[m,l]=(0,u.useState)({label:s.label??"",cronExpression:s.cronExpression??"",signingMode:s.signingMode??"bearer",replayWindowSec:String(s.replayWindowSec??300)});(0,u.useEffect)(()=>{l({label:s.label??"",cronExpression:s.cronExpression??"",signingMode:s.signingMode??"bearer",replayWindowSec:String(s.replayWindowSec??300)})},[s]);const k=s.kind==="schedule"?ve:s.kind==="webhook"?is:gt,I=s.kind==="schedule"?Bt(m.cronExpression):null,_=/fail|error/i.test(s.lastResult??""),C=s.lastResult?.startsWith("Created execution issue ")?"Task created":s.lastResult;return(0,e.jsxs)("form",{"aria-label":`Trigger: ${s.label??s.kind}`,className:"space-y-4 rounded-lg border border-border p-4",onSubmit:i(x=>x.preventDefault(),"onSubmit"),children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,e.jsx)(k,{className:"h-3.5 w-3.5 shrink-0"}),(0,e.jsx)("span",{className:"truncate",children:s.label??s.kind})]}),I?(0,e.jsx)("p",{id:`cron-readable-${s.id}`,className:"text-xs text-muted-foreground",children:I}):null]}),(0,e.jsxs)("div",{className:"flex shrink-0 items-center gap-2",children:[s.lastResult?(0,e.jsx)(ye,{variant:_?"destructive":"secondary",children:C}):null,(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:s.kind==="schedule"&&s.nextRunAt?`Next: ${new Date(s.nextRunAt).toLocaleString()}`:s.kind==="webhook"?"Webhook":"API"})]})]}),s.kind==="webhook"&&s.webhookUrl&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{htmlFor:`webhook-url-${s.id}`,className:"text-xs",children:"Webhook URL"}),(0,e.jsx)(V,{id:`webhook-url-${s.id}`,value:s.webhookUrl,readOnly:!0,onFocus:i(x=>x.target.select(),"onFocus")}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Send a POST request with Content-Type: application/json. Keep this URL private when signing is disabled."})]}),(0,e.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Label"}),(0,e.jsx)(V,{value:m.label,disabled:r,onChange:i(x=>l(S=>({...S,label:x.target.value})),"onChange")})]}),s.kind==="schedule"&&(0,e.jsxs)("div",{className:"space-y-1.5 md:col-span-2",children:[(0,e.jsx)(O,{className:"text-xs",children:"Schedule"}),(0,e.jsx)($e,{value:m.cronExpression,onChange:i(x=>l(S=>({...S,cronExpression:x})),"onChange")})]}),s.kind==="webhook"&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Signing mode"}),(0,e.jsxs)(pe,{value:m.signingMode,onValueChange:i(x=>l(S=>({...S,signingMode:x})),"onValueChange"),disabled:r,children:[(0,e.jsx)(ue,{children:(0,e.jsx)(me,{})}),(0,e.jsx)(he,{children:gs.map(x=>(0,e.jsx)(de,{value:x,children:x},x))})]})]}),!xs.has(m.signingMode)&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Replay window (seconds)"}),(0,e.jsx)(V,{value:m.replayWindowSec,disabled:r,onChange:i(x=>l(S=>({...S,replayWindowSec:x.target.value})),"onChange")})]})]})]}),!r&&(0,e.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,e.jsxs)(E,{variant:"ghost",size:"sm",className:"mr-auto text-muted-foreground hover:text-destructive",onClick:i(()=>c(s.id),"onClick"),children:[(0,e.jsx)(Et,{className:"mr-1.5 h-3.5 w-3.5"}),"Delete"]}),s.kind==="webhook"&&(0,e.jsxs)(E,{variant:"outline",size:"sm",onClick:i(()=>n(s.id),"onClick"),children:[(0,e.jsx)(Tt,{className:"mr-1.5 h-3.5 w-3.5"}),"Rotate secret"]}),(0,e.jsxs)(E,{variant:"outline",size:"sm",onClick:i(()=>a(s.id,hs(s,m,ys())),"onClick"),children:[(0,e.jsx)(Ft,{className:"mr-1.5 h-3.5 w-3.5"}),"Save trigger"]})]})]})}i(vs,"RoutineTriggerCard");var fs=[{value:"coalesce_if_active",title:"Coalesce if active",description:"Keep one follow-up run queued while an active run is still working."},{value:"always_enqueue",title:"Always enqueue",description:"Queue every trigger occurrence, even if several runs stack up."},{value:"skip_if_active",title:"Skip if active",description:"Drop overlapping trigger occurrences while the routine is already active."}],bs=[{value:"skip_missed",title:"Skip missed",description:"Ignore schedule windows that were missed while paused."},{value:"enqueue_missed_with_cap",title:"Enqueue missed with cap",description:"Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap."}],js=[{value:"always",title:"Run on every scheduled tick",description:"Fire on the schedule no matter what — the default behavior."},{value:"require_external_activity",title:"Skip when there's been no activity since the last run",description:"On a scheduled tick, only run if something happened since the last run that finished. Lets a watcher-style routine stay asleep while the system is settled instead of burning tokens."}],ws=[{value:"company",title:"Company-wide",description:"Any activity across the company counts as a reason to run."},{value:"project",title:"This project",description:"Only activity in the routine's project counts as a reason to run."}],Ns=["schedule","webhook"],ks=["app_webhook","bearer","hmac_sha256","github_hmac","none"],Ss={bearer:"Send Authorization: Bearer <secret> with each request.",hmac_sha256:"Send X-Paperclip-Timestamp and X-Paperclip-Signature: sha256=<hex>, signing timestamp + a dot + the exact JSON body.",github_hmac:"Accept GitHub-style X-Hub-Signature-256 header (HMAC over raw body, no timestamp).",app_webhook:"Accept a bearer token or an HMAC-SHA256 signature over the exact request body in X-Hub-Signature or X-Hub-Signature-256.",fireflies_hmac:"Signed webhook (legacy).",none:"No authentication — the webhook URL itself acts as a shared secret."},Is=new Set(["app_webhook","bearer","github_hmac","fireflies_hmac","none"]);function Cs({defaultDescriptionAnnotationsOpen:s=!1}={}){const{routine:a,editDraft:n,setEditDraft:c,assigneeOptions:r,projectOptions:m,recentAssigneeIds:l,recentProjectIds:k,agentById:I,projectById:_,currentAssignee:C,currentProject:x,mentionOptions:S,assigneeSelectorRef:D,projectSelectorRef:q,descriptionEditorRef:A,routineRuns:g,activity:b,saveRoutine:w,saveConflict:se,isSectionDirty:v,navigateToSection:P}=G(),[j,M]=(0,u.useState)(s),o=a.triggers.length,Q=(0,u.useMemo)(()=>{const d=a.triggers.filter(y=>y.kind==="schedule"&&y.nextRunAt).map(y=>new Date(y.nextRunAt)).sort((y,z)=>y.getTime()-z.getTime())[0];return d?d.toLocaleString():null},[a.triggers]),U=n.env?Object.keys(n.env).length:0,R=(g??[])[0]??null,B=(b??[]).slice(0,5);return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsx)("div",{className:"overflow-x-auto overscroll-x-contain",children:(0,e.jsxs)("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[(0,e.jsx)("span",{children:"For"}),(0,e.jsx)(Oe,{ref:D,value:n.assigneeAgentId,options:r,recentOptionIds:l,placeholder:"Responsible",noneLabel:"No responsible",searchPlaceholder:"Search responsible...",emptyMessage:"No responsible found.",onChange:i(d=>c(y=>({...y,assigneeAgentId:d})),"onChange"),onConfirm:i(()=>{n.projectId?A.current?.focus():q.current?.focus()},"onConfirm"),renderTriggerValue:i(d=>d?C?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(De,{agent:C,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,e.jsx)("span",{className:"truncate",children:d.label})]}):(0,e.jsx)("span",{className:"truncate",children:d.label}):(0,e.jsx)("span",{className:"text-muted-foreground",children:"Responsible"}),"renderTriggerValue"),renderOption:i(d=>{if(!d.id)return(0,e.jsx)("span",{className:"truncate",children:d.label});const y=I.get(d.id);return(0,e.jsxs)(e.Fragment,{children:[y?(0,e.jsx)(De,{agent:y,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,(0,e.jsx)("span",{className:"truncate",children:d.label})]})},"renderOption")}),(0,e.jsx)("span",{children:"in"}),(0,e.jsx)(Oe,{ref:q,value:n.projectId,options:m,recentOptionIds:k,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:i(d=>c(y=>({...y,projectId:d})),"onChange"),onConfirm:i(()=>A.current?.focus(),"onConfirm"),renderTriggerValue:i(d=>d&&x?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:x.color??"var(--project-none)"}}),(0,e.jsx)("span",{className:"truncate",children:d.label})]}):(0,e.jsx)("span",{className:"text-muted-foreground",children:"Project"}),"renderTriggerValue"),renderOption:i(d=>{if(!d.id)return(0,e.jsx)("span",{className:"truncate",children:d.label});const y=_.get(d.id);return(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:y?.color??"var(--project-none)"}}),(0,e.jsx)("span",{className:"truncate",children:d.label})]})},"renderOption")})]})}),a.assigneeAgentId?null:(0,e.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-4 text-sm text-amber-900 dark:text-amber-200",children:"Default agent required. This routine can stay as a draft and still run manually, but automation stays paused until you assign a default agent."}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("div",{className:"flex items-center justify-end",children:a.descriptionDocument?(0,e.jsx)(Xt,{issueId:a.id,docKey:"description",target:{kind:"routine",routineId:a.id,documentKey:"description"},panelOpen:j,onToggle:i(()=>M(d=>!d),"onToggle")}):null}),a.descriptionDocument?(0,e.jsx)(es,{issueId:a.id,doc:a.descriptionDocument,target:{kind:"routine",routineId:a.id,documentKey:"description"},bodyMarkdown:n.description,draftDirty:v("overview")||w.isPending,draftConflicted:se,historicalPreview:!1,locationHash:typeof window>"u"?"":window.location.hash,panelOpen:j,onPanelOpenChange:M,children:(0,e.jsx)(Me,{ref:A,value:n.description,onChange:i(d=>c(y=>({...y,description:d})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-120px) text-sm leading-7",mentions:S,onSubmit:i(()=>{!w.isPending&&n.title.trim()&&w.mutate()},"onSubmit")})}):(0,e.jsx)(Me,{ref:A,value:n.description,onChange:i(d=>c(y=>({...y,description:d})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-120px) text-sm leading-7",mentions:S,onSubmit:i(()=>{!w.isPending&&n.title.trim()&&w.mutate()},"onSubmit")})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(rs,{}),(0,e.jsx)(We,{title:n.title,description:n.description,value:n.variables,onChange:i(d=>c(y=>({...y,variables:d})),"onChange")})]}),(0,e.jsxs)("div",{className:"grid gap-3 sm:grid-cols-3",children:[(0,e.jsx)(ce,{icon:ve,label:"Triggers",value:o===0?"None":`${o} active`,hint:Q?`Next fire ${Q}`:"No schedule",to:i(()=>P("triggers"),"to"),ariaLabel:`${o} triggers. Open triggers.`}),(0,e.jsx)(ce,{icon:Mt,label:"Secrets",value:U===0?"None":`${U} bound`,hint:"Manage bound secrets",to:i(()=>P("secrets"),"to"),ariaLabel:`${U} secrets bound. Open secrets.`}),(0,e.jsx)(ce,{icon:wt,label:"Last run",value:R?R.status.replaceAll("_"," "):"No runs",hint:R?Ee(R.triggeredAt):"Trigger a run",to:i(()=>P("runs"),"to"),ariaLabel:R?`Last run ${R.status}. Open runs.`:"No runs. Open runs."})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Recent activity"}),B.length===0?(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):(0,e.jsxs)("div",{className:"divide-y divide-border/60",children:[B.map(d=>(0,e.jsxs)("div",{className:"flex items-center gap-2 py-1.5 text-xs",children:[(0,e.jsx)(ye,{variant:"outline",className:"shrink-0 font-mono",children:d.action}),(0,e.jsx)("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:d.details&&Object.keys(d.details).length>0?Object.keys(d.details).slice(0,3).join(" · "):""}),(0,e.jsx)("span",{className:"shrink-0 text-muted-foreground/60",children:Ee(d.createdAt)})]},d.id)),(0,e.jsxs)("button",{type:"button",onClick:i(()=>P("activity"),"onClick"),className:"flex items-center gap-1 pt-2 text-xs text-muted-foreground hover:text-foreground",children:["View all activity ",(0,e.jsx)(xe,{className:"h-3 w-3"})]})]})]})]})}i(Cs,"OverviewSection");function ce({icon:s,label:a,value:n,hint:c,to:r,ariaLabel:m}){return(0,e.jsx)("button",{type:"button",onClick:r,"aria-label":m,className:"text-left",children:(0,e.jsx)($t,{className:"gap-2 p-4 transition-colors hover:border-border hover:bg-accent/30",children:(0,e.jsxs)(Ut,{className:"space-y-1 p-0",children:[(0,e.jsxs)("div",{className:"flex items-center gap-1.5 text-xs uppercase tracking-wide text-muted-foreground",children:[(0,e.jsx)(s,{className:"h-3.5 w-3.5"}),a,(0,e.jsx)(xe,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground/60"})]}),(0,e.jsx)("p",{className:"text-lg font-semibold",children:n}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:c})]})})})}i(ce,"SummaryCard");function As(){const{routine:s,newTrigger:a,setNewTrigger:n,createTrigger:c,updateTrigger:r,deleteTrigger:m,rotateTrigger:l,secretMessage:k,copySecretValue:I,setSecretMessage:_}=G(),[C,x]=(0,u.useState)(!1),[S,D]=(0,u.useState)(!0),q=(0,u.useMemo)(()=>a.kind==="schedule"?as(a.cronExpression):null,[a.cronExpression,a.kind]),A=c.isPending||(q?!q.valid||!S:!1);return(0,u.useEffect)(()=>{a.kind!=="schedule"&&D(!0)},[a.kind]),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:s.triggers.length===0?"No triggers yet":`${s.triggers.length} trigger${s.triggers.length===1?"":"s"}`}),(0,e.jsx)(E,{size:"sm",variant:C?"secondary":"default",onClick:i(()=>x(g=>!g),"onClick"),"aria-expanded":C,children:C?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(Rt,{className:"mr-1.5 h-3.5 w-3.5"}),"Cancel"]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(xt,{className:"mr-1.5 h-3.5 w-3.5"}),"New trigger"]})})]}),C?(0,e.jsxs)("div",{className:"space-y-3 rounded-lg border border-border p-4",children:[(0,e.jsx)("p",{className:"text-sm font-medium",children:"Add trigger"}),(0,e.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Kind"}),(0,e.jsxs)(pe,{value:a.kind,onValueChange:i(g=>n(b=>({...b,kind:g})),"onValueChange"),children:[(0,e.jsx)(ue,{children:(0,e.jsx)(me,{})}),(0,e.jsx)(he,{children:Ns.map(g=>(0,e.jsx)(de,{value:g,children:g},g))})]})]}),a.kind==="schedule"&&(0,e.jsxs)("div",{className:"space-y-1.5 md:col-span-2",children:[(0,e.jsx)(O,{className:"text-xs",children:"Schedule"}),(0,e.jsx)($e,{value:a.cronExpression,onChange:i(g=>n(b=>({...b,cronExpression:g})),"onChange"),onValidityChange:D})]}),a.kind==="webhook"&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Signing mode"}),(0,e.jsxs)(pe,{value:a.signingMode,onValueChange:i(g=>n(b=>({...b,signingMode:g})),"onValueChange"),children:[(0,e.jsx)(ue,{children:(0,e.jsx)(me,{})}),(0,e.jsx)(he,{children:ks.map(g=>(0,e.jsx)(de,{value:g,children:g},g))})]}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:Ss[a.signingMode]})]}),!Is.has(a.signingMode)&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Replay window (seconds)"}),(0,e.jsx)(V,{value:a.replayWindowSec,onChange:i(g=>n(b=>({...b,replayWindowSec:g.target.value})),"onChange")})]})]})]}),(0,e.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[(0,e.jsx)(E,{size:"sm",variant:"ghost",onClick:i(()=>x(!1),"onClick"),children:"Cancel"}),(0,e.jsx)(E,{size:"sm",onClick:i(()=>c.mutate(void 0,{onSuccess:i(()=>{n(Ue()),x(!1)},"onSuccess")}),"onClick"),disabled:A,children:c.isPending?"Adding...":"Add trigger"})]})]}):null,k?(0,e.jsxs)("div",{className:"space-y-3 rounded-lg border border-border bg-muted/20 p-4 text-sm",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"font-medium",children:k.title}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Save this now. Paperclip will not show the secret value again."})]}),(0,e.jsx)("div",{className:"space-y-3",children:k.entries.map((g,b)=>(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(V,{"aria-label":"New webhook URL",value:g.webhookUrl,readOnly:!0,className:"flex-1"}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>I("Webhook URL",g.webhookUrl),"onClick"),children:"URL"})]}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(V,{"aria-label":"New webhook secret",value:g.webhookSecret,readOnly:!0,className:"flex-1"}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>I("Webhook secret",g.webhookSecret),"onClick"),children:"Secret"})]})]},`${g.webhookUrl}-${b}`))}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>_(null),"onClick"),children:"Done"})]}):null,s.triggers.length===0?(0,e.jsx)(te,{icon:ve,message:"No triggers yet.",action:"Add a trigger",onAction:i(()=>x(!0),"onAction")}):(0,e.jsx)("div",{className:"space-y-3",children:s.triggers.map(g=>(0,e.jsx)(vs,{trigger:g,onSave:i((b,w)=>r.mutate({id:b,patch:w}),"onSave"),onRotate:i(b=>l.mutate(b),"onRotate"),onDelete:i(b=>m.mutate(b),"onDelete")},g.id))})]})}i(As,"TriggersSection");function Ps(){const{editDraft:s,setEditDraft:a,navigateToSection:n}=G(),c=s.variables.length>0;return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3 rounded-md border border-border bg-muted/20 px-4 py-3 text-xs",children:[(0,e.jsxs)("span",{className:"flex-1 text-muted-foreground",children:["Variables are auto-detected from ",(0,e.jsx)("code",{className:"font-mono",children:"{{placeholders}}"})," in the title & instructions. The variable name is read-only — rename by editing the placeholder."]}),(0,e.jsxs)(E,{variant:"secondary",size:"sm",onClick:i(()=>n("overview"),"onClick"),children:[(0,e.jsx)(us,{className:"mr-1.5 h-3.5 w-3.5"}),"Edit instructions"]})]}),c?(0,e.jsx)(We,{title:s.title,description:s.description,value:s.variables,onChange:i(r=>a(m=>({...m,variables:r})),"onChange")}):(0,e.jsx)(te,{icon:cs,message:"No variables yet. Add a {{placeholder}} in the title or instructions to create one.",action:"Edit instructions",onAction:i(()=>n("overview"),"onAction")})]})}i(Ps,"VariablesSection");function Rs(){const{editDraft:s,setEditDraft:a,availableSecrets:n,createSecret:c}=G(),r=(0,u.useMemo)(()=>[...n].filter(m=>m.status==="active").sort((m,l)=>{const k=(l.referenceCount??0)-(m.referenceCount??0);return k!==0?k:new Date(l.updatedAt).getTime()-new Date(m.updatedAt).getTime()}).slice(0,8),[n]);return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground",children:["Routine secrets apply to every task this routine creates. They override matching keys in project and agent env. ",(0,e.jsx)("span",{className:"font-mono",children:"PAPERCLIP_*"})," names are reserved."]}),(0,e.jsx)(Jt,{value:s.env??{},secrets:n,recentlyUsedSecrets:r,onCreateSecret:i(async(m,l)=>c.mutateAsync({name:m,value:l}),"onCreateSecret"),onChange:i(m=>a(l=>({...l,env:m??null})),"onChange")})]})}i(Rs,"SecretsSection");function Ts(){const{editDraft:s,setEditDraft:a,routine:n}=G(),c=n.triggers.some(m=>m.kind==="schedule"),r=s.activityGatePolicy==="require_external_activity";return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Concurrency"}),(0,e.jsx)(Y,{ariaLabel:"Concurrency policy",value:s.concurrencyPolicy,onValueChange:i(m=>a(l=>({...l,concurrencyPolicy:m})),"onValueChange"),options:fs})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Catch-up"}),(0,e.jsx)(Y,{ariaLabel:"Catch-up policy",value:s.catchUpPolicy,onValueChange:i(m=>a(l=>({...l,catchUpPolicy:m})),"onValueChange"),options:bs})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Advanced run policy"}),(0,e.jsx)(Y,{ariaLabel:"Advanced run policy",value:s.activityGatePolicy,onValueChange:i(m=>a(l=>({...l,activityGatePolicy:m})),"onValueChange"),options:js,disabled:!c}),c?r?(0,e.jsxs)("div",{className:"space-y-2 rounded-lg border border-border p-3",children:[(0,e.jsx)(O,{className:"text-xs font-medium",children:"Activity scope"}),(0,e.jsx)(Y,{ariaLabel:"Activity gate scope",value:s.activityGateScope,onValueChange:i(m=>a(l=>({...l,activityGateScope:m})),"onValueChange"),options:ws})]}):null:(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Add a schedule trigger to gate runs on activity. Webhook, manual, and API fires always run."})]}),(0,e.jsx)(Os,{triggers:n.triggers,concurrencyPolicy:s.concurrencyPolicy})]})}i(Ts,"DeliverySection");var Es={queued:"text-emerald-600 dark:text-emerald-400",coalesced:"text-amber-600 dark:text-amber-400",skipped:"text-muted-foreground"};function Os({triggers:s,concurrencyPolicy:a}){const n=(0,u.useMemo)(()=>{const c=s.filter(r=>r.kind==="schedule"&&r.enabled&&r.cronExpression).map(r=>({trigger:r,fires:Qt(r.cronExpression,5,{timeZone:r.timezone??"UTC"})})).filter(r=>r.fires.length>0).sort((r,m)=>r.fires[0].getTime()-m.fires[0].getTime())[0];return c?{timeZone:c.trigger.timezone??"UTC",entries:ts(c.fires,a)}:null},[s,a]);return(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Next 5 fires"}),n?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"space-y-1.5 rounded-lg border border-border p-3 font-mono text-xs",children:n.entries.map((c,r)=>(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-muted-foreground/40",children:"·"}),(0,e.jsx)("span",{className:"tabular-nums",children:Ds(c.at,n.timeZone)}),(0,e.jsx)(xe,{className:"h-3 w-3 shrink-0 text-muted-foreground/50"}),(0,e.jsx)("span",{className:ct("font-medium",Es[c.disposition]),children:c.label}),c.note?(0,e.jsxs)("span",{className:"truncate text-muted-foreground/60",children:["(",c.note,")"]}):null]},r))}),(0,e.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/60",children:["Preview assumes the previous run is still in flight when the next fires. Times shown in"," ",n.timeZone,"."]})]}):(0,e.jsx)("p",{className:"rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground",children:"No enabled schedule trigger to preview. Add a schedule in Triggers to see how this policy treats upcoming fires."})]})}i(Os,"NextFiresPreview");function Ds(s,a){try{return new Intl.DateTimeFormat(void 0,{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(s).replace(",","")}catch{return s.toISOString()}}i(Ds,"formatFireTime");var ge="paperclip.routineLastSection";function Ms(s){return s.filter(a=>!a.archivedAt).map(a=>({id:a.id,label:a.name,searchText:a.description??""}))}i(Ms,"buildRoutineProjectOptions");var _s={overview:"Overview",triggers:"Triggers",variables:"Variables",secrets:"Secrets",delivery:"Delivery",runs:"Runs",activity:"Activity",history:"History"};function ee(s){return s!=null&&ss.includes(s)}i(ee,"isRoutineSection");function qs(s){try{const a=localStorage.getItem(ge);if(!a)return null;const n=JSON.parse(a)[s];return ee(n)?n:null}catch{return null}}i(qs,"readLastSection");function le(s,a){try{const n=localStorage.getItem(ge),c=n?JSON.parse(n):{};c[s]=a,localStorage.setItem(ge,JSON.stringify(c))}catch{}}i(le,"writeLastSection");var Fe={triggers:"triggers",runs:"runs",activity:"activity",secrets:"secrets",history:"history"};function Ke(s){s&&(s.style.height="auto",s.style.height=`${s.scrollHeight}px`)}i(Ke,"autoResizeTextarea");function Fs(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}i(Fs,"getLocalTimezone");function Ks(s){return{...s,description:s.description.trim()||null,projectId:s.projectId||null,assigneeAgentId:s.assigneeAgentId||null,env:s.env&&Object.keys(s.env).length>0?s.env:null}}i(Ks,"buildRoutineMutationPayload");function di(){const{routineId:s,section:a}=ht(),{selectedCompanyId:n}=mt(),{setBreadcrumbs:c}=vt(),r=lt(),m=yt(),{pushToast:l}=Dt(),k=(0,u.useRef)(null),I=(0,u.useRef)(null),_=(0,u.useRef)(null),C=(0,u.useRef)(null),x=(0,u.useRef)(null),[S,D]=(0,u.useState)(null),[q,A]=(0,u.useState)(!1),[g,b]=(0,u.useState)(!1),[w,se]=(0,u.useState)(Ue),[v,P]=(0,u.useState)({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed",activityGatePolicy:"always",activityGateScope:"company",variables:[],env:null}),j=ee(a)?a:"overview",M=(0,u.useCallback)((t,h)=>{s&&(le(s,t),m(`/routines/${s}/${t}`,{replace:h?.replace??!0}))},[m,s]),{data:o,isLoading:Q,error:U}=L({queryKey:p.routines.detail(s),queryFn:i(()=>T.get(s),"queryFn"),enabled:!!s}),R=o?.activeIssue?.id,{data:B}=L({queryKey:p.issues.liveRuns(R),queryFn:i(()=>Kt.liveRunsForIssue(R),"queryFn"),enabled:!!R,refetchInterval:3e3}),d=(B??[]).length>0,{data:y}=L({queryKey:p.routines.runs(s),queryFn:i(()=>T.listRuns(s),"queryFn"),enabled:!!s,refetchInterval:d?3e3:!1}),z=(0,u.useMemo)(()=>({triggerIds:o?.triggers.map(t=>t.id)??[],runIds:y?.map(t=>t.id)??[]}),[o?.triggers,y]),{data:Ve}=L({queryKey:[...p.routines.activity(n,s),z.triggerIds.join(","),z.runIds.join(",")],queryFn:i(()=>T.activity(n,s,z),"queryFn"),enabled:!!n&&!!s&&!!o}),{data:F}=L({queryKey:p.agents.list(n),queryFn:i(()=>bt.list(n),"queryFn"),enabled:!!n}),{data:K}=L({queryKey:p.projects.list(n,{includeArchived:!0}),queryFn:i(()=>Ot.list(n,{includeArchived:!0}),"queryFn"),enabled:!!n}),{data:fe}=L({queryKey:p.access.companyUserDirectory(n),queryFn:i(()=>Wt.listUserDirectory(n),"queryFn"),enabled:!!n}),{data:ze=[]}=L({queryKey:n?p.secrets.list(n):["secrets","none"],queryFn:i(()=>_e.list(n),"queryFn"),enabled:!!n}),Ge=W({mutationFn:i(t=>{if(!n)throw new Error("Select a company to create secrets");return _e.create(n,t)},"mutationFn"),onSuccess:i(()=>{n&&r.invalidateQueries({queryKey:p.secrets.list(n)})},"onSuccess")}),f=(0,u.useMemo)(()=>o?{title:o.title,description:o.description??"",projectId:o.projectId??"",assigneeAgentId:o.assigneeAgentId??"",priority:o.priority,concurrencyPolicy:o.concurrencyPolicy,catchUpPolicy:o.catchUpPolicy,activityGatePolicy:o.activityGatePolicy,activityGateScope:o.activityGateScope,variables:o.variables,env:o.env??null}:null,[o]),H=(0,u.useMemo)(()=>{if(!f)return[];const t=[];return v.title!==f.title&&t.push({key:"title",label:"the title"}),v.description!==f.description&&t.push({key:"description",label:"the description"}),v.projectId!==f.projectId&&t.push({key:"projectId",label:"the project"}),v.assigneeAgentId!==f.assigneeAgentId&&t.push({key:"assigneeAgentId",label:"the default agent"}),v.priority!==f.priority&&t.push({key:"priority",label:"the priority"}),v.concurrencyPolicy!==f.concurrencyPolicy&&t.push({key:"concurrencyPolicy",label:"the concurrency policy"}),v.catchUpPolicy!==f.catchUpPolicy&&t.push({key:"catchUpPolicy",label:"the catch-up policy"}),v.activityGatePolicy!==f.activityGatePolicy&&t.push({key:"activityGatePolicy",label:"the advanced run policy"}),v.activityGateScope!==f.activityGateScope&&t.push({key:"activityGateScope",label:"the activity gate scope"}),JSON.stringify(v.variables)!==JSON.stringify(f.variables)&&t.push({key:"variables",label:"the variables"}),JSON.stringify(v.env??null)!==JSON.stringify(f.env??null)&&t.push({key:"env",label:"the secrets"}),t},[v,f]),ie=H.length>0,J=(0,u.useCallback)(t=>{const h=qe[t];return h?H.filter(N=>h.includes(N.key)):[]},[H]),ne=(0,u.useCallback)(t=>J(t).length>0,[J]),be=(0,u.useCallback)(t=>{if(!f)return;const h=qe[t];h&&P(N=>{const Re={...N};for(const Te of h)Re[Te]=f[Te];return Re})},[f]);(0,u.useEffect)(()=>{o&&(c([{label:"Routines",href:"/routines"},{label:o.title}]),f&&(k.current!==o.id||!ie)&&(P(f),k.current=o.id))},[o,f,ie,c]),(0,u.useEffect)(()=>{Ke(I.current)},[v.title,o?.id]),(0,u.useEffect)(()=>{s&&ee(a)&&le(s,a)},[s,a]);const Qe=(0,u.useCallback)(async(t,h)=>{try{await _t(h),l({title:`${t} copied`,tone:"success"})}catch(N){l({title:`Failed to copy ${t.toLowerCase()}`,body:N instanceof Error?N.message:"Clipboard access was denied.",tone:"error"})}},[l]),Z=W({mutationFn:i(()=>{const t=Ks(v),h=o?.latestRevisionId??null;return T.update(s,{...t,...h?{baseRevisionId:h}:{}})},"mutationFn"),onSuccess:i(async()=>{A(!1),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)}),r.invalidateQueries({queryKey:p.routines.revisions(s)})])},"onSuccess"),onError:i(t=>{if(t instanceof ut&&t.status===409){A(!0),l({title:"Routine changed",body:"Someone else updated this routine. Reload to see the latest revision.",tone:"warn"});return}l({title:"Failed to save routine",body:t instanceof Error?t.message:"Paperclip could not save the routine.",tone:"error"})},"onError")}),X=W({mutationFn:i(t=>T.run(s,{...t?.variables&&Object.keys(t.variables).length>0?{variables:t.variables}:{},...t?.assigneeAgentId!==void 0?{assigneeAgentId:t.assigneeAgentId}:{},...t?.projectId!==void 0?{projectId:t.projectId}:{},...t?.executionWorkspaceId!==void 0?{executionWorkspaceId:t.executionWorkspaceId}:{},...t?.executionWorkspacePreference!==void 0?{executionWorkspacePreference:t.executionWorkspacePreference}:{},...t?.executionWorkspaceSettings!==void 0?{executionWorkspaceSettings:t.executionWorkspaceSettings}:{}}),"mutationFn"),onSuccess:i(async()=>{l({title:"Routine run started",tone:"success"}),b(!1),M("runs"),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.runs(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Routine run failed",body:t instanceof Error?t.message:"Paperclip could not start the routine run.",tone:"error"})},"onError")}),je=W({mutationFn:i(t=>T.update(s,{status:t}),"mutationFn"),onSuccess:i(async(t,h)=>{l({title:"Routine saved",body:h==="paused"?"Automation paused.":"Automation enabled.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to update routine",body:t instanceof Error?t.message:"Paperclip could not update the routine.",tone:"error"})},"onError")}),Be=W({mutationFn:i(async()=>{const t=(o?.triggers??[]).filter(N=>N.kind===w.kind).length,h=t>0?`${w.kind}-${t+1}`:w.kind;return T.createTrigger(s,{kind:w.kind,label:h,...w.kind==="schedule"?{cronExpression:w.cronExpression.trim(),timezone:Fs()}:{},...w.kind==="webhook"?{signingMode:w.signingMode,replayWindowSec:Number(w.replayWindowSec||"300")}:{}})},"mutationFn"),onSuccess:i(async t=>{t.secretMaterial?D({title:"Webhook trigger created",entries:[{webhookUrl:t.secretMaterial.webhookUrl,webhookSecret:t.secretMaterial.webhookSecret}]}):l({title:"Trigger added",body:"The routine schedule was saved.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to add trigger",body:t instanceof Error?t.message:"Paperclip could not create the trigger.",tone:"error"})},"onError")}),He=W({mutationFn:i(({id:t,patch:h})=>T.updateTrigger(t,h),"mutationFn"),onSuccess:i(async()=>{l({title:"Trigger saved",body:"The routine cadence update was saved.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to update trigger",body:t instanceof Error?t.message:"Paperclip could not update the trigger.",tone:"error"})},"onError")}),Je=W({mutationFn:i(t=>T.deleteTrigger(t),"mutationFn"),onSuccess:i(async()=>{l({title:"Trigger deleted",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to delete trigger",body:t instanceof Error?t.message:"Paperclip could not delete the trigger.",tone:"error"})},"onError")}),Ze=W({mutationFn:i(t=>T.rotateTriggerSecret(t),"mutationFn"),onSuccess:i(async t=>{D({title:"Webhook secret rotated",entries:[{webhookUrl:t.secretMaterial.webhookUrl,webhookSecret:t.secretMaterial.webhookSecret}]}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to rotate webhook secret",body:t instanceof Error?t.message:"Paperclip could not rotate the webhook secret.",tone:"error"})},"onError")}),we=(0,u.useMemo)(()=>new Map((F??[]).map(t=>[t.id,t])),[F]),Ne=(0,u.useMemo)(()=>new Map((K??[]).map(t=>[t.id,t])),[K]),ae=(0,u.useMemo)(()=>It(),[o?.id]),Xe=(0,u.useMemo)(()=>Nt(),[o?.id]),Ye=(0,u.useMemo)(()=>Ct((F??[]).filter(t=>t.status!=="terminated"),ae).map(t=>({id:t.id,label:t.name,searchText:`${t.name} ${t.role} ${t.title??""}`})),[F,ae]),et=(0,u.useMemo)(()=>Ms(K??[]),[K]),tt=(0,u.useMemo)(()=>Lt({agents:F,projects:(K??[]).filter(t=>!t.archivedAt),members:fe?.users}),[F,fe?.users,K]),st=(0,u.useCallback)(t=>{P(h=>{const N=typeof t=="function"?t(h):t;return N.assigneeAgentId&&N.assigneeAgentId!==h.assigneeAgentId&&kt(N.assigneeAgentId),N.projectId&&N.projectId!==h.projectId&&At(N.projectId),N})},[]),it=v.assigneeAgentId?we.get(v.assigneeAgentId)??null:null,nt=v.projectId?Ne.get(v.projectId)??null:null,ke=(0,u.useCallback)(()=>{A(!1),f&&P(f),r.invalidateQueries({queryKey:p.routines.detail(s)})},[r,f,s]),at=(0,u.useCallback)(t=>{t.secretMaterials.length>0&&(M("triggers"),D({title:t.secretMaterials.length===1?"Webhook trigger restored":`${t.secretMaterials.length} webhook triggers restored`,entries:t.secretMaterials.map(h=>({webhookUrl:h.webhookUrl,webhookSecret:h.webhookSecret}))}))},[M]),rt=(0,u.useCallback)(t=>{A(!1),r.setQueryData(p.routines.detail(s),h=>h&&{...h,...t.routine,latestRevisionId:t.revision.id,latestRevisionNumber:t.revision.revisionNumber}),P({title:t.routine.title,description:t.routine.description??"",projectId:t.routine.projectId??"",assigneeAgentId:t.routine.assigneeAgentId??"",priority:t.routine.priority,concurrencyPolicy:t.routine.concurrencyPolicy,catchUpPolicy:t.routine.catchUpPolicy,activityGatePolicy:t.routine.activityGatePolicy,activityGateScope:t.routine.activityGateScope,variables:t.routine.variables,env:t.routine.env??null}),k.current=t.routine.id},[r,s]);if(!n)return(0,e.jsx)(te,{icon:St,message:"Select a company to view routines."});const re=new URLSearchParams(window.location.search).get("tab");if(s&&re&&Fe[re])return(0,e.jsx)(oe,{to:`/routines/${s}/${Fe[re]}`,replace:!0});if(s&&!a){const t=qs(s)??"overview";return(0,e.jsx)(oe,{to:`/routines/${s}/${t}`,replace:!0})}if(s&&a&&!ee(a))return(0,e.jsx)(oe,{to:`/routines/${s}/overview`,replace:!0});if(Q)return(0,e.jsx)(Vt,{variant:"issues-list"});if(U||!o||!f)return(0,e.jsx)(te,{icon:qt,message:U instanceof Error?U.message:"We couldn't load this routine."});const $=o.status==="active",Se=je.isPending||o.status==="archived",Ie=o.status==="archived"?"Archived":o.assigneeAgentId?$?"Active":"Paused":"Draft",Ce=o.status==="archived"?"text-muted-foreground":$?"text-emerald-400":"text-muted-foreground",Ae={routine:o,routineId:s,companyId:o.companyId,editDraft:v,setEditDraft:st,routineDefaults:f,dirtyFields:H,isEditDirty:ie,sectionDirtyFields:J,isSectionDirty:ne,discardSection:be,saveRoutine:Z,saveConflict:q,reloadLatest:ke,automationEnabled:$,automationLabel:Ie,automationLabelClassName:Ce,automationToggleDisabled:Se,onToggleAutomation:i(()=>{if(!$&&!o.assigneeAgentId){l({title:"Default agent required",body:"Set a default agent before enabling routine automation.",tone:"warn"});return}je.mutate($?"paused":"active")},"onToggleAutomation"),onOpenRunDialog:i(()=>b(!0),"onOpenRunDialog"),runRoutinePending:X.isPending,newTrigger:w,setNewTrigger:se,createTrigger:Be,updateTrigger:He,deleteTrigger:Je,rotateTrigger:Ze,secretMessage:S,setSecretMessage:D,copySecretValue:Qe,availableSecrets:ze,createSecret:Ge,agents:F??[],projects:K??[],agentById:we,projectById:Ne,assigneeOptions:Ye,projectOptions:et,recentAssigneeIds:ae,recentProjectIds:Xe,mentionOptions:tt,currentAssignee:it,currentProject:nt,routineRuns:y,activity:Ve,hasLiveRun:d,activeIssueId:R,titleInputRef:I,descriptionEditorRef:_,assigneeSelectorRef:C,projectSelectorRef:x,onHistoryRestoreSecretMaterials:at,onHistoryRestored:rt,navigateToSection:M},Pe=Yt.includes(j);return(0,e.jsxs)(Ht.Provider,{value:Ae,children:[(0,e.jsx)("a",{href:"#routine-section",className:"sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-20 focus:rounded focus:bg-background focus:px-3 focus:py-1.5 focus:text-sm",children:"Skip to section"}),(0,e.jsxs)("div",{className:"-m-4 flex h-full min-h-0 flex-col overflow-hidden md:-m-6",children:[(0,e.jsxs)("header",{className:"flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6",children:[(0,e.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[(0,e.jsx)("textarea",{ref:I,"data-autosize-title":!0,className:"min-w-0 flex-1 resize-none overflow-hidden bg-transparent text-base font-semibold leading-7 outline-none placeholder:text-muted-foreground/50",placeholder:"Routine title",rows:1,value:v.title,onChange:i(t=>{P(h=>({...h,title:t.target.value})),Ke(t.target)},"onChange"),onKeyDown:i(t=>{t.key==="Enter"&&!t.metaKey&&!t.ctrlKey&&!t.nativeEvent.isComposing&&(t.preventDefault(),j==="overview"?_.current?.focus():M("overview"))},"onKeyDown")}),o.managedByPlugin?(0,e.jsxs)(ye,{variant:"outline",className:"hidden shrink-0 gap-1.5 text-xs text-muted-foreground sm:inline-flex",children:[(0,e.jsx)(ft,{className:"h-3 w-3"}),o.managedByPlugin.pluginDisplayName,(0,e.jsx)("span",{className:"font-mono text-(length:--text-nano)",children:o.managedByPlugin.resourceKey})]}):null]}),(0,e.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:[(0,e.jsx)(os,{onClick:i(()=>b(!0),"onClick"),disabled:X.isPending}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(jt,{size:"default",checked:$,onCheckedChange:Ae.onToggleAutomation,disabled:Se,"aria-label":$?"Pause automatic triggers":"Enable automatic triggers"}),(0,e.jsx)("span",{className:`text-sm font-medium ${Ce}`,children:Ie})]})]})]}),(0,e.jsx)(zt,{activeSection:j,onNavigate:M,isSectionDirty:ne}),(0,e.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,e.jsx)(ls,{activeSection:j,hrefFor:i(t=>`/routines/${s}/${t}`,"hrefFor"),isSectionDirty:ne,hasLiveRun:d,onNavigate:i(t=>le(s,t),"onNavigate")}),(0,e.jsx)("main",{id:"routine-section",role:"main",className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 pb-6 pt-10 md:px-8",children:(0,e.jsxs)("section",{"aria-labelledby":"routine-section-title",className:Pe?"mx-auto w-full max-w-3xl":"w-full",children:[(0,e.jsx)(Zt,{title:_s[j],copyText:j==="overview"?ps({editing:!0,draft:v.description,saved:o.description}):null}),j==="overview"&&(0,e.jsx)(Cs,{}),j==="triggers"&&(0,e.jsx)(As,{}),j==="variables"&&(0,e.jsx)(Ps,{}),j==="secrets"&&(0,e.jsx)(Rs,{}),j==="delivery"&&(0,e.jsx)(Ts,{}),j==="runs"&&(0,e.jsx)(Gt,{}),j==="activity"&&(0,e.jsx)(ms,{}),j==="history"&&(0,e.jsx)(ns,{}),Pe?(0,e.jsx)(ds,{dirtyFields:J(j),isSaving:Z.isPending,saveConflict:q,onSave:i(()=>{!Z.isPending&&v.title.trim()&&Z.mutate()},"onSave"),onDiscard:i(()=>be(j),"onDiscard"),onReload:ke}):null]})})]})]}),(0,e.jsx)(Pt,{open:g,onOpenChange:b,companyId:o.companyId,routineName:o.title,agents:F??[],projects:K??[],defaultProjectId:o.projectId,defaultAssigneeAgentId:o.assigneeAgentId,variables:o.variables??[],isPending:X.isPending,onSubmit:i(t=>X.mutate(t),"onSubmit")})]})}i(di,"RoutineDetail");export{di as RoutineDetail};
1
+ var ot=Object.defineProperty;var i=(s,a)=>ot(s,"name",{value:a,configurable:!0});import{i as Le}from"./rolldown-runtime-ZpX3ckPj.js";import{G as ct,Ra as lt,St as p,Va as dt,Wi as ut,aa as L,ht as mt,ia as W,za as pt}from"./agent-avatar-url-BnmqahQ7.js";import{An as Ee,Bn as ht,X as gt,ct as xt,f as yt,i as E,l as oe,n as vt,nt as ft,r as bt}from"./BreadcrumbContext-Bxr1TyKN.js";import{c as jt,t as O,x as wt}from"./label-YjU0jMtG.js";import{At as Nt,Ct as Oe,Ft as kt,Mr as St,Mt as It,Pt as Ct,jt as At,t as Pt}from"./RoutineRunVariablesDialog-DMTFaEse.js";import{Z as Rt}from"./mention-chips-ClRmijVb.js";import{t as De}from"./AgentAvatar-DZh8tNnK.js";import{E as Tt,T as Et}from"./checkbox-5wFlZdZn.js";import{l as T,t as Me}from"./MarkdownEditor-D7suACD6.js";import{h as Ot}from"./StatusIcon-YdJnE47W.js";import{t as xe}from"./arrow-right-bnOoaiPg.js";import{a as Dt}from"./ToastContext-Dh8dPdr5.js";import{r as Mt,t as _t}from"./clipboard-CTmezHYG.js";import{a as de,c as ue,l as me,n as pe,r as he}from"./select-DRgGQ-iP.js";import{i as qt,r as Ft}from"./use-copy-action-qHyHFl14.js";import{t as Kt}from"./heartbeats-Dae6h2SU.js";import{t as ye}from"./badge-D5aOL1Ll.js";import{t as V}from"./input-CtLHwxEw.js";import{i as Lt,o as Wt}from"./company-members-Dd6xBf6K.js";import{r as Ut,t as $t}from"./card-PCL2aF_L.js";import{t as te}from"./EmptyState-DliXLd04.js";import{t as Vt}from"./PageSkeleton-BZF4K6Hf.js";import{A as zt,B as We,Bt as _e,C as Gt,D as Qt,E as Bt,F as Ht,I as qe,It as Jt,L as Ue,M as Zt,Mt as Xt,N as Yt,Nt as es,O as ts,P as ss,Qt as is,R as G,S as ns,T as as,V as rs,_n as ve,_t as os,bn as cs,j as ls,k as ds,on as us,w as $e,x as ms,z as ps,zt as Y}from"./index-DvHeLBFO.js";var u=Le(dt(),1);function hs(s,a,n){const c={label:a.label.trim()||null};return s.kind==="schedule"&&(c.cronExpression=a.cronExpression.trim(),c.timezone=s.timezone??n),s.kind==="webhook"&&(c.signingMode=a.signingMode,c.replayWindowSec=Number(a.replayWindowSec||"300")),c}i(hs,"buildRoutineTriggerPatch");var e=Le(pt(),1),gs=["app_webhook","bearer","hmac_sha256","github_hmac","none"],xs=new Set(["app_webhook","bearer","github_hmac","fireflies_hmac","none"]);function ys(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}i(ys,"getLocalTimezone$1");function vs({trigger:s,onSave:a,onRotate:n,onDelete:c,disabled:r}){const[m,l]=(0,u.useState)({label:s.label??"",cronExpression:s.cronExpression??"",signingMode:s.signingMode??"bearer",replayWindowSec:String(s.replayWindowSec??300)});(0,u.useEffect)(()=>{l({label:s.label??"",cronExpression:s.cronExpression??"",signingMode:s.signingMode??"bearer",replayWindowSec:String(s.replayWindowSec??300)})},[s]);const k=s.kind==="schedule"?ve:s.kind==="webhook"?is:gt,I=s.kind==="schedule"?Bt(m.cronExpression):null,_=/fail|error/i.test(s.lastResult??""),C=s.lastResult?.startsWith("Created execution issue ")?"Task created":s.lastResult;return(0,e.jsxs)("form",{"aria-label":`Trigger: ${s.label??s.kind}`,className:"space-y-4 rounded-lg border border-border p-4",onSubmit:i(x=>x.preventDefault(),"onSubmit"),children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2 text-sm font-medium",children:[(0,e.jsx)(k,{className:"h-3.5 w-3.5 shrink-0"}),(0,e.jsx)("span",{className:"truncate",children:s.label??s.kind})]}),I?(0,e.jsx)("p",{id:`cron-readable-${s.id}`,className:"text-xs text-muted-foreground",children:I}):null]}),(0,e.jsxs)("div",{className:"flex shrink-0 items-center gap-2",children:[s.lastResult?(0,e.jsx)(ye,{variant:_?"destructive":"secondary",children:C}):null,(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:s.kind==="schedule"&&s.nextRunAt?`Next: ${new Date(s.nextRunAt).toLocaleString()}`:s.kind==="webhook"?"Webhook":"API"})]})]}),s.kind==="webhook"&&s.webhookUrl&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{htmlFor:`webhook-url-${s.id}`,className:"text-xs",children:"Webhook URL"}),(0,e.jsx)(V,{id:`webhook-url-${s.id}`,value:s.webhookUrl,readOnly:!0,onFocus:i(x=>x.target.select(),"onFocus")}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Send a POST request with Content-Type: application/json. Keep this URL private when signing is disabled."})]}),(0,e.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Label"}),(0,e.jsx)(V,{value:m.label,disabled:r,onChange:i(x=>l(S=>({...S,label:x.target.value})),"onChange")})]}),s.kind==="schedule"&&(0,e.jsxs)("div",{className:"space-y-1.5 md:col-span-2",children:[(0,e.jsx)(O,{className:"text-xs",children:"Schedule"}),(0,e.jsx)($e,{value:m.cronExpression,onChange:i(x=>l(S=>({...S,cronExpression:x})),"onChange")})]}),s.kind==="webhook"&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Signing mode"}),(0,e.jsxs)(pe,{value:m.signingMode,onValueChange:i(x=>l(S=>({...S,signingMode:x})),"onValueChange"),disabled:r,children:[(0,e.jsx)(ue,{children:(0,e.jsx)(me,{})}),(0,e.jsx)(he,{children:gs.map(x=>(0,e.jsx)(de,{value:x,children:x},x))})]})]}),!xs.has(m.signingMode)&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Replay window (seconds)"}),(0,e.jsx)(V,{value:m.replayWindowSec,disabled:r,onChange:i(x=>l(S=>({...S,replayWindowSec:x.target.value})),"onChange")})]})]})]}),!r&&(0,e.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[(0,e.jsxs)(E,{variant:"ghost",size:"sm",className:"mr-auto text-muted-foreground hover:text-destructive",onClick:i(()=>c(s.id),"onClick"),children:[(0,e.jsx)(Et,{className:"mr-1.5 h-3.5 w-3.5"}),"Delete"]}),s.kind==="webhook"&&(0,e.jsxs)(E,{variant:"outline",size:"sm",onClick:i(()=>n(s.id),"onClick"),children:[(0,e.jsx)(Tt,{className:"mr-1.5 h-3.5 w-3.5"}),"Rotate secret"]}),(0,e.jsxs)(E,{variant:"outline",size:"sm",onClick:i(()=>a(s.id,hs(s,m,ys())),"onClick"),children:[(0,e.jsx)(Ft,{className:"mr-1.5 h-3.5 w-3.5"}),"Save trigger"]})]})]})}i(vs,"RoutineTriggerCard");var fs=[{value:"coalesce_if_active",title:"Coalesce if active",description:"Keep one follow-up run queued while an active run is still working."},{value:"always_enqueue",title:"Always enqueue",description:"Queue every trigger occurrence, even if several runs stack up."},{value:"skip_if_active",title:"Skip if active",description:"Drop overlapping trigger occurrences while the routine is already active."}],bs=[{value:"skip_missed",title:"Skip missed",description:"Ignore schedule windows that were missed while paused."},{value:"enqueue_missed_with_cap",title:"Enqueue missed with cap",description:"Catch up missed schedule windows after recovery; sub-hourly schedules are combined into one catch-up run, slower schedules replay each missed window up to a cap."}],js=[{value:"always",title:"Run on every scheduled tick",description:"Fire on the schedule no matter what — the default behavior."},{value:"require_external_activity",title:"Skip when there's been no activity since the last run",description:"On a scheduled tick, only run if something happened since the last run that finished. Lets a watcher-style routine stay asleep while the system is settled instead of burning tokens."}],ws=[{value:"company",title:"Company-wide",description:"Any activity across the company counts as a reason to run."},{value:"project",title:"This project",description:"Only activity in the routine's project counts as a reason to run."}],Ns=["schedule","webhook"],ks=["app_webhook","bearer","hmac_sha256","github_hmac","none"],Ss={bearer:"Send Authorization: Bearer <secret> with each request.",hmac_sha256:"Send X-Paperclip-Timestamp and X-Paperclip-Signature: sha256=<hex>, signing timestamp + a dot + the exact JSON body.",github_hmac:"Accept GitHub-style X-Hub-Signature-256 header (HMAC over raw body, no timestamp).",app_webhook:"Accept a bearer token or an HMAC-SHA256 signature over the exact request body in X-Hub-Signature or X-Hub-Signature-256.",fireflies_hmac:"Signed webhook (legacy).",none:"No authentication — the webhook URL itself acts as a shared secret."},Is=new Set(["app_webhook","bearer","github_hmac","fireflies_hmac","none"]);function Cs({defaultDescriptionAnnotationsOpen:s=!1}={}){const{routine:a,editDraft:n,setEditDraft:c,assigneeOptions:r,projectOptions:m,recentAssigneeIds:l,recentProjectIds:k,agentById:I,projectById:_,currentAssignee:C,currentProject:x,mentionOptions:S,assigneeSelectorRef:D,projectSelectorRef:q,descriptionEditorRef:A,routineRuns:g,activity:b,saveRoutine:w,saveConflict:se,isSectionDirty:v,navigateToSection:P}=G(),[j,M]=(0,u.useState)(s),o=a.triggers.length,Q=(0,u.useMemo)(()=>{const d=a.triggers.filter(y=>y.kind==="schedule"&&y.nextRunAt).map(y=>new Date(y.nextRunAt)).sort((y,z)=>y.getTime()-z.getTime())[0];return d?d.toLocaleString():null},[a.triggers]),U=n.env?Object.keys(n.env).length:0,R=(g??[])[0]??null,B=(b??[]).slice(0,5);return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsx)("div",{className:"overflow-x-auto overscroll-x-contain",children:(0,e.jsxs)("div",{className:"inline-flex min-w-full flex-wrap items-center gap-2 text-sm text-muted-foreground sm:min-w-max sm:flex-nowrap",children:[(0,e.jsx)("span",{children:"For"}),(0,e.jsx)(Oe,{ref:D,value:n.assigneeAgentId,options:r,recentOptionIds:l,placeholder:"Responsible",noneLabel:"No responsible",searchPlaceholder:"Search responsible...",emptyMessage:"No responsible found.",onChange:i(d=>c(y=>({...y,assigneeAgentId:d})),"onChange"),onConfirm:i(()=>{n.projectId?A.current?.focus():q.current?.focus()},"onConfirm"),renderTriggerValue:i(d=>d?C?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(De,{agent:C,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),(0,e.jsx)("span",{className:"truncate",children:d.label})]}):(0,e.jsx)("span",{className:"truncate",children:d.label}):(0,e.jsx)("span",{className:"text-muted-foreground",children:"Responsible"}),"renderTriggerValue"),renderOption:i(d=>{if(!d.id)return(0,e.jsx)("span",{className:"truncate",children:d.label});const y=I.get(d.id);return(0,e.jsxs)(e.Fragment,{children:[y?(0,e.jsx)(De,{agent:y,size:16,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,(0,e.jsx)("span",{className:"truncate",children:d.label})]})},"renderOption")}),(0,e.jsx)("span",{children:"in"}),(0,e.jsx)(Oe,{ref:q,value:n.projectId,options:m,recentOptionIds:k,placeholder:"Project",noneLabel:"No project",searchPlaceholder:"Search projects...",emptyMessage:"No projects found.",onChange:i(d=>c(y=>({...y,projectId:d})),"onChange"),onConfirm:i(()=>A.current?.focus(),"onConfirm"),renderTriggerValue:i(d=>d&&x?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:x.color??"var(--project-none)"}}),(0,e.jsx)("span",{className:"truncate",children:d.label})]}):(0,e.jsx)("span",{className:"text-muted-foreground",children:"Project"}),"renderTriggerValue"),renderOption:i(d=>{if(!d.id)return(0,e.jsx)("span",{className:"truncate",children:d.label});const y=_.get(d.id);return(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"h-3.5 w-3.5 shrink-0 rounded-sm",style:{backgroundColor:y?.color??"var(--project-none)"}}),(0,e.jsx)("span",{className:"truncate",children:d.label})]})},"renderOption")})]})}),a.assigneeAgentId?null:(0,e.jsx)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-4 text-sm text-amber-900 dark:text-amber-200",children:"Default agent required. This routine can stay as a draft and still run manually, but automation stays paused until you assign a default agent."}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("div",{className:"flex items-center justify-end",children:a.descriptionDocument?(0,e.jsx)(Xt,{issueId:a.id,docKey:"description",target:{kind:"routine",routineId:a.id,documentKey:"description"},panelOpen:j,onToggle:i(()=>M(d=>!d),"onToggle")}):null}),a.descriptionDocument?(0,e.jsx)(es,{issueId:a.id,doc:a.descriptionDocument,target:{kind:"routine",routineId:a.id,documentKey:"description"},bodyMarkdown:n.description,draftDirty:v("overview")||w.isPending,draftConflicted:se,historicalPreview:!1,locationHash:typeof window>"u"?"":window.location.hash,panelOpen:j,onPanelOpenChange:M,children:(0,e.jsx)(Me,{ref:A,value:n.description,onChange:i(d=>c(y=>({...y,description:d})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-120px) text-sm leading-7",mentions:S,onSubmit:i(()=>{!w.isPending&&n.title.trim()&&w.mutate()},"onSubmit")})}):(0,e.jsx)(Me,{ref:A,value:n.description,onChange:i(d=>c(y=>({...y,description:d})),"onChange"),placeholder:"Add instructions...",bordered:!1,contentClassName:"min-h-(--sz-120px) text-sm leading-7",mentions:S,onSubmit:i(()=>{!w.isPending&&n.title.trim()&&w.mutate()},"onSubmit")})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(rs,{}),(0,e.jsx)(We,{title:n.title,description:n.description,value:n.variables,onChange:i(d=>c(y=>({...y,variables:d})),"onChange")})]}),(0,e.jsxs)("div",{className:"grid gap-3 sm:grid-cols-3",children:[(0,e.jsx)(ce,{icon:ve,label:"Triggers",value:o===0?"None":`${o} active`,hint:Q?`Next fire ${Q}`:"No schedule",to:i(()=>P("triggers"),"to"),ariaLabel:`${o} triggers. Open triggers.`}),(0,e.jsx)(ce,{icon:Mt,label:"Secrets",value:U===0?"None":`${U} bound`,hint:"Manage bound secrets",to:i(()=>P("secrets"),"to"),ariaLabel:`${U} secrets bound. Open secrets.`}),(0,e.jsx)(ce,{icon:wt,label:"Last run",value:R?R.status.replaceAll("_"," "):"No runs",hint:R?Ee(R.triggeredAt):"Trigger a run",to:i(()=>P("runs"),"to"),ariaLabel:R?`Last run ${R.status}. Open runs.`:"No runs. Open runs."})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Recent activity"}),B.length===0?(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"No activity yet."}):(0,e.jsxs)("div",{className:"divide-y divide-border/60",children:[B.map(d=>(0,e.jsxs)("div",{className:"flex items-center gap-2 py-1.5 text-xs",children:[(0,e.jsx)(ye,{variant:"outline",className:"shrink-0 font-mono",children:d.action}),(0,e.jsx)("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:d.details&&Object.keys(d.details).length>0?Object.keys(d.details).slice(0,3).join(" · "):""}),(0,e.jsx)("span",{className:"shrink-0 text-muted-foreground/60",children:Ee(d.createdAt)})]},d.id)),(0,e.jsxs)("button",{type:"button",onClick:i(()=>P("activity"),"onClick"),className:"flex items-center gap-1 pt-2 text-xs text-muted-foreground hover:text-foreground",children:["View all activity ",(0,e.jsx)(xe,{className:"h-3 w-3"})]})]})]})]})}i(Cs,"OverviewSection");function ce({icon:s,label:a,value:n,hint:c,to:r,ariaLabel:m}){return(0,e.jsx)("button",{type:"button",onClick:r,"aria-label":m,className:"text-left",children:(0,e.jsx)($t,{className:"gap-2 p-4 transition-colors hover:border-border hover:bg-accent/30",children:(0,e.jsxs)(Ut,{className:"space-y-1 p-0",children:[(0,e.jsxs)("div",{className:"flex items-center gap-1.5 text-xs uppercase tracking-wide text-muted-foreground",children:[(0,e.jsx)(s,{className:"h-3.5 w-3.5"}),a,(0,e.jsx)(xe,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground/60"})]}),(0,e.jsx)("p",{className:"text-lg font-semibold",children:n}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:c})]})})})}i(ce,"SummaryCard");function As(){const{routine:s,newTrigger:a,setNewTrigger:n,createTrigger:c,updateTrigger:r,deleteTrigger:m,rotateTrigger:l,secretMessage:k,copySecretValue:I,setSecretMessage:_}=G(),[C,x]=(0,u.useState)(!1),[S,D]=(0,u.useState)(!0),q=(0,u.useMemo)(()=>a.kind==="schedule"?as(a.cronExpression):null,[a.cronExpression,a.kind]),A=c.isPending||(q?!q.valid||!S:!1);return(0,u.useEffect)(()=>{a.kind!=="schedule"&&D(!0)},[a.kind]),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsx)("p",{className:"text-sm font-medium text-muted-foreground",children:s.triggers.length===0?"No triggers yet":`${s.triggers.length} trigger${s.triggers.length===1?"":"s"}`}),(0,e.jsx)(E,{size:"sm",variant:C?"secondary":"default",onClick:i(()=>x(g=>!g),"onClick"),"aria-expanded":C,children:C?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(Rt,{className:"mr-1.5 h-3.5 w-3.5"}),"Cancel"]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(xt,{className:"mr-1.5 h-3.5 w-3.5"}),"New trigger"]})})]}),C?(0,e.jsxs)("div",{className:"space-y-3 rounded-lg border border-border p-4",children:[(0,e.jsx)("p",{className:"text-sm font-medium",children:"Add trigger"}),(0,e.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Kind"}),(0,e.jsxs)(pe,{value:a.kind,onValueChange:i(g=>n(b=>({...b,kind:g})),"onValueChange"),children:[(0,e.jsx)(ue,{children:(0,e.jsx)(me,{})}),(0,e.jsx)(he,{children:Ns.map(g=>(0,e.jsx)(de,{value:g,children:g},g))})]})]}),a.kind==="schedule"&&(0,e.jsxs)("div",{className:"space-y-1.5 md:col-span-2",children:[(0,e.jsx)(O,{className:"text-xs",children:"Schedule"}),(0,e.jsx)($e,{value:a.cronExpression,onChange:i(g=>n(b=>({...b,cronExpression:g})),"onChange"),onValidityChange:D})]}),a.kind==="webhook"&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Signing mode"}),(0,e.jsxs)(pe,{value:a.signingMode,onValueChange:i(g=>n(b=>({...b,signingMode:g})),"onValueChange"),children:[(0,e.jsx)(ue,{children:(0,e.jsx)(me,{})}),(0,e.jsx)(he,{children:ks.map(g=>(0,e.jsx)(de,{value:g,children:g},g))})]}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:Ss[a.signingMode]})]}),!Is.has(a.signingMode)&&(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsx)(O,{className:"text-xs",children:"Replay window (seconds)"}),(0,e.jsx)(V,{value:a.replayWindowSec,onChange:i(g=>n(b=>({...b,replayWindowSec:g.target.value})),"onChange")})]})]})]}),(0,e.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[(0,e.jsx)(E,{size:"sm",variant:"ghost",onClick:i(()=>x(!1),"onClick"),children:"Cancel"}),(0,e.jsx)(E,{size:"sm",onClick:i(()=>c.mutate(void 0,{onSuccess:i(()=>{n(Ue()),x(!1)},"onSuccess")}),"onClick"),disabled:A,children:c.isPending?"Adding...":"Add trigger"})]})]}):null,k?(0,e.jsxs)("div",{className:"space-y-3 rounded-lg border border-border bg-muted/20 p-4 text-sm",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"font-medium",children:k.title}),(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Save this now. Paperclip will not show the secret value again."})]}),(0,e.jsx)("div",{className:"space-y-3",children:k.entries.map((g,b)=>(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(V,{"aria-label":"New webhook URL",value:g.webhookUrl,readOnly:!0,className:"flex-1"}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>I("Webhook URL",g.webhookUrl),"onClick"),children:"URL"})]}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(V,{"aria-label":"New webhook secret",value:g.webhookSecret,readOnly:!0,className:"flex-1"}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>I("Webhook secret",g.webhookSecret),"onClick"),children:"Secret"})]})]},`${g.webhookUrl}-${b}`))}),(0,e.jsx)(E,{variant:"outline",size:"sm",onClick:i(()=>_(null),"onClick"),children:"Done"})]}):null,s.triggers.length===0?(0,e.jsx)(te,{icon:ve,message:"No triggers yet.",action:"Add a trigger",onAction:i(()=>x(!0),"onAction")}):(0,e.jsx)("div",{className:"space-y-3",children:s.triggers.map(g=>(0,e.jsx)(vs,{trigger:g,onSave:i((b,w)=>r.mutate({id:b,patch:w}),"onSave"),onRotate:i(b=>l.mutate(b),"onRotate"),onDelete:i(b=>m.mutate(b),"onDelete")},g.id))})]})}i(As,"TriggersSection");function Ps(){const{editDraft:s,setEditDraft:a,navigateToSection:n}=G(),c=s.variables.length>0;return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"flex items-center gap-3 rounded-md border border-border bg-muted/20 px-4 py-3 text-xs",children:[(0,e.jsxs)("span",{className:"flex-1 text-muted-foreground",children:["Variables are auto-detected from ",(0,e.jsx)("code",{className:"font-mono",children:"{{placeholders}}"})," in the title & instructions. The variable name is read-only — rename by editing the placeholder."]}),(0,e.jsxs)(E,{variant:"secondary",size:"sm",onClick:i(()=>n("overview"),"onClick"),children:[(0,e.jsx)(us,{className:"mr-1.5 h-3.5 w-3.5"}),"Edit instructions"]})]}),c?(0,e.jsx)(We,{title:s.title,description:s.description,value:s.variables,onChange:i(r=>a(m=>({...m,variables:r})),"onChange")}):(0,e.jsx)(te,{icon:cs,message:"No variables yet. Add a {{placeholder}} in the title or instructions to create one.",action:"Edit instructions",onAction:i(()=>n("overview"),"onAction")})]})}i(Ps,"VariablesSection");function Rs(){const{editDraft:s,setEditDraft:a,availableSecrets:n,createSecret:c}=G(),r=(0,u.useMemo)(()=>[...n].filter(m=>m.status==="active").sort((m,l)=>{const k=(l.referenceCount??0)-(m.referenceCount??0);return k!==0?k:new Date(l.updatedAt).getTime()-new Date(m.updatedAt).getTime()}).slice(0,8),[n]);return(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{className:"rounded-md border border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground",children:["Routine secrets apply to every task this routine creates. They override matching keys in project and agent env. ",(0,e.jsx)("span",{className:"font-mono",children:"PAPERCLIP_*"})," names are reserved."]}),(0,e.jsx)(Jt,{value:s.env??{},secrets:n,recentlyUsedSecrets:r,onCreateSecret:i(async(m,l)=>c.mutateAsync({name:m,value:l}),"onCreateSecret"),onChange:i(m=>a(l=>({...l,env:m??null})),"onChange")})]})}i(Rs,"SecretsSection");function Ts(){const{editDraft:s,setEditDraft:a,routine:n}=G(),c=n.triggers.some(m=>m.kind==="schedule"),r=s.activityGatePolicy==="require_external_activity";return(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Concurrency"}),(0,e.jsx)(Y,{ariaLabel:"Concurrency policy",value:s.concurrencyPolicy,onValueChange:i(m=>a(l=>({...l,concurrencyPolicy:m})),"onValueChange"),options:fs})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Catch-up"}),(0,e.jsx)(Y,{ariaLabel:"Catch-up policy",value:s.catchUpPolicy,onValueChange:i(m=>a(l=>({...l,catchUpPolicy:m})),"onValueChange"),options:bs})]}),(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Advanced run policy"}),(0,e.jsx)(Y,{ariaLabel:"Advanced run policy",value:s.activityGatePolicy,onValueChange:i(m=>a(l=>({...l,activityGatePolicy:m})),"onValueChange"),options:js,disabled:!c}),c?r?(0,e.jsxs)("div",{className:"space-y-2 rounded-lg border border-border p-3",children:[(0,e.jsx)(O,{className:"text-xs font-medium",children:"Activity scope"}),(0,e.jsx)(Y,{ariaLabel:"Activity gate scope",value:s.activityGateScope,onValueChange:i(m=>a(l=>({...l,activityGateScope:m})),"onValueChange"),options:ws})]}):null:(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:"Add a schedule trigger to gate runs on activity. Webhook, manual, and API fires always run."})]}),(0,e.jsx)(Os,{triggers:n.triggers,concurrencyPolicy:s.concurrencyPolicy})]})}i(Ts,"DeliverySection");var Es={queued:"text-emerald-600 dark:text-emerald-400",coalesced:"text-amber-600 dark:text-amber-400",skipped:"text-muted-foreground"};function Os({triggers:s,concurrencyPolicy:a}){const n=(0,u.useMemo)(()=>{const c=s.filter(r=>r.kind==="schedule"&&r.enabled&&r.cronExpression).map(r=>({trigger:r,fires:Qt(r.cronExpression,5,{timeZone:r.timezone??"UTC"})})).filter(r=>r.fires.length>0).sort((r,m)=>r.fires[0].getTime()-m.fires[0].getTime())[0];return c?{timeZone:c.trigger.timezone??"UTC",entries:ts(c.fires,a)}:null},[s,a]);return(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs font-medium uppercase tracking-(--tracking-caps) text-muted-foreground",children:"Next 5 fires"}),n?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"space-y-1.5 rounded-lg border border-border p-3 font-mono text-xs",children:n.entries.map((c,r)=>(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("span",{className:"text-muted-foreground/40",children:"·"}),(0,e.jsx)("span",{className:"tabular-nums",children:Ds(c.at,n.timeZone)}),(0,e.jsx)(xe,{className:"h-3 w-3 shrink-0 text-muted-foreground/50"}),(0,e.jsx)("span",{className:ct("font-medium",Es[c.disposition]),children:c.label}),c.note?(0,e.jsxs)("span",{className:"truncate text-muted-foreground/60",children:["(",c.note,")"]}):null]},r))}),(0,e.jsxs)("p",{className:"text-(length:--text-micro) text-muted-foreground/60",children:["Preview assumes the previous run is still in flight when the next fires. Times shown in"," ",n.timeZone,"."]})]}):(0,e.jsx)("p",{className:"rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground",children:"No enabled schedule trigger to preview. Add a schedule in Triggers to see how this policy treats upcoming fires."})]})}i(Os,"NextFiresPreview");function Ds(s,a){try{return new Intl.DateTimeFormat(void 0,{timeZone:a,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(s).replace(",","")}catch{return s.toISOString()}}i(Ds,"formatFireTime");var ge="paperclip.routineLastSection";function Ms(s){return s.filter(a=>!a.archivedAt).map(a=>({id:a.id,label:a.name,searchText:a.description??""}))}i(Ms,"buildRoutineProjectOptions");var _s={overview:"Overview",triggers:"Triggers",variables:"Variables",secrets:"Secrets",delivery:"Delivery",runs:"Runs",activity:"Activity",history:"History"};function ee(s){return s!=null&&ss.includes(s)}i(ee,"isRoutineSection");function qs(s){try{const a=localStorage.getItem(ge);if(!a)return null;const n=JSON.parse(a)[s];return ee(n)?n:null}catch{return null}}i(qs,"readLastSection");function le(s,a){try{const n=localStorage.getItem(ge),c=n?JSON.parse(n):{};c[s]=a,localStorage.setItem(ge,JSON.stringify(c))}catch{}}i(le,"writeLastSection");var Fe={triggers:"triggers",runs:"runs",activity:"activity",secrets:"secrets",history:"history"};function Ke(s){s&&(s.style.height="auto",s.style.height=`${s.scrollHeight}px`)}i(Ke,"autoResizeTextarea");function Fs(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}i(Fs,"getLocalTimezone");function Ks(s){return{...s,description:s.description.trim()||null,projectId:s.projectId||null,assigneeAgentId:s.assigneeAgentId||null,env:s.env&&Object.keys(s.env).length>0?s.env:null}}i(Ks,"buildRoutineMutationPayload");function di(){const{routineId:s,section:a}=ht(),{selectedCompanyId:n}=mt(),{setBreadcrumbs:c}=vt(),r=lt(),m=yt(),{pushToast:l}=Dt(),k=(0,u.useRef)(null),I=(0,u.useRef)(null),_=(0,u.useRef)(null),C=(0,u.useRef)(null),x=(0,u.useRef)(null),[S,D]=(0,u.useState)(null),[q,A]=(0,u.useState)(!1),[g,b]=(0,u.useState)(!1),[w,se]=(0,u.useState)(Ue),[v,P]=(0,u.useState)({title:"",description:"",projectId:"",assigneeAgentId:"",priority:"medium",concurrencyPolicy:"coalesce_if_active",catchUpPolicy:"skip_missed",activityGatePolicy:"always",activityGateScope:"company",variables:[],env:null}),j=ee(a)?a:"overview",M=(0,u.useCallback)((t,h)=>{s&&(le(s,t),m(`/routines/${s}/${t}`,{replace:h?.replace??!0}))},[m,s]),{data:o,isLoading:Q,error:U}=L({queryKey:p.routines.detail(s),queryFn:i(()=>T.get(s),"queryFn"),enabled:!!s}),R=o?.activeIssue?.id,{data:B}=L({queryKey:p.issues.liveRuns(R),queryFn:i(()=>Kt.liveRunsForIssue(R),"queryFn"),enabled:!!R,refetchInterval:3e3}),d=(B??[]).length>0,{data:y}=L({queryKey:p.routines.runs(s),queryFn:i(()=>T.listRuns(s),"queryFn"),enabled:!!s,refetchInterval:d?3e3:!1}),z=(0,u.useMemo)(()=>({triggerIds:o?.triggers.map(t=>t.id)??[],runIds:y?.map(t=>t.id)??[]}),[o?.triggers,y]),{data:Ve}=L({queryKey:[...p.routines.activity(n,s),z.triggerIds.join(","),z.runIds.join(",")],queryFn:i(()=>T.activity(n,s,z),"queryFn"),enabled:!!n&&!!s&&!!o}),{data:F}=L({queryKey:p.agents.list(n),queryFn:i(()=>bt.list(n),"queryFn"),enabled:!!n}),{data:K}=L({queryKey:p.projects.list(n,{includeArchived:!0}),queryFn:i(()=>Ot.list(n,{includeArchived:!0}),"queryFn"),enabled:!!n}),{data:fe}=L({queryKey:p.access.companyUserDirectory(n),queryFn:i(()=>Wt.listUserDirectory(n),"queryFn"),enabled:!!n}),{data:ze=[]}=L({queryKey:n?p.secrets.list(n):["secrets","none"],queryFn:i(()=>_e.list(n),"queryFn"),enabled:!!n}),Ge=W({mutationFn:i(t=>{if(!n)throw new Error("Select a company to create secrets");return _e.create(n,t)},"mutationFn"),onSuccess:i(()=>{n&&r.invalidateQueries({queryKey:p.secrets.list(n)})},"onSuccess")}),f=(0,u.useMemo)(()=>o?{title:o.title,description:o.description??"",projectId:o.projectId??"",assigneeAgentId:o.assigneeAgentId??"",priority:o.priority,concurrencyPolicy:o.concurrencyPolicy,catchUpPolicy:o.catchUpPolicy,activityGatePolicy:o.activityGatePolicy,activityGateScope:o.activityGateScope,variables:o.variables,env:o.env??null}:null,[o]),H=(0,u.useMemo)(()=>{if(!f)return[];const t=[];return v.title!==f.title&&t.push({key:"title",label:"the title"}),v.description!==f.description&&t.push({key:"description",label:"the description"}),v.projectId!==f.projectId&&t.push({key:"projectId",label:"the project"}),v.assigneeAgentId!==f.assigneeAgentId&&t.push({key:"assigneeAgentId",label:"the default agent"}),v.priority!==f.priority&&t.push({key:"priority",label:"the priority"}),v.concurrencyPolicy!==f.concurrencyPolicy&&t.push({key:"concurrencyPolicy",label:"the concurrency policy"}),v.catchUpPolicy!==f.catchUpPolicy&&t.push({key:"catchUpPolicy",label:"the catch-up policy"}),v.activityGatePolicy!==f.activityGatePolicy&&t.push({key:"activityGatePolicy",label:"the advanced run policy"}),v.activityGateScope!==f.activityGateScope&&t.push({key:"activityGateScope",label:"the activity gate scope"}),JSON.stringify(v.variables)!==JSON.stringify(f.variables)&&t.push({key:"variables",label:"the variables"}),JSON.stringify(v.env??null)!==JSON.stringify(f.env??null)&&t.push({key:"env",label:"the secrets"}),t},[v,f]),ie=H.length>0,J=(0,u.useCallback)(t=>{const h=qe[t];return h?H.filter(N=>h.includes(N.key)):[]},[H]),ne=(0,u.useCallback)(t=>J(t).length>0,[J]),be=(0,u.useCallback)(t=>{if(!f)return;const h=qe[t];h&&P(N=>{const Re={...N};for(const Te of h)Re[Te]=f[Te];return Re})},[f]);(0,u.useEffect)(()=>{o&&(c([{label:"Routines",href:"/routines"},{label:o.title}]),f&&(k.current!==o.id||!ie)&&(P(f),k.current=o.id))},[o,f,ie,c]),(0,u.useEffect)(()=>{Ke(I.current)},[v.title,o?.id]),(0,u.useEffect)(()=>{s&&ee(a)&&le(s,a)},[s,a]);const Qe=(0,u.useCallback)(async(t,h)=>{try{await _t(h),l({title:`${t} copied`,tone:"success"})}catch(N){l({title:`Failed to copy ${t.toLowerCase()}`,body:N instanceof Error?N.message:"Clipboard access was denied.",tone:"error"})}},[l]),Z=W({mutationFn:i(()=>{const t=Ks(v),h=o?.latestRevisionId??null;return T.update(s,{...t,...h?{baseRevisionId:h}:{}})},"mutationFn"),onSuccess:i(async()=>{A(!1),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)}),r.invalidateQueries({queryKey:p.routines.revisions(s)})])},"onSuccess"),onError:i(t=>{if(t instanceof ut&&t.status===409){A(!0),l({title:"Routine changed",body:"Someone else updated this routine. Reload to see the latest revision.",tone:"warn"});return}l({title:"Failed to save routine",body:t instanceof Error?t.message:"Paperclip could not save the routine.",tone:"error"})},"onError")}),X=W({mutationFn:i(t=>T.run(s,{...t?.variables&&Object.keys(t.variables).length>0?{variables:t.variables}:{},...t?.assigneeAgentId!==void 0?{assigneeAgentId:t.assigneeAgentId}:{},...t?.projectId!==void 0?{projectId:t.projectId}:{},...t?.executionWorkspaceId!==void 0?{executionWorkspaceId:t.executionWorkspaceId}:{},...t?.executionWorkspacePreference!==void 0?{executionWorkspacePreference:t.executionWorkspacePreference}:{},...t?.executionWorkspaceSettings!==void 0?{executionWorkspaceSettings:t.executionWorkspaceSettings}:{}}),"mutationFn"),onSuccess:i(async()=>{l({title:"Routine run started",tone:"success"}),b(!1),M("runs"),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.runs(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Routine run failed",body:t instanceof Error?t.message:"Paperclip could not start the routine run.",tone:"error"})},"onError")}),je=W({mutationFn:i(t=>T.update(s,{status:t}),"mutationFn"),onSuccess:i(async(t,h)=>{l({title:"Routine saved",body:h==="paused"?"Automation paused.":"Automation enabled.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to update routine",body:t instanceof Error?t.message:"Paperclip could not update the routine.",tone:"error"})},"onError")}),Be=W({mutationFn:i(async()=>{const t=(o?.triggers??[]).filter(N=>N.kind===w.kind).length,h=t>0?`${w.kind}-${t+1}`:w.kind;return T.createTrigger(s,{kind:w.kind,label:h,...w.kind==="schedule"?{cronExpression:w.cronExpression.trim(),timezone:Fs()}:{},...w.kind==="webhook"?{signingMode:w.signingMode,replayWindowSec:Number(w.replayWindowSec||"300")}:{}})},"mutationFn"),onSuccess:i(async t=>{t.secretMaterial?D({title:"Webhook trigger created",entries:[{webhookUrl:t.secretMaterial.webhookUrl,webhookSecret:t.secretMaterial.webhookSecret}]}):l({title:"Trigger added",body:"The routine schedule was saved.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to add trigger",body:t instanceof Error?t.message:"Paperclip could not create the trigger.",tone:"error"})},"onError")}),He=W({mutationFn:i(({id:t,patch:h})=>T.updateTrigger(t,h),"mutationFn"),onSuccess:i(async()=>{l({title:"Trigger saved",body:"The routine cadence update was saved.",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to update trigger",body:t instanceof Error?t.message:"Paperclip could not update the trigger.",tone:"error"})},"onError")}),Je=W({mutationFn:i(t=>T.deleteTrigger(t),"mutationFn"),onSuccess:i(async()=>{l({title:"Trigger deleted",tone:"success"}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.list(n)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to delete trigger",body:t instanceof Error?t.message:"Paperclip could not delete the trigger.",tone:"error"})},"onError")}),Ze=W({mutationFn:i(t=>T.rotateTriggerSecret(t),"mutationFn"),onSuccess:i(async t=>{D({title:"Webhook secret rotated",entries:[{webhookUrl:t.secretMaterial.webhookUrl,webhookSecret:t.secretMaterial.webhookSecret}]}),await Promise.all([r.invalidateQueries({queryKey:p.routines.detail(s)}),r.invalidateQueries({queryKey:p.routines.activity(n,s)})])},"onSuccess"),onError:i(t=>{l({title:"Failed to rotate webhook secret",body:t instanceof Error?t.message:"Paperclip could not rotate the webhook secret.",tone:"error"})},"onError")}),we=(0,u.useMemo)(()=>new Map((F??[]).map(t=>[t.id,t])),[F]),Ne=(0,u.useMemo)(()=>new Map((K??[]).map(t=>[t.id,t])),[K]),ae=(0,u.useMemo)(()=>It(),[o?.id]),Xe=(0,u.useMemo)(()=>Nt(),[o?.id]),Ye=(0,u.useMemo)(()=>Ct((F??[]).filter(t=>t.status!=="terminated"),ae).map(t=>({id:t.id,label:t.name,searchText:`${t.name} ${t.role} ${t.title??""}`})),[F,ae]),et=(0,u.useMemo)(()=>Ms(K??[]),[K]),tt=(0,u.useMemo)(()=>Lt({agents:F,projects:(K??[]).filter(t=>!t.archivedAt),members:fe?.users}),[F,fe?.users,K]),st=(0,u.useCallback)(t=>{P(h=>{const N=typeof t=="function"?t(h):t;return N.assigneeAgentId&&N.assigneeAgentId!==h.assigneeAgentId&&kt(N.assigneeAgentId),N.projectId&&N.projectId!==h.projectId&&At(N.projectId),N})},[]),it=v.assigneeAgentId?we.get(v.assigneeAgentId)??null:null,nt=v.projectId?Ne.get(v.projectId)??null:null,ke=(0,u.useCallback)(()=>{A(!1),f&&P(f),r.invalidateQueries({queryKey:p.routines.detail(s)})},[r,f,s]),at=(0,u.useCallback)(t=>{t.secretMaterials.length>0&&(M("triggers"),D({title:t.secretMaterials.length===1?"Webhook trigger restored":`${t.secretMaterials.length} webhook triggers restored`,entries:t.secretMaterials.map(h=>({webhookUrl:h.webhookUrl,webhookSecret:h.webhookSecret}))}))},[M]),rt=(0,u.useCallback)(t=>{A(!1),r.setQueryData(p.routines.detail(s),h=>h&&{...h,...t.routine,latestRevisionId:t.revision.id,latestRevisionNumber:t.revision.revisionNumber}),P({title:t.routine.title,description:t.routine.description??"",projectId:t.routine.projectId??"",assigneeAgentId:t.routine.assigneeAgentId??"",priority:t.routine.priority,concurrencyPolicy:t.routine.concurrencyPolicy,catchUpPolicy:t.routine.catchUpPolicy,activityGatePolicy:t.routine.activityGatePolicy,activityGateScope:t.routine.activityGateScope,variables:t.routine.variables,env:t.routine.env??null}),k.current=t.routine.id},[r,s]);if(!n)return(0,e.jsx)(te,{icon:St,message:"Select a company to view routines."});const re=new URLSearchParams(window.location.search).get("tab");if(s&&re&&Fe[re])return(0,e.jsx)(oe,{to:`/routines/${s}/${Fe[re]}`,replace:!0});if(s&&!a){const t=qs(s)??"overview";return(0,e.jsx)(oe,{to:`/routines/${s}/${t}`,replace:!0})}if(s&&a&&!ee(a))return(0,e.jsx)(oe,{to:`/routines/${s}/overview`,replace:!0});if(Q)return(0,e.jsx)(Vt,{variant:"issues-list"});if(U||!o||!f)return(0,e.jsx)(te,{icon:qt,message:U instanceof Error?U.message:"We couldn't load this routine."});const $=o.status==="active",Se=je.isPending||o.status==="archived",Ie=o.status==="archived"?"Archived":o.assigneeAgentId?$?"Active":"Paused":"Draft",Ce=o.status==="archived"?"text-muted-foreground":$?"text-emerald-400":"text-muted-foreground",Ae={routine:o,routineId:s,companyId:o.companyId,editDraft:v,setEditDraft:st,routineDefaults:f,dirtyFields:H,isEditDirty:ie,sectionDirtyFields:J,isSectionDirty:ne,discardSection:be,saveRoutine:Z,saveConflict:q,reloadLatest:ke,automationEnabled:$,automationLabel:Ie,automationLabelClassName:Ce,automationToggleDisabled:Se,onToggleAutomation:i(()=>{if(!$&&!o.assigneeAgentId){l({title:"Default agent required",body:"Set a default agent before enabling routine automation.",tone:"warn"});return}je.mutate($?"paused":"active")},"onToggleAutomation"),onOpenRunDialog:i(()=>b(!0),"onOpenRunDialog"),runRoutinePending:X.isPending,newTrigger:w,setNewTrigger:se,createTrigger:Be,updateTrigger:He,deleteTrigger:Je,rotateTrigger:Ze,secretMessage:S,setSecretMessage:D,copySecretValue:Qe,availableSecrets:ze,createSecret:Ge,agents:F??[],projects:K??[],agentById:we,projectById:Ne,assigneeOptions:Ye,projectOptions:et,recentAssigneeIds:ae,recentProjectIds:Xe,mentionOptions:tt,currentAssignee:it,currentProject:nt,routineRuns:y,activity:Ve,hasLiveRun:d,activeIssueId:R,titleInputRef:I,descriptionEditorRef:_,assigneeSelectorRef:C,projectSelectorRef:x,onHistoryRestoreSecretMaterials:at,onHistoryRestored:rt,navigateToSection:M},Pe=Yt.includes(j);return(0,e.jsxs)(Ht.Provider,{value:Ae,children:[(0,e.jsx)("a",{href:"#routine-section",className:"sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-20 focus:rounded focus:bg-background focus:px-3 focus:py-1.5 focus:text-sm",children:"Skip to section"}),(0,e.jsxs)("div",{className:"-m-4 flex h-full min-h-0 flex-col overflow-hidden md:-m-6",children:[(0,e.jsxs)("header",{className:"flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-6",children:[(0,e.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[(0,e.jsx)("textarea",{ref:I,"data-autosize-title":!0,className:"min-w-0 flex-1 resize-none overflow-hidden bg-transparent text-base font-semibold leading-7 outline-none placeholder:text-muted-foreground/50",placeholder:"Routine title",rows:1,value:v.title,onChange:i(t=>{P(h=>({...h,title:t.target.value})),Ke(t.target)},"onChange"),onKeyDown:i(t=>{t.key==="Enter"&&!t.metaKey&&!t.ctrlKey&&!t.nativeEvent.isComposing&&(t.preventDefault(),j==="overview"?_.current?.focus():M("overview"))},"onKeyDown")}),o.managedByPlugin?(0,e.jsxs)(ye,{variant:"outline",className:"hidden shrink-0 gap-1.5 text-xs text-muted-foreground sm:inline-flex",children:[(0,e.jsx)(ft,{className:"h-3 w-3"}),o.managedByPlugin.pluginDisplayName,(0,e.jsx)("span",{className:"font-mono text-(length:--text-nano)",children:o.managedByPlugin.resourceKey})]}):null]}),(0,e.jsxs)("div",{className:"ml-auto flex shrink-0 items-center gap-3",children:[(0,e.jsx)(os,{onClick:i(()=>b(!0),"onClick"),disabled:X.isPending}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(jt,{size:"default",checked:$,onCheckedChange:Ae.onToggleAutomation,disabled:Se,"aria-label":$?"Pause automatic triggers":"Enable automatic triggers"}),(0,e.jsx)("span",{className:`text-sm font-medium ${Ce}`,children:Ie})]})]})]}),(0,e.jsx)(zt,{activeSection:j,onNavigate:M,isSectionDirty:ne}),(0,e.jsxs)("div",{className:"flex min-h-0 flex-1",children:[(0,e.jsx)(ls,{activeSection:j,hrefFor:i(t=>`/routines/${s}/${t}`,"hrefFor"),isSectionDirty:ne,hasLiveRun:d,onNavigate:i(t=>le(s,t),"onNavigate")}),(0,e.jsx)("main",{id:"routine-section",role:"main",className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 pb-6 pt-10 md:px-8",children:(0,e.jsxs)("section",{"aria-labelledby":"routine-section-title",className:Pe?"mx-auto w-full max-w-3xl":"w-full",children:[(0,e.jsx)(Zt,{title:_s[j],copyText:j==="overview"?ps({editing:!0,draft:v.description,saved:o.description}):null}),j==="overview"&&(0,e.jsx)(Cs,{}),j==="triggers"&&(0,e.jsx)(As,{}),j==="variables"&&(0,e.jsx)(Ps,{}),j==="secrets"&&(0,e.jsx)(Rs,{}),j==="delivery"&&(0,e.jsx)(Ts,{}),j==="runs"&&(0,e.jsx)(Gt,{}),j==="activity"&&(0,e.jsx)(ms,{}),j==="history"&&(0,e.jsx)(ns,{}),Pe?(0,e.jsx)(ds,{dirtyFields:J(j),isSaving:Z.isPending,saveConflict:q,onSave:i(()=>{!Z.isPending&&v.title.trim()&&Z.mutate()},"onSave"),onDiscard:i(()=>be(j),"onDiscard"),onReload:ke}):null]})})]})]}),(0,e.jsx)(Pt,{open:g,onOpenChange:b,companyId:o.companyId,routineName:o.title,agents:F??[],projects:K??[],defaultProjectId:o.projectId,defaultAssigneeAgentId:o.assigneeAgentId,variables:o.variables??[],isPending:X.isPending,onSubmit:i(t=>X.mutate(t),"onSubmit")})]})}i(di,"RoutineDetail");export{di as RoutineDetail};