@tickernelz/wardmote-ui 2026.1115.2 → 2026.1115.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AdapterManager-DlCyzyMu.js → AdapterManager-DD2p5mWg.js} +1 -1
- package/dist/assets/{AdvancedToolsRoute-4n8ZC6o0.js → AdvancedToolsRoute-DlPZ_L6N.js} +1 -1
- package/dist/assets/{AgentActionButtons-LV4FbrTY.js → AgentActionButtons-sm-e5f06.js} +1 -1
- package/dist/assets/{AgentChat-CXR66MM4.js → AgentChat-b78UeZDu.js} +1 -1
- package/dist/assets/{AgentChats-C4cEfRO_.js → AgentChats-XK32PfX0.js} +1 -1
- package/dist/assets/{AgentDefaults-BZwFysUw.js → AgentDefaults-BZlzjR_2.js} +1 -1
- package/dist/assets/{AgentDetail-DPCbH362.js → AgentDetail-DwlY6mx-.js} +1 -1
- package/dist/assets/{AgentTodoCard-82Za1R6Y.js → AgentTodoCard-C6-lHXns.js} +1 -1
- package/dist/assets/{Agents-BotjqSPg.js → Agents-C1-WHkTj.js} +3 -3
- package/dist/assets/{AppDetail-B5T_4Bu-.js → AppDetail-9cue4nY2.js} +1 -1
- package/dist/assets/{AppNotConnected-eBGlritA.js → AppNotConnected-oZ4OtRZ5.js} +1 -1
- package/dist/assets/{ApprovalCard-CyXVBGnO.js → ApprovalCard-B1Fs4K4S.js} +1 -1
- package/dist/assets/{ApprovalDetail-BSNBUdim.js → ApprovalDetail-BchdkauI.js} +1 -1
- package/dist/assets/{ApprovalPayload-vezR61PH.js → ApprovalPayload-HdMQnZAw.js} +1 -1
- package/dist/assets/{Approvals-YzDki85i.js → Approvals-ecXixAXF.js} +1 -1
- package/dist/assets/{AppsReview-D02Q501S.js → AppsReview-DSeqYXkI.js} +1 -1
- package/dist/assets/{ArtifactCard-CC5aIvtf.js → ArtifactCard-B9GVJfR3.js} +1 -1
- package/dist/assets/{Artifacts-CnP5QapS.js → Artifacts-Cfi9iGlP.js} +1 -1
- package/dist/assets/{AssistantConnection-refIKgUa.js → AssistantConnection-D1H83dKT.js} +1 -1
- package/dist/assets/{AttentionInteractionResolver-_l8MisRg.js → AttentionInteractionResolver-K_Jeu6_2.js} +1 -1
- package/dist/assets/{AuditHub-CKyN1yDa.js → AuditHub-DlVx-mPL.js} +1 -1
- package/dist/assets/{BoardChat-Dn5D5hbo.js → BoardChat-BWW2praB.js} +1 -1
- package/dist/assets/{BootstrapSetupUxLab-CDn9Qoy4.js → BootstrapSetupUxLab-C4zke6Cv.js} +1 -1
- package/dist/assets/{Browse-BQApRQGO.js → Browse-DLwvtbXu.js} +1 -1
- package/dist/assets/{BudgetPolicyCard-BAwZpX0_.js → BudgetPolicyCard-B6DX8U3d.js} +1 -1
- package/dist/assets/{CaseDetail-CPGVCggR.js → CaseDetail-dci6PiNM.js} +1 -1
- package/dist/assets/{Cases-CpluIjg7.js → Cases-DySeA3ym.js} +1 -1
- package/dist/assets/{ChatEndpointDetail-C15kjogV.js → ChatEndpointDetail-DYg7hB9_.js} +1 -1
- package/dist/assets/{ChatEndpointSetup-Czgls4T4.js → ChatEndpointSetup-D82OKj2o.js} +1 -1
- package/dist/assets/{ChoiceControls-Dd_bVqHH.js → ChoiceControls-BCF1vPaa.js} +1 -1
- package/dist/assets/{Companies-DK47FHh_.js → Companies-gUbW68nN.js} +1 -1
- package/dist/assets/{CompanyAccess-G_ygWCdy.js → CompanyAccess-C0cDvj8M.js} +1 -1
- package/dist/assets/{CompanyActivity-BzF5S-ak.js → CompanyActivity-CbIPKv4K.js} +1 -1
- package/dist/assets/{CompanyConnections-V6QokJbP.js → CompanyConnections-BezhEQiP.js} +1 -1
- package/dist/assets/{CompanyEnvironments-Dtsf3CLS.js → CompanyEnvironments-6-P8NN3Q.js} +1 -1
- package/dist/assets/{CompanyExport-CMPWrtnT.js → CompanyExport-UdhY3JMr.js} +1 -1
- package/dist/assets/{CompanyImport-1brk-ZPP.js → CompanyImport-Dj5G-Ci_.js} +1 -1
- package/dist/assets/{CompanySettings-DXs4duFl.js → CompanySettings-ifpz0tmL.js} +1 -1
- package/dist/assets/{CompanySettingsPluginPage-C2DZeyFu.js → CompanySettingsPluginPage-BCK7KaI1.js} +1 -1
- package/dist/assets/{CompanySkills-BE6s5mI1.js → CompanySkills-mzA6IM7-.js} +1 -1
- package/dist/assets/{ConfigureBuiltInAgentModal-7wvPpeNM.js → ConfigureBuiltInAgentModal-DsiGg71e.js} +1 -1
- package/dist/assets/{CopyableGatewayUrl-i8-LiYxQ.js → CopyableGatewayUrl-DwtHLPUd.js} +1 -1
- package/dist/assets/{Dashboard-CU-kG6C4.js → Dashboard-CHGehxNs.js} +1 -1
- package/dist/assets/{DecisionDateChips-BhvEmkt1.js → DecisionDateChips-Ce1EP_35.js} +1 -1
- package/dist/assets/{DecisionQueuePage-CBULv6cY.js → DecisionQueuePage-B55ERukD.js} +1 -1
- package/dist/assets/{DesignGuide-BwncU-wB.js → DesignGuide-CoW-4sZp.js} +1 -1
- package/dist/assets/{EmailEndpointSetup-BPf_8pC0.js → EmailEndpointSetup-Q4I-LgnZ.js} +1 -1
- package/dist/assets/{ExecutionWorkspaceDetail-CqvRHX5r.js → ExecutionWorkspaceDetail-_LuHtfta.js} +1 -1
- package/dist/assets/{GatewayDetail-Br82oQib.js → GatewayDetail-BKCHLhcu.js} +1 -1
- package/dist/assets/{GatewaysList-kBD3cwdU.js → GatewaysList-CZ-_zFD_.js} +1 -1
- package/dist/assets/{GoalDetail-BFeUPzal.js → GoalDetail-Bd04vnyA.js} +1 -1
- package/dist/assets/{GoalTree-CaQSt6o5.js → GoalTree-DtvAb581.js} +1 -1
- package/dist/assets/{Goals-CnYUdXEo.js → Goals-BXW_WXNa.js} +1 -1
- package/dist/assets/{ImageGalleryModal-QrZd2HrQ.js → ImageGalleryModal-xeIIyU7g.js} +1 -1
- package/dist/assets/{Inbox-C6bCCEH6.js → Inbox-DmxWV98u.js} +1 -1
- package/dist/assets/{InstanceAdvanced-CTjlJp69.js → InstanceAdvanced-DMrEvjyY.js} +1 -1
- package/dist/assets/{InviteLanding-C65R08_E.js → InviteLanding-C-S7p6JM.js} +1 -1
- package/dist/assets/{IssueChatLongThreadPerf-mdn5NFzU.js → IssueChatLongThreadPerf-BWbJprSQ.js} +1 -1
- package/dist/assets/{IssueChatThread-CZ9Q-xq-.js → IssueChatThread-DmAyIOuN.js} +1 -1
- package/dist/assets/{IssueDetail-svM2GGnk.js → IssueDetail-issXYSBj.js} +1 -1
- package/dist/assets/{IssueOutputSection-Du3C5TFv.js → IssueOutputSection-BioA9Nux.js} +1 -1
- package/dist/assets/{IssueRecoveryActionCard-Bq2QDhQA.js → IssueRecoveryActionCard-CGWmkRkb.js} +1 -1
- package/dist/assets/{IssueReferencePill-Cnjk1Ugc.js → IssueReferencePill-DWL74G_c.js} +1 -1
- package/dist/assets/{IssueThreadInteractionCard-CAzrNSjO.js → IssueThreadInteractionCard-bP4n_lcw.js} +1 -1
- package/dist/assets/{Issues-D97SDuYL.js → Issues-ButYwujh.js} +1 -1
- package/dist/assets/{LiveNowTodoLine-Cq1ub6Gj.js → LiveNowTodoLine-CiCmi71g.js} +1 -1
- package/dist/assets/{ManagedAiConnectionDetails-COyNN_aD.js → ManagedAiConnectionDetails-CgCv2fqy.js} +1 -1
- package/dist/assets/{McpConnect-CYsPUSYV.js → McpConnect-CeT7gUW_.js} +1 -1
- package/dist/assets/{MembershipAction-DYMy7umB.js → MembershipAction-BX9XIExA.js} +1 -1
- package/dist/assets/{ModelsAndProviders-BJaNzbhV.js → ModelsAndProviders-SEGB5DIt.js} +1 -1
- package/dist/assets/{NewAgent-DGXol110.js → NewAgent-LKqNzfsM.js} +1 -1
- package/dist/assets/{OmpAllSettings-BvYkLMhp.js → OmpAllSettings-1aXWEp6h.js} +1 -1
- package/dist/assets/{PipelineSettings-B6Am-LrO.js → PipelineSettings-UFCz50OY.js} +1 -1
- package/dist/assets/{Pipelines-MgjAhzew.js → Pipelines-n5EQOzN2.js} +1 -1
- package/dist/assets/{PixelsOffice-DnBnPerp.js → PixelsOffice-De61dU2s.js} +1 -1
- package/dist/assets/{PluginPage-C1XADFT2.js → PluginPage-CBSnEw7x.js} +1 -1
- package/dist/assets/{PluginSettings-CapWiXsO.js → PluginSettings-D2pNKDKr.js} +1 -1
- package/dist/assets/{ProfileDetailRoute-PJCQrW25.js → ProfileDetailRoute-DCbTvhPd.js} +1 -1
- package/dist/assets/{ProfileSettings-DXbA8GQP.js → ProfileSettings-BUYIctBS.js} +1 -1
- package/dist/assets/{ProfileWizardRoute-DaZPFglw.js → ProfileWizardRoute-o4Kf_DhP.js} +1 -1
- package/dist/assets/{ProjectDetail-DQxMbc1Q.js → ProjectDetail-DOF0t71W.js} +1 -1
- package/dist/assets/{ProjectWorkspaceDetail-dA3zVCbf.js → ProjectWorkspaceDetail-BEbFq9oK.js} +1 -1
- package/dist/assets/{ProjectWorkspacesContent-DnzUTFfW.js → ProjectWorkspacesContent-DwVqtur5.js} +1 -1
- package/dist/assets/{Projects-D3ZC8FJk.js → Projects-BsZYs3Fo.js} +1 -1
- package/dist/assets/{PublicIssueSharePage-BtWc4gq4.js → PublicIssueSharePage-8uOICn1V.js} +1 -1
- package/dist/assets/{ReviewQueueCard-C9YVH9hi.js → ReviewQueueCard-rQxgVMx_.js} +1 -1
- package/dist/assets/{RichWorkProductCard-CJPI3xQY.js → RichWorkProductCard-FcmQ5fHH.js} +1 -1
- package/dist/assets/{RoutineDetail-DUZXGXpv.js → RoutineDetail-DWqy00zc.js} +1 -1
- package/dist/assets/{RoutineRunVariablesDialog-CQJpihoC.js → RoutineRunVariablesDialog-DaGovqJt.js} +1 -1
- package/dist/assets/{Routines-CZMUFOH1.js → Routines-BE2PduWG.js} +1 -1
- package/dist/assets/{ScrollToBottom-wVHhI6vr.js → ScrollToBottom-DiemLpd4.js} +1 -1
- package/dist/assets/{Search-8efHT3Mn.js → Search-B_dblFtf.js} +1 -1
- package/dist/assets/{Secrets-BZCIDLKj.js → Secrets-D8ZlRoVo.js} +1 -1
- package/dist/assets/{SkillSourceTree-D31jixpq.js → SkillSourceTree-CDK_UwP7.js} +1 -1
- package/dist/assets/{SkillSources-Bn1LRP0O.js → SkillSources-C8inxmWw.js} +1 -1
- package/dist/assets/{SkillStudio-C4o17_hm.js → SkillStudio-8S7xrus7.js} +1 -1
- package/dist/assets/{SourceTrustBadge-C0F4cAmH.js → SourceTrustBadge-DTVyCj4T.js} +1 -1
- package/dist/assets/{StatusCards-BIvnBXBN.js → StatusCards-BpujcoJb.js} +1 -1
- package/dist/assets/{SummarySlotCard-Bpu8HBIR.js → SummarySlotCard-CTolnfbx.js} +1 -1
- package/dist/assets/{TaskChatLab-DAEcgWdy.js → TaskChatLab-BfJcSULz.js} +1 -1
- package/dist/assets/{TaskChatMarker-Bbn6iq01.js → TaskChatMarker-BYJIRrTg.js} +1 -1
- package/dist/assets/{TaskChatProtocolCard-wllJ9P2o.js → TaskChatProtocolCard-DTsBzh1L.js} +1 -1
- package/dist/assets/{TaskChatThreadView-Bnyakc3A.js → TaskChatThreadView-CBwEERny.js} +1 -1
- package/dist/assets/{TaskTreeControls-BFz5K7U-.js → TaskTreeControls-BzPeXKPq.js} +1 -1
- package/dist/assets/{Terminal-DGUlqBL9.js → Terminal-DGY0GEez.js} +1 -1
- package/dist/assets/{TerminalView-Cz01H-I5.js → TerminalView-CZkTSDKg.js} +1 -1
- package/dist/assets/{TrustPresetSection-lyB0V8c9.js → TrustPresetSection-DeIvlixJ.js} +1 -1
- package/dist/assets/{UserProfile-5qgIbXdf.js → UserProfile-BkcJ9Wfx.js} +1 -1
- package/dist/assets/{WhatNeedsMe-DjxO39CR.js → WhatNeedsMe-Bg72QkYe.js} +1 -1
- package/dist/assets/{Workspaces-BzTr5cqx.js → Workspaces-BeS2M4CD.js} +1 -1
- package/dist/assets/{connection-owner-EECE9Eiz.js → connection-owner-qWfs2q4d.js} +1 -1
- package/dist/assets/{index-DbENFODe.js → index-CSIXA5y5.js} +3 -3
- package/dist/assets/{issue-properties-BmOIUOmd.js → issue-properties-D3qASSPI.js} +1 -1
- package/dist/assets/{issue-workspace-selection-CIvSmFv2.js → issue-workspace-selection-sfcpgxzV.js} +1 -1
- package/dist/assets/{pipeline-stage-presentation-DoJvVCJ3.js → pipeline-stage-presentation-C9WooPFB.js} +1 -1
- package/dist/assets/{shared-BMQlB2gM.js → shared-57amdu2f.js} +1 -1
- package/dist/assets/{transcript-adapter-DDVisW9K.js → transcript-adapter-D7nXUOr3.js} +1 -1
- package/dist/assets/{useSummaryDraftStream-BNKrqAT0.js → useSummaryDraftStream-1H3w75Dm.js} +1 -1
- package/dist/index.html +1 -1
- package/dist/sw.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var on=Object.defineProperty;var a=(t,s)=>on(t,"name",{value:s,configurable:!0});import{i as Is}from"./rolldown-runtime-ZpX3ckPj.js";import{D as qt,E as ke,Mt as ln,O as Ot,bn as cn,c as zt,d as As,f as _,g as dn,h as Qe,l as wt,mn as un,na as mn,t as Ds,ta as xn,u as pn,vn as hn,x as Q,yn as gn}from"./createLucideIcon-B-uEJvX6.js";import{h as $s,y as Wt}from"./star-BXywPGTx.js";import{X as fn,_ as Ze,n as cs,r as de,t as J,v as oe}from"./queryKeys-yuC-YxZI.js";import{t as vn}from"./useInfiniteQuery-KaGSl9U6.js";import{n as Kt}from"./CompanyContext-DDgccGSs.js";import{l as jn,o as bn,t as _e,u as yn}from"./router-2HX_SyKK.js";import{t as ze}from"./label-CPQI5V7i.js";import{i as $e,n as Me,r as Ps,t as Je}from"./tabs-BP71y3CO.js";import{t as Vt}from"./activity-BwjvcZxv.js";import{t as Nn}from"./arrow-down-left-Bbtqoesi.js";import{t as ft}from"./arrow-up-right-Who3c6Eu.js";import{t as kn}from"./bot-B76w73ks.js";import{t as Cn}from"./chevron-down-B_rMrTLq.js";import{t as wn}from"./chevron-right-DDmPvaMb.js";import{t as vt}from"./coins-DOScIoKX.js";import{t as te}from"./button-D3bYvq4T.js";import{t as Mn}from"./minus-BICJQjhd.js";import{t as Sn}from"./octagon-alert-GkcxkXei.js";import{t as Tn}from"./plus-BbX1VFl1.js";import{t as In}from"./rotate-ccw-axI90MQW.js";import{t as An}from"./scroll-text-DkybSLN1.js";import{t as Dn}from"./shield-alert-CE3cG15R.js";import{t as $n}from"./BudgetPolicyCard-BAwZpX0_.js";import{r as Pn}from"./SidebarContext-CQAYTXv1.js";import{t as st}from"./badge-Dz4tmpgp.js";import"./agent-avatar-url-BIEMYowR.js";import{t as At}from"./Identity-J7JnIwUT.js";import{t as Rn}from"./AgentAvatar-B4hORIPc.js";import{a as En}from"./ToastContext-BL2cptrZ.js";import{t as Rs}from"./agents-DjsXf9UL.js";import{t as Fn}from"./heartbeats-xPg7ZEsm.js";import{a as Ln,n as Bn,r as Un,s as _n,t as qn}from"./dialog-DlsqN-fP.js";import{t as qe}from"./input-It0utqV7.js";import{t as On}from"./access-RvWIoVKp.js";import{t as Ue}from"./skeleton-BrYUg3zU.js";import{n as zn,r as Wn,t as ds}from"./audit-navigation-IalprBz0.js";import{t as mt}from"./routines-5Q3z9LWd.js";import{n as Xt}from"./BreadcrumbContext-_dNLeVnD.js";import{t as Kn}from"./AgentIdentity-DysUzsFa.js";import{i as Ie,n as Ke,o as Ve,r as Xe,s as He}from"./select-DKYWrP8G.js";import{i as Ee,o as ye,r as ue,s as Ne,t as ne}from"./card-CtkberpO.js";import{Dn as Ht,E as Re,Ra as Vn,Yt as Xn,eo as Hn,io as Qn,no as Yn,oi as Dt,si as Es,sr as Gn,to as St,v as xt,za as $t}from"./index-DbENFODe.js";import{t as Zn}from"./activity-format-BNHOXlUD.js";import{t as Jn}from"./decision-models-DGwWNl8R.js";import{t as ea}from"./fast-responses-DfTJsIyW.js";import{t as Tt}from"./budgets-Dh83JquC.js";import{t as ta}from"./RoutineActivityRow-BKtWtOsg.js";import{t as jt}from"./QuotaBar-t5jmdx0g.js";var Fs={name:"circle-dot-dashed",size:24,node:[["path",{d:"M10.1 2.18a9.93 9.93 0 0 1 3.8 0",key:"1qdqn0"}],["path",{d:"M17.6 3.71a9.95 9.95 0 0 1 2.69 2.7",key:"1bq7p6"}],["path",{d:"M21.82 10.1a9.93 9.93 0 0 1 0 3.8",key:"1rlaqf"}],["path",{d:"M20.29 17.6a9.95 9.95 0 0 1-2.7 2.69",key:"1xk03u"}],["path",{d:"M13.9 21.82a9.94 9.94 0 0 1-3.8 0",key:"l7re25"}],["path",{d:"M6.4 20.29a9.95 9.95 0 0 1-2.69-2.7",key:"1v18p6"}],["path",{d:"M2.18 13.9a9.93 9.93 0 0 1 0-3.8",key:"xdo6bj"}],["path",{d:"M3.71 6.4a9.95 9.95 0 0 1 2.7-2.69",key:"1jjmaz"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]};Fs.node;var sa=Ds(Fs),Ls={name:"square-chart-gantt",size:24,node:[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 8h7",key:"kbo1nt"}],["path",{d:"M8 12h6",key:"ikassy"}],["path",{d:"M11 16h5",key:"oq65wt"}]],aliases:["gantt-chart-square","square-gantt-chart"]};Ls.node;var We=Ds(Ls),x=Is(mn(),1),e=Is(xn(),1);function Bs({entries:t,fastResponse:s=!1,connectionsEnabled:n=!0}){return t.length?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Recent requests. Inputs are not retained."}),(0,e.jsx)("div",{className:"overflow-x-auto",children:(0,e.jsxs)("table",{className:"w-full text-sm","aria-label":s?"Fast responses":"Decision requests",children:[(0,e.jsx)("thead",{children:(0,e.jsx)("tr",{className:"border-b border-line text-ink-3",children:["When / feature","Responsible","Task",...s?["Connection"]:[],"Model","Status","Duration","Tokens in / out","Cost"].map(i=>(0,e.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:i},i))})}),(0,e.jsx)("tbody",{children:t.map(i=>(0,e.jsxs)("tr",{className:"border-b border-line last:border-0",children:[(0,e.jsxs)("td",{className:"px-3 py-3",children:[(0,e.jsx)("div",{className:"whitespace-nowrap",children:Qe(i.startedAt)}),(0,e.jsx)("div",{className:"text-xs text-ink-3",children:i.feature==="settings.test"?"Setup test":i.feature})]}),(0,e.jsx)("td",{className:"px-3 py-3",children:i.actorType==="system"?"Wardmote services":i.userName??(i.responsibleUserId==="local-board"?"Board":"Former user")}),(0,e.jsx)("td",{className:"px-3 py-3",children:i.issueId?(0,e.jsx)(_e,{className:"underline underline-offset-4",to:`/issues/${i.issueIdentifier??i.issueId}`,children:i.issueIdentifier??"View task"}):"—"}),s&&(0,e.jsx)("td",{className:"px-3 py-3",children:i.connectionName??(i.connectionId?"Removed connection":"—")}),(0,e.jsx)("td",{className:"px-3 py-3 font-mono text-xs",children:i.model}),(0,e.jsxs)("td",{className:"px-3 py-3",children:[(0,e.jsx)("div",{children:i.status==="succeeded"?"Succeeded":i.status==="running"?"Running":i.status==="unknown"?"Unresolved":i.status==="skipped"?"Skipped":i.status==="pending"?"Pending":"Failed"}),i.publicationStatus&&(0,e.jsx)("div",{className:"text-xs text-ink-3",children:i.publicationStatus}),i.errorCode&&(0,e.jsx)("div",{className:"text-xs text-ink-3",children:i.errorCode.replaceAll("_"," ")})]}),(0,e.jsx)("td",{className:"px-3 py-3 font-mono",children:i.durationMs===null?"—":`${(i.durationMs/1e3).toFixed(1)}s`}),(0,e.jsxs)("td",{className:"whitespace-nowrap px-3 py-3 font-mono",children:[i.inputTokens===null?"—":Q(i.inputTokens)," / ",i.outputTokens===null?"—":Q(i.outputTokens)]}),(0,e.jsxs)("td",{className:"px-3 py-3 font-mono",children:[(0,e.jsx)("div",{children:i.costCents===null?"Unknown":dn(i.costCents)}),i.costStatus!=="unpriced"&&i.costStatus&&(0,e.jsx)("span",{className:"text-xs text-ink-3",children:i.costStatus==="estimated"?"Estimated":"Reported"})]})]},i.id))})]})})]}):(0,e.jsxs)("p",{className:"text-sm text-ink-3",children:[s?"No fast responses in this period.":"No decision requests in this period."," ",(0,e.jsx)(_e,{to:n?"/company/settings/connections":s?"/company/settings/instance/features":"/company/settings",className:"underline underline-offset-4",children:s?n?"Configure fast response":"Turn on fast replies":"Configure a decision model"})," to run a test."]})}a(Bs,"DecisionHistoryTable");function na({companyId:t,from:s,to:n}){const{enabled:i}=Es(),r=oe({queryKey:["decision-history",t,s,n],queryFn:a(()=>Jn.history(t,s,n),"queryFn"),refetchInterval:a(c=>c.state.data?.some(l=>l.status==="running")?5e3:!1,"refetchInterval")});return r.isPending?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Loading decision requests…"}):r.error?(0,e.jsxs)("div",{role:"alert",className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-sm text-bad",children:"Could not load decision requests."}),(0,e.jsx)(te,{variant:"secondary",onClick:a(()=>{r.refetch()},"onClick"),children:"Try again"})]}):(0,e.jsx)(Bs,{entries:r.data??[],connectionsEnabled:i})}a(na,"DecisionHistory");function aa({companyId:t,from:s,to:n}){const{enabled:i}=Es(),r=oe({queryKey:["fast-response-history",t,s,n],queryFn:a(()=>ea.history(t,s??void 0,n??void 0),"queryFn"),refetchInterval:a(c=>c.state.data?.some(l=>["pending","running"].includes(l.status)||["pending","streaming","retry"].includes(l.publicationStatus))?3e3:!1,"refetchInterval")});return r.isPending?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Loading fast responses…"}):r.error?(0,e.jsxs)("div",{role:"alert",children:[(0,e.jsx)("p",{className:"text-sm text-bad",children:"Could not load fast responses."}),(0,e.jsx)(te,{variant:"secondary",onClick:a(()=>{r.refetch()},"onClick"),children:"Try again"})]}):(0,e.jsx)(Bs,{entries:r.data??[],fastResponse:!0,connectionsEnabled:i})}a(aa,"FastResponseHistory");var bt={report(t,s,n){const i=new URLSearchParams;return s&&i.set("from",s),n&&i.set("to",n),!s&&!n&&i.set("period","all"),de.get(`/companies/${t}/costs/subscriptions?${i}`)},refresh:a(t=>de.post(`/companies/${t}/costs/subscriptions/refresh`,{}),"refresh"),update:a((t,s,n)=>de.patch(`/companies/${t}/costs/subscriptions/${s}`,n),"update"),link:a((t,s,n,i,r)=>de.post(`/companies/${t}/costs/subscriptions/${s}/link`,{targetId:n,expectedRevision:i,targetRevision:r}),"link")};function us(t,s){return s==="USD"?_(Number(t)):new Intl.NumberFormat(void 0,{style:"currency",currency:s,currencyDisplay:"code"}).format(Number(t)/100)}a(us,"subscriptionMoney");function Pt({usage:t}){return(0,e.jsxs)("span",{className:"font-mono text-xs text-ink-3",children:[Q(t.inputTokens+t.cachedInputTokens)," in · ",Q(t.outputTokens)," out",t.cachedInputTokens>0&&(0,e.jsxs)("span",{className:"block",children:[Q(t.cachedInputTokens)," input cached"]})]})}a(Pt,"SubscriptionTokenUsage");function ia({account:t,accounts:s,companyId:n,onDone:i}){const[r,c]=(0,x.useState)(t.price.plan),[l,g]=(0,x.useState)(t.price.amountCents==null?"":gn(t.price.amountCents).replace(/\.?0+$/,"")),[h,I]=(0,x.useState)(t.price.currency),[f,u]=(0,x.useState)(t.price.cadence),[y,w]=(0,x.useState)(t.price.status),[b,q]=(0,x.useState)(""),$=Ze({mutationFn:a(()=>bt.update(n,t.id,{expectedRevision:t.price.revision,plan:r,amountCents:l.trim()?cn(l.trim()):null,currency:h,cadence:f,status:y}),"mutationFn"),onSuccess:i}),K=Ze({mutationFn:a(()=>bt.link(n,t.id,b,t.price.revision,s.find(D=>D.id===b).price.revision),"mutationFn"),onSuccess:i}),F=s.filter(D=>D.id!==t.id&&D.provider===t.provider&&D.canEdit),z=$.isPending||K.isPending,Y="h-9 rounded-md border border-line-strong bg-bg px-3 text-sm";return(0,e.jsxs)("div",{className:"space-y-5",children:[(0,e.jsxs)("form",{className:"space-y-4",onSubmit:a(D=>{D.preventDefault(),$.mutate()},"onSubmit"),children:[(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-plan",children:"Plan"}),(0,e.jsx)(qe,{id:"subscription-plan",value:r,onChange:a(D=>c(D.target.value),"onChange"),required:!0,maxLength:100})]}),(0,e.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-price",children:"Price per billing period"}),(0,e.jsx)(qe,{id:"subscription-price",type:"number",min:"0",step:"any",value:l,placeholder:"Unknown",onChange:a(D=>g(D.target.value),"onChange")})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-currency",children:"Currency"}),(0,e.jsx)("select",{id:"subscription-currency",className:Y,value:h,onChange:a(D=>I(D.target.value),"onChange"),children:ln.map(D=>(0,e.jsx)("option",{children:D},D))})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-cadence",children:"Billed"}),(0,e.jsxs)("select",{id:"subscription-cadence",className:Y,value:f,onChange:a(D=>u(D.target.value),"onChange"),children:[(0,e.jsx)("option",{value:"month",children:"Monthly"}),(0,e.jsx)("option",{value:"year",children:"Annually"})]})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-status",children:"Tracking"}),(0,e.jsxs)("select",{id:"subscription-status",className:Y,value:y,onChange:a(D=>w(D.target.value),"onChange"),children:[(0,e.jsx)("option",{value:"active",children:"Active"}),(0,e.jsx)("option",{value:"ended",children:"Subscription ended"}),(0,e.jsx)("option",{value:"excluded",children:"Exclude from this organization"})]})]})]}),(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Enter the full amount for one account or seat. Annual prices are divided by 12. Changes apply from now. Ending tracking here does not cancel your provider subscription."}),$.error&&(0,e.jsx)("p",{role:"alert",className:"text-sm text-bad",children:"Could not save this price. Check the amount, or reopen the account if another person updated it."}),(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsx)(te,{type:"button",variant:"ghost",disabled:z,onClick:i,children:"Cancel"}),(0,e.jsx)(te,{type:"submit",disabled:z,children:$.isPending?"Saving…":"Save price"})]})]}),F.length>0&&(0,e.jsxs)("div",{className:"space-y-2 border-t border-line pt-4",children:[(0,e.jsx)(ze,{htmlFor:"subscription-link",children:"Same subscription as another account?"}),(0,e.jsxs)("select",{id:"subscription-link",className:Y,value:b,onChange:a(D=>q(D.target.value),"onChange"),children:[(0,e.jsx)("option",{value:"",children:"Choose an account"}),F.map(D=>(0,e.jsxs)("option",{value:D.id,children:[D.name," · ",D.price.plan]},D.id))]}),(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Linking counts these accounts once, combines their Wardmote usage, and keeps the selected account’s price. Only link the same subscription or paid seat."}),K.error&&(0,e.jsx)("p",{role:"alert",className:"text-sm text-bad",children:"Could not link these accounts. Reopen their details and try again."}),(0,e.jsx)(te,{type:"button",variant:"secondary",disabled:!b||z,onClick:a(()=>K.mutate(),"onClick"),children:"Link accounts"})]})]})}a(ia,"SubscriptionEditor");function ra({companyId:t,report:s,error:n,onChanged:i}){const[r,c]=(0,x.useState)(!1),[l,g]=(0,x.useState)(null),h=a(()=>{g(null),i()},"closeEditor"),I=s?.monthlyTotals.length,f=s?.monthlyTotals.reduce((u,y)=>u+y.estimatedCount,0)??0;return(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(ne,{className:"block p-4",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"Subscriptions"}),(0,e.jsx)("div",{className:"mt-2 font-mono text-2xl font-semibold tabular-nums",children:I?s.monthlyTotals.map(u=>(0,e.jsxs)("div",{children:[us(u.amountCents,u.currency),(0,e.jsx)("span",{className:"text-sm font-normal",children:"/month"})]},u.currency)):s&&s.activeCount===0&&s.accounts.length>0?"$0.00/month":"—"}),(0,e.jsxs)("div",{className:"mt-1 space-y-1 text-xs text-ink-3",children:[s?(0,e.jsxs)(e.Fragment,{children:[f>0&&(0,e.jsx)("div",{children:(0,e.jsx)(st,{variant:"outline",className:"font-normal text-ink-3",children:f<s.activeCount-s.unknownPriceCount?"Partially estimated":"Estimated"})}),s.unknownPriceCount>0&&!!I&&(0,e.jsx)("div",{children:"Known monthly subtotal"}),(0,e.jsx)("div",{children:s.accounts.length===0?"No visible subscriptions":(0,e.jsxs)(e.Fragment,{children:[s.activeCount," active ",s.activeCount===1?"subscription":"subscriptions",s.unknownPriceCount>0&&` · ${s.unknownPriceCount} ${s.unknownPriceCount===1?"price":"prices"} unknown`]})}),s.accounts.length>0&&(0,e.jsx)("div",{children:"Monthly fees for accounts visible to you"}),s.unidentifiedAccountCount>0&&(0,e.jsxs)("div",{children:[s.unidentifiedAccountCount," unconfirmed ",s.unidentifiedAccountCount===1?"account identity":"account identities"]}),(0,e.jsx)(Pt,{usage:s.subscription})]}):n?(0,e.jsx)("div",{children:"Subscription data is unavailable."}):(0,e.jsx)("div",{children:"Loading subscriptions…"}),s&&n?(0,e.jsx)("div",{children:"Showing last loaded subscription data."}):null]}),(0,e.jsx)(te,{variant:"link",size:"sm",className:"h-auto p-0",onClick:a(()=>c(!0),"onClick"),disabled:!s,children:"View details"})]}),(0,e.jsx)(qn,{open:r,onOpenChange:a(u=>{c(u),u||g(null)},"onOpenChange"),children:(0,e.jsxs)(Bn,{className:"max-h-(--sz-80vh) overflow-y-auto sm:max-w-3xl",children:[(0,e.jsxs)(Ln,{children:[(0,e.jsx)(_n,{children:l?"Subscription price":"Subscriptions"}),(0,e.jsx)(Un,{children:"Current monthly costs for accounts visible to you. Token totals cover company work in the selected period."})]}),l?(0,e.jsx)(ia,{companyId:t,account:l,accounts:s?.accounts??[],onDone:h},l.id):(0,e.jsxs)("div",{className:"space-y-4",children:[s?.accounts.length===0&&(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No subscriptions are visible to you yet. Connect an AI account or run an agent with a connected subscription."}),s?.accounts.map(u=>(0,e.jsxs)("div",{className:"space-y-2 border-b border-line pb-4 last:border-0",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"font-medium",children:u.name}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[u.shared?"Shared":u.ownerName??(u.ownerUserId?"Account owner":"Personal accounts")," · ",ke(u.provider)," · ",u.price.plan]})]}),(0,e.jsxs)("div",{className:"text-right",children:[(0,e.jsx)("div",{className:"font-mono",children:u.price.status!=="active"?u.price.status==="ended"?"Ended":"Excluded":u.price.monthlyCents==null?"Price unknown":`${us(u.price.monthlyCents,u.price.currency)}/month`}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[u.price.source==="catalog"?"Estimated · before tax":u.price.source==="user"?"User supplied":"",u.price.cadence==="year"?" · annual payment ÷ 12":""]})]})]}),(0,e.jsx)(Pt,{usage:u.usage}),Number(u.usage.costCents)>0&&(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[_(Number(u.usage.costCents))," recorded usage charges in selected period, separate from the subscription fee."]}),u.agents.length>0&&(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:["Used by ",u.agents.map(y=>y.name).join(", ")]}),!u.identityVerified&&(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Account identity is unconfirmed. Link duplicates if these connections use the same subscription."}),u.observedAt&&(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:["Plan checked ",Qe(u.observedAt),u.refreshStatus==="unavailable"?" · latest check unavailable":""]}),u.refreshStatus==="unavailable"&&!u.observedAt&&(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"The provider did not make plan details available. You can enter the price yourself."}),u.canEdit&&(0,e.jsx)("div",{children:(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>g(u),"onClick"),children:"Edit price"})})]},u.id)),!!s?.unattributedSubscription.eventCount&&(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Some subscription usage has no recorded account. It is included in the subscription token total."}),(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Monthly fees cover the whole account, including use outside Wardmote. They are separate from recorded charges and agent budgets. Currencies are totaled separately."})]})]})})]})}a(ra,"SubscriptionCostCard");function Us({eventCount:t,estimatedEventCount:s}){if(!s)return null;const n=s===t;return(0,e.jsx)(st,{variant:"outline",className:"font-normal text-ink-3",title:`${s} estimated ${s===1?"charge":"charges"}. Calculated from token usage and published rates; provider bills may differ.`,children:n?"Estimated":"Partially estimated"})}a(Us,"CostEstimateLabel");function pt({costCents:t,eventCount:s,estimatedEventCount:n,unpricedEventCount:i,suffix:r}){return(0,e.jsxs)("div",{className:"flex flex-col items-end gap-1 text-right",children:[(0,e.jsxs)("div",{className:"whitespace-nowrap font-mono font-medium tabular-nums",children:[t===0&&(s??0)>0&&i===s?"—":_(t),r]}),(0,e.jsx)(Us,{eventCount:s,estimatedEventCount:n})]})}a(pt,"CostAmount");function oa({report:t}){return(0,e.jsxs)(ne,{className:"gap-3 py-4",children:[(0,e.jsx)(ye,{className:"gap-0 px-5",children:(0,e.jsx)(Ne,{className:"text-base",children:"By user"})}),(0,e.jsxs)(ue,{className:"px-5",children:[(0,e.jsx)("div",{className:"overflow-x-auto",children:(0,e.jsxs)("table",{"aria-label":"Costs by user",className:"stack-table w-full text-sm",children:[(0,e.jsx)("thead",{className:"text-ink-3",children:(0,e.jsxs)("tr",{className:"border-b border-line",children:[(0,e.jsx)("th",{scope:"col",className:"py-2 pr-4 text-left font-medium",children:"User"}),(0,e.jsx)("th",{scope:"col",className:"px-4 py-2 text-right font-medium",children:"Runs"}),(0,e.jsx)("th",{scope:"col",className:"px-4 py-2 text-right font-medium",children:"Input"}),(0,e.jsx)("th",{scope:"col",className:"px-4 py-2 text-right font-medium",children:"Output"}),(0,e.jsx)("th",{scope:"col",className:"py-2 pl-4 text-right font-medium",children:"Cost"})]})}),(0,e.jsxs)("tbody",{children:[t.rows.length===0&&(0,e.jsx)("tr",{children:(0,e.jsx)("td",{colSpan:5,"data-cell":"title",className:"py-3 text-ink-3",children:"No user-attributed costs yet."})}),t.rows.map(s=>(0,e.jsxs)("tr",{className:"border-b border-line last:border-0",children:[(0,e.jsx)("th",{scope:"row","data-cell":"title",className:"py-3 pr-4 text-left font-normal",children:s.userId?(0,e.jsx)(At,{name:s.userName??"Unknown user",avatarUrl:s.userImage}):"Unattributed"}),(0,e.jsx)("td",{"data-cell":"meta","data-label":"Runs",className:"px-4 py-3 text-right tabular-nums",children:s.runCount.toLocaleString()}),(0,e.jsxs)("td",{"data-cell":"meta","data-label":"Input",className:"px-4 py-3 text-right tabular-nums",children:[Q(s.inputTokens+s.cachedInputTokens),s.cachedInputTokens>0&&(0,e.jsxs)("div",{className:"whitespace-nowrap text-xs text-ink-3",children:[Q(s.cachedInputTokens)," cached"]})]}),(0,e.jsx)("td",{"data-cell":"meta","data-label":"Output",className:"px-4 py-3 text-right tabular-nums",children:Q(s.outputTokens)}),(0,e.jsxs)("td",{"data-cell":"end",className:"py-3 pl-4 text-right tabular-nums",children:[(0,e.jsx)(pt,{costCents:s.costCents,eventCount:s.eventCount,estimatedEventCount:s.estimatedEventCount,unpricedEventCount:s.unpricedEventCount}),s.unpricedEventCount>0&&(0,e.jsxs)("div",{className:"whitespace-nowrap text-xs text-ink-3",children:[s.unpricedEventCount," unpriced ",s.unpricedEventCount===1?"charge":"charges"]})]})]},s.userId??"unattributed"))]})]})}),t.rows.some(s=>s.userId===null)&&(0,e.jsx)("p",{className:"mt-3 text-xs text-ink-3",children:"Unattributed costs have no recorded user in this organization."})]})]})}a(oa,"CostByUserTable");function Te(t,s){const n=new URLSearchParams;!t&&!s&&n.set("period","all"),t&&n.set("from",t),s&&n.set("to",s);const i=n.toString();return i?`?${i}`:""}a(Te,"dateParams");var xe={summary:a((t,s,n)=>de.get(`/companies/${t}/costs/summary${Te(s,n)}`),"summary"),byUser:a((t,s,n)=>de.get(`/companies/${t}/costs/by-user${Te(s,n)}`),"byUser"),byAgent:a((t,s,n)=>de.get(`/companies/${t}/costs/by-agent${Te(s,n)}`),"byAgent"),byAgentModel:a((t,s,n)=>de.get(`/companies/${t}/costs/by-agent-model${Te(s,n)}`),"byAgentModel"),byProject:a((t,s,n)=>de.get(`/companies/${t}/costs/by-project${Te(s,n)}`),"byProject"),byProvider:a((t,s,n)=>de.get(`/companies/${t}/costs/by-provider${Te(s,n)}`),"byProvider"),byBiller:a((t,s,n)=>de.get(`/companies/${t}/costs/by-biller${Te(s,n)}`),"byBiller"),financeSummary:a((t,s,n)=>de.get(`/companies/${t}/costs/finance-summary${Te(s,n)}`),"financeSummary"),financeByBiller:a((t,s,n)=>de.get(`/companies/${t}/costs/finance-by-biller${Te(s,n)}`),"financeByBiller"),financeByKind:a((t,s,n)=>de.get(`/companies/${t}/costs/finance-by-kind${Te(s,n)}`),"financeByKind"),financeEvents:a((t,s,n,i=100)=>de.get(`/companies/${t}/costs/finance-events${la(s,n,i)}`),"financeEvents"),windowSpend:a(t=>de.get(`/companies/${t}/costs/window-spend`),"windowSpend"),quotaWindows:a(t=>de.get(`/companies/${t}/costs/quota-windows`),"quotaWindows")};function la(t,s,n){const i=new URLSearchParams;!t&&!s&&i.set("period","all"),t&&i.set("from",t),s&&i.set("to",s),n&&i.set("limit",String(n));const r=i.toString();return r?`?${r}`:""}a(la,"dateParamsWithLimit");function ms({row:t,weekSpendCents:s,budgetMonthlyCents:n,showBudgetUtilization:i=!0,totalCompanySpendCents:r,providerRows:c}){const l=(0,x.useMemo)(()=>{const f=new Map;for(const u of c){const y=f.get(u.provider)??{provider:u.provider,costCents:0,inputTokens:0,outputTokens:0};y.costCents+=u.costCents,y.inputTokens+=u.inputTokens+u.cachedInputTokens,y.outputTokens+=u.outputTokens,f.set(u.provider,y)}return Array.from(f.values()).sort((u,y)=>y.costCents-u.costCents)},[c]),g=(0,x.useMemo)(()=>{const f=new Map;for(const u of c)f.set(u.billingType,(f.get(u.billingType)??0)+u.costCents);return Array.from(f.entries()).sort((u,y)=>y[1]-u[1])},[c]),h=n,I=h>0?Math.min(100,t.costCents/h*100):0;return(0,e.jsxs)(ne,{children:[(0,e.jsx)(ye,{className:"px-4 pt-4 pb-0 gap-1",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)(Ne,{className:"text-sm font-semibold",children:ke(t.biller)}),(0,e.jsxs)(Ee,{className:"text-xs mt-0.5",children:[(0,e.jsx)("span",{className:"font-mono",children:Q(t.inputTokens+t.cachedInputTokens)})," in"," · ",(0,e.jsx)("span",{className:"font-mono",children:Q(t.outputTokens)})," out"," · ",t.providerCount," provider",t.providerCount===1?"":"s"," · ",t.modelCount," model",t.modelCount===1?"":"s"]})]}),(0,e.jsx)("span",{className:"text-xl font-bold tabular-nums shrink-0",children:_(t.costCents)})]})}),(0,e.jsxs)(ue,{className:"px-4 pb-4 pt-3 space-y-4",children:[i&&n>0&&(0,e.jsx)(jt,{label:"Period spend",percentUsed:I,leftLabel:_(t.costCents),rightLabel:`${Math.round(I)}% of company budget`}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[t.apiRunCount>0?`${t.apiRunCount} metered run${t.apiRunCount===1?"":"s"}`:"0 metered runs"," · ",t.subscriptionRunCount>0?`${t.subscriptionRunCount} subscription run${t.subscriptionRunCount===1?"":"s"}`:"0 subscription runs"," · ",_(s)," this week"]}),g.length>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Billing types"}),(0,e.jsx)("div",{className:"space-y-1.5",children:g.map(([f,u])=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,e.jsx)("span",{className:"text-ink-3",children:zt(f)}),(0,e.jsx)("span",{className:"font-medium tabular-nums",children:_(u)})]},f))})]})]}),l.length>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Upstream providers"}),(0,e.jsx)("div",{className:"space-y-1.5",children:l.map(f=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,e.jsx)("span",{className:"text-ink-3",children:ke(f.provider)}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsx)("div",{className:"font-medium",children:_(f.costCents)}),(0,e.jsxs)("div",{className:"text-ink-3",children:[Q(f.inputTokens+f.outputTokens)," tok"]})]})]},f.provider))})]})]})]})]})}a(ms,"BillerSpendCard");function ca(t){return(t/100).toFixed(2)}a(ca,"centsInputValue");function da(t){const s=Number(t);return!Number.isFinite(s)||s<0?null:Math.round(s*100)}a(da,"parseDollarInput");function ua(t){return t.status==="resolved"?"Resolved":t.status==="dismissed"?"Dismissed":t.approvalStatus==="revision_requested"?"Escalated":t.approvalStatus==="pending"?"Pending approval":"Open"}a(ua,"incidentStateLabel");function xs({incident:t,onRaiseAndResume:s,onKeepPaused:n,isMutating:i}){const[r,c]=(0,x.useState)(ca(Math.max(t.amountObserved+1e3,t.amountLimit))),l=da(r),g=ua(t);return(0,e.jsxs)(ne,{className:"overflow-hidden border-red-500/20 bg-(image:--gradient-extract-4)",children:[(0,e.jsx)(ye,{className:"px-5 pt-5 pb-3",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsxs)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-red-700/90 dark:text-red-200/80",children:[t.scopeType," hard stop"]}),(0,e.jsx)(st,{variant:t.status==="resolved"?"outline":"secondary",children:g})]}),(0,e.jsx)(Ne,{className:"mt-1 text-base text-red-950 dark:text-red-50",children:t.scopeName}),(0,e.jsx)(Ee,{className:"mt-1 text-red-900/75 dark:text-red-100/70",children:t.thresholdType==="hard"&&t.amountObserved<t.amountLimit?`Accounting is incomplete. Known spend is ${_(t.amountObserved)}; review pending or unpriced usage in the budget policy.`:`Spending reached ${_(t.amountObserved)} against a limit of ${_(t.amountLimit)}.`})]}),(0,e.jsx)("div",{className:"rounded-full border border-red-400/30 bg-red-500/10 p-2 text-red-600 dark:text-red-200",children:(0,e.jsx)(Sn,{className:"h-4 w-4"})})]})}),(0,e.jsxs)(ue,{className:"space-y-4 px-5 pb-5 pt-0",children:[(0,e.jsxs)("div",{className:"flex items-start gap-2 rounded-xl border border-red-400/20 bg-red-500/10 px-3 py-2 text-sm text-red-950/90 dark:text-red-50/90",children:[(0,e.jsx)(Qn,{className:"mt-0.5 h-4 w-4 shrink-0"}),(0,e.jsx)("div",{children:t.scopeType==="project"?"Project execution is paused. New work in this project will not start until you resolve the budget incident.":"This scope is paused. New heartbeats will not start until you resolve the budget incident."})]}),(0,e.jsxs)("div",{className:"rounded-xl border border-line/60 bg-bg/60 p-3",children:[(0,e.jsx)("label",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-ink-3",children:"New budget (USD)"}),(0,e.jsxs)("div",{className:"mt-2 flex flex-col gap-3 sm:flex-row",children:[(0,e.jsx)(qe,{value:r,onChange:a(h=>c(h.target.value),"onChange"),inputMode:"decimal",placeholder:"0.00"}),(0,e.jsxs)(te,{className:"gap-2",disabled:i||l===null||l<=t.amountObserved,onClick:a(()=>{typeof l=="number"&&s(l)},"onClick"),children:[(0,e.jsx)(ft,{className:"h-4 w-4"}),i?"Applying...":"Raise budget & resume"]})]}),l!==null&&l<=t.amountObserved?(0,e.jsx)("p",{className:"mt-2 text-xs text-red-700 dark:text-red-200/80",children:"The new budget must exceed current observed spend."}):null]}),(0,e.jsx)("div",{className:"flex justify-end",children:(0,e.jsx)(te,{variant:"ghost",disabled:i,onClick:n,children:"Keep paused"})})]})]})}a(xs,"BudgetIncidentCard");function ma({row:t}){return(0,e.jsxs)(ne,{children:[(0,e.jsx)(ye,{className:"px-4 pt-4 pb-1",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)(Ne,{className:"text-base",children:ke(t.biller)}),(0,e.jsxs)(Ee,{className:"mt-1 text-xs",children:[t.eventCount," event",t.eventCount===1?"":"s"," across ",t.kindCount," kind",t.kindCount===1?"":"s"]})]}),(0,e.jsxs)("div",{className:"text-right",children:[(0,e.jsx)("div",{className:"text-lg font-semibold tabular-nums",children:_(t.netCents,t.currency)}),(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"net"})]})]})}),(0,e.jsx)(ue,{className:"space-y-3 px-4 pb-4 pt-3",children:(0,e.jsxs)("div",{className:"grid gap-2 text-sm sm:grid-cols-3",children:[(0,e.jsxs)("div",{className:"border border-line p-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"debits"}),(0,e.jsx)("div",{className:"mt-1 font-medium tabular-nums",children:_(t.debitCents,t.currency)})]}),(0,e.jsxs)("div",{className:"border border-line p-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"credits"}),(0,e.jsx)("div",{className:"mt-1 font-medium tabular-nums",children:_(t.creditCents,t.currency)})]}),(0,e.jsxs)("div",{className:"border border-line p-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"estimated"}),(0,e.jsx)("div",{className:"mt-1 font-medium tabular-nums",children:_(t.estimatedDebitCents,t.currency)})]})]})})]})}a(ma,"FinanceBillerCard");function xa({rows:t}){return(0,e.jsxs)(ne,{children:[(0,e.jsxs)(ye,{className:"px-4 pt-4 pb-1",children:[(0,e.jsx)(Ne,{className:"text-base",children:"Financial event mix"}),(0,e.jsx)(Ee,{children:"Account-level charges grouped by event kind."})]}),(0,e.jsx)(ue,{className:"space-y-2 px-4 pb-4 pt-3",children:t.length===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No finance events in this period."}):t.map(s=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3 border border-line px-3 py-2",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"truncate text-sm font-medium",children:As(s.eventKind)}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[s.eventCount," event",s.eventCount===1?"":"s"," · ",s.billerCount," biller",s.billerCount===1?"":"s"]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsx)("div",{className:"text-sm font-medium",children:_(s.netCents,s.currency)}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[_(s.debitCents,s.currency)," debits"]})]})]},`${s.eventKind}:${s.currency}`))})]})}a(xa,"FinanceKindCard");function pa({rows:t,emptyMessage:s="No financial events recorded in this period. Events appear when reported through the API, CLI, or a supported integration."}){return(0,e.jsxs)(ne,{children:[(0,e.jsxs)(ye,{className:"px-4 pt-4 pb-1",children:[(0,e.jsx)(Ne,{className:"text-base",children:"Recent financial events"}),(0,e.jsx)(Ee,{children:"Provider charges, subscriptions, fees, and credits. Reported separately from run-cost estimates."})]}),(0,e.jsx)(ue,{className:"space-y-3 px-4 pb-4 pt-3",children:t.length===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:s}):t.map(n=>(0,e.jsx)("div",{className:"border border-line p-3",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)(st,{variant:"secondary",children:n.metadataJson?.source==="provider_cost_report"?"Provider cost report":As(n.eventKind)}),(0,e.jsx)(st,{variant:n.direction==="credit"?"outline":"secondary",children:pn(n.direction)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:Qe(n.occurredAt)})]}),(0,e.jsxs)("div",{className:"text-sm font-medium",children:[ke(n.biller),n.provider?` -> ${ke(n.provider)}`:"",n.model?(0,e.jsx)("span",{className:"ml-1 font-mono text-xs text-ink-3",children:n.model}):null]}),(n.description||n.externalInvoiceId||n.region||n.pricingTier)&&(0,e.jsxs)("div",{className:"space-y-1 text-xs text-ink-3",children:[n.description?(0,e.jsx)("div",{children:n.description}):null,n.externalInvoiceId?(0,e.jsxs)("div",{children:["invoice ",n.externalInvoiceId]}):null,n.region?(0,e.jsxs)("div",{children:["region ",n.region]}):null,n.pricingTier?(0,e.jsxs)("div",{children:["tier ",n.pricingTier]}):null]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsx)("div",{className:"text-sm font-semibold",children:_(n.amountCents,n.currency)}),(0,e.jsx)("div",{className:"text-xs text-ink-3",children:n.currency}),n.estimated?(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-amber-600",children:"estimated"}):null]})]})},n.id))})]})}a(pa,"FinanceTimelineCard");var ha=new Set(["credentials_unavailable","authentication_required","refresh_token_reused","refresh_token_expired","refresh_token_invalidated"]);function ga(t,s){return s.map(n=>{if(n.ok||n.errorFamily&&ha.has(n.errorFamily))return n;const i=t?.find(r=>r.provider===n.provider&&r.accountKey===n.accountKey);return i?.windows.length?{...n,windows:i.windows,source:i.source,capturedAt:i.capturedAt}:n})}a(ga,"retainQuotaWindows");function Mt(t){return t?"Showing the last available quota. Updates will resume automatically.":"Subscription quota is currently unavailable. Check usage with your provider."}a(Mt,"quotaUnavailableMessage");function fa({accounts:t,failed:s}){return(0,e.jsx)("div",{className:"space-y-4",children:t.map(n=>(0,e.jsxs)("section",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-sm font-medium",children:n.accountLabel??"Subscription account"}),(s||!n.ok)&&(0,e.jsx)("p",{className:"text-sm text-ink-3",children:n.errorFamily==="credentials_unavailable"?"Connect or reconnect a subscription in AI connections to view its quota.":Mt(n.windows.length>0)}),n.windows.map((i,r)=>i.usedPercent==null?(0,e.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,e.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,e.jsx)("span",{children:i.label}),(0,e.jsx)("span",{className:"font-mono text-ink-3",children:i.valueLabel??"Usage not reported"})]}),i.resetsAt&&(0,e.jsxs)("p",{className:"text-xs font-mono text-ink-3",children:["Resets ",Qe(i.resetsAt)]})]},`${i.label}:${r}`):(0,e.jsx)(jt,{className:"font-mono",label:i.label,percentUsed:i.usedPercent,leftLabel:i.valueLabel??(i.usedPercent===null?"Usage not reported":`${i.usedPercent}% used`),rightLabel:i.resetsAt?`Resets ${Qe(i.resetsAt)}`:void 0},`${i.label}:${r}`)),n.capturedAt&&(0,e.jsxs)("p",{className:"text-xs font-mono text-ink-3",children:["Last checked ",Qe(n.capturedAt)]})]},n.accountKey??n.provider))})}a(fa,"AccountQuotaPanels");var ct=["currentsession","currentweekallmodels","currentweeksonnetonly","currentweeksonnet","currentweekopusonly","currentweekopus","extrausage"];function Rt(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}a(Rt,"normalizeLabel$1");function va(t){return typeof t.detail=="string"&&t.detail.trim().length>0?t.detail.trim():t.resetsAt?`Resets ${new Date(t.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}`:null}a(va,"detailText$1");function ja(t){return[...t].sort((s,n)=>{const i=ct.indexOf(Rt(s.label)),r=ct.indexOf(Rt(n.label));return(i===-1?ct.length:i)-(r===-1?ct.length:r)})}a(ja,"orderedWindows$1");function ba(t){return t==null?"bg-zinc-700":t>=90?"bg-(--status-task-blocked)":t>=70?"bg-(--status-task-todo)":"bg-accent/70"}a(ba,"fillClass$1");function ya({windows:t,source:s=null,error:n=null}){const i=ja(t);return(0,e.jsxs)("div",{className:"border border-line px-4 py-4",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 border-b border-line pb-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-ink-3",children:"Anthropic subscription"}),(0,e.jsx)("div",{className:"mt-1 text-sm text-ink-3",children:"Quota from the Claude subscription connected to this server."})]}),s?(0,e.jsx)("span",{className:"shrink-0 border border-line px-2.5 py-1 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-eyebrow) text-ink-3",children:qt(s)}):null]}),n?(0,e.jsx)("div",{role:"status",className:"mt-4 text-sm text-ink-3",children:Mt(t.length>0)}):null,(0,e.jsx)("div",{className:"mt-4 space-y-4",children:i.map(r=>{const c=Rt(r.label),l=va(r);if(c==="extrausage")return(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:r.label}),r.valueLabel?(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:r.valueLabel}):null]}),l?(0,e.jsx)("div",{className:"mt-2 text-sm text-ink-3",children:l}):null]},r.label);const g=Math.min(100,Math.max(0,r.usedPercent??0));return(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:r.label}),l?(0,e.jsx)("div",{className:"mt-1 text-xs text-ink-3",children:l}):null]}),r.usedPercent!=null?(0,e.jsxs)("div",{className:"shrink-0 text-sm font-semibold tabular-nums text-ink",children:[r.usedPercent,"% used"]}):null]}),(0,e.jsx)("div",{className:"mt-3 h-2 overflow-hidden bg-bg-3",children:(0,e.jsx)("div",{className:wt("h-full transition-(--tp-width) duration-200",ba(r.usedPercent)),style:{width:`${g}%`}})})]},r.label)})})]})}a(ya,"ClaudeSubscriptionPanel");var dt=["5hlimit","weeklylimit","credits"];function Et(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}a(Et,"normalizeLabel");function Na(t){return[...t].sort((s,n)=>{const i=Et(s.label).replace(/^gpt53codexspark/,""),r=Et(n.label).replace(/^gpt53codexspark/,""),c=dt.indexOf(i),l=dt.indexOf(r);return(c===-1?dt.length:c)-(l===-1?dt.length:l)})}a(Na,"orderedWindows");function ka(t){return typeof t.detail=="string"&&t.detail.trim().length>0?t.detail.trim():t.resetsAt?`Resets ${new Date(t.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}`:null}a(ka,"detailText");function Ca(t){return t==null?"bg-zinc-700":t>=90?"bg-(--status-task-blocked)":t>=70?"bg-(--status-task-todo)":"bg-accent/70"}a(Ca,"fillClass");function ps(t){const s=Et(t);return s.includes("gpt53codexspark")||s.includes("gpt5")}a(ps,"isModelSpecific");function wa({windows:t,source:s=null,error:n=null}){const i=Na(t),r=i.filter(l=>!ps(l.label)),c=i.filter(l=>ps(l.label));return(0,e.jsxs)("div",{className:"border border-line px-4 py-4",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 border-b border-line pb-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-ink-3",children:"Codex subscription"}),(0,e.jsx)("div",{className:"mt-1 text-sm text-ink-3",children:"Quota from the Codex subscription connected to this server."})]}),s?(0,e.jsx)("span",{className:"shrink-0 border border-line px-2.5 py-1 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-eyebrow) text-ink-3",children:qt(s)}):null]}),n?(0,e.jsx)("div",{role:"status",className:"mt-4 text-sm text-ink-3",children:Mt(t.length>0)}):null,(0,e.jsxs)("div",{className:"mt-4 space-y-5",children:[(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-ink-3",children:"Account windows"}),(0,e.jsx)("div",{className:"space-y-3",children:r.map(l=>(0,e.jsx)(hs,{window:l},l.label))})]}),c.length>0?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-ink-3",children:"Model windows"}),(0,e.jsx)("div",{className:"space-y-3",children:c.map(l=>(0,e.jsx)(hs,{window:l},l.label))})]}):null]})]})}a(wa,"CodexSubscriptionPanel");function hs({window:t}){const s=ka(t);return t.usedPercent==null?(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:t.label}),t.valueLabel?(0,e.jsx)("div",{className:"text-sm font-semibold tabular-nums text-ink",children:t.valueLabel}):null]}),s?(0,e.jsx)("div",{className:"mt-2 text-xs text-ink-3",children:s}):null]}):(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:t.label}),s?(0,e.jsx)("div",{className:"mt-1 text-xs text-ink-3",children:s}):null]}),(0,e.jsxs)("div",{className:"shrink-0 text-sm font-semibold tabular-nums text-ink",children:[t.usedPercent,"% used"]})]}),(0,e.jsx)("div",{className:"mt-3 h-2 overflow-hidden bg-bg-3",children:(0,e.jsx)("div",{className:wt("h-full transition-(--tp-width) duration-200",Ca(t.usedPercent)),style:{width:`${Math.max(0,Math.min(100,t.usedPercent))}%`}})})]})}a(hs,"QuotaWindowRow");var Ma=["5h","24h","7d"];function gs({provider:t,rows:s,budgetMonthlyCents:n,showBudgetUtilization:i=!0,totalCompanySpendCents:r,weekSpendCents:c,windowRows:l,showDeficitNotch:g,quotaAccounts:h,quotaRequestFailed:I,quotaWindows:f=[],quotaError:u=null,quotaSource:y=null,quotaLoading:w=!1}){const{totalInputTokens:b,totalOutputTokens:q,totalTokens:$,totalCostCents:K,totalApiRuns:F,totalSubRuns:z,totalSubInputTokens:Y,totalSubOutputTokens:D,totalSubTokens:V,subSharePct:N}=(0,x.useMemo)(()=>{let v=0,X=0,Z=0,L=0,pe=0,me=0,Se=0;for(const m of s)v+=m.inputTokens+m.cachedInputTokens,X+=m.outputTokens,Z+=m.costCents,L+=m.apiRunCount,pe+=m.subscriptionRunCount,me+=m.subscriptionInputTokens+m.subscriptionCachedInputTokens,Se+=m.subscriptionOutputTokens;const he=v+X,ie=me+Se,E=he;return{totalInputTokens:v,totalOutputTokens:X,totalTokens:he,totalCostCents:Z,totalApiRuns:L,totalSubRuns:pe,totalSubInputTokens:me,totalSubOutputTokens:Se,totalSubTokens:ie,subSharePct:E>0?ie/E*100:0}},[s]),j=n,M=j>0?Math.min(100,K/j*100):0,O=j>0?j/4.33:0,d=O>0?Math.min(100,c/O*100):0,U=i&&n>0,S=(0,x.useMemo)(()=>new Map(l.map(v=>[v.window,v])),[l]),le=(0,x.useMemo)(()=>Math.max(...l.map(v=>v.costCents),0),[l]),ae=t==="anthropic",k=t==="openai"&&y?.startsWith("codex-"),H=(t==="anthropic"||t==="openai")&&(w||!!h?.length||f.length>0||u!=null);return(0,e.jsxs)(ne,{children:[(0,e.jsx)(ye,{className:"px-4 pt-4 pb-0 gap-1",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)(Ne,{className:"text-sm font-semibold",children:ke(t)}),(0,e.jsxs)(Ee,{className:"text-xs mt-0.5",children:[(0,e.jsx)("span",{className:"font-mono",children:Q(b)})," in"," · ",(0,e.jsx)("span",{className:"font-mono",children:Q(q)})," out",(F>0||z>0)&&(0,e.jsxs)("span",{className:"ml-1.5",children:["·"," ",F>0&&`~${F} api`,F>0&&z>0&&" / ",z>0&&`~${z} sub`," runs"]})]})]}),(0,e.jsx)("span",{className:"text-xl font-bold tabular-nums shrink-0",children:_(K)})]})}),(0,e.jsxs)(ue,{className:"px-4 pb-4 pt-3 space-y-4",children:[U&&(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(jt,{label:"Period spend",percentUsed:M,leftLabel:_(K),rightLabel:`${Math.round(M)}% of company budget`,showDeficitNotch:g}),(0,e.jsx)(jt,{label:"This week",percentUsed:d,leftLabel:_(c),rightLabel:`~${_(Math.round(O))} / wk`,showDeficitNotch:d>=100})]}),l.length>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Rolling windows"}),(0,e.jsx)("div",{className:"space-y-2.5",children:Ma.map(v=>{const X=S.get(v);if(!X)return null;const Z=X.costCents,L=X.inputTokens+X.cachedInputTokens+X.outputTokens,pe=le>0?Z/le*100:0;return(0,e.jsxs)("div",{className:"space-y-1",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,e.jsx)("span",{className:"font-mono text-ink-3 w-6 shrink-0",children:v}),(0,e.jsxs)("span",{className:"text-ink-3 font-mono flex-1",children:[Q(L)," tok"]}),(0,e.jsx)("span",{className:"font-medium tabular-nums",children:_(Z)})]}),(0,e.jsx)("div",{className:"h-2 w-full border border-line overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-accent/60 transition-(--tp-width) duration-150",style:{width:`${pe}%`}})})]},v)})})]})]}),z>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Subscription"}),(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:[(0,e.jsx)("span",{className:"font-mono text-ink",children:z})," runs"," · ",V>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-ink",children:Q(V)})," total"," · "]}),(0,e.jsx)("span",{className:"font-mono text-ink",children:Q(Y)})," in"," · ",(0,e.jsx)("span",{className:"font-mono text-ink",children:Q(D)})," out"]}),N>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"h-1.5 w-full border border-line overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-accent/60 transition-(--tp-width) duration-150",style:{width:`${N}%`}})}),(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:[Math.round(N),"% of token usage via subscription"]})]})]})]}),s.length>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsx)("div",{className:"space-y-3",children:s.map(v=>{const X=v.inputTokens+v.cachedInputTokens+v.outputTokens,Z=$>0?X/$*100:0,L=K>0?v.costCents/K*100:0;return(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("span",{className:"text-xs text-ink-3 truncate font-mono block",children:v.model}),(0,e.jsxs)("span",{className:"text-(length:--text-micro) text-ink-3 truncate block",children:[ke(v.biller)," · ",zt(v.billingType)]})]}),(0,e.jsxs)("div",{className:"flex items-center gap-3 shrink-0 tabular-nums text-xs",children:[(0,e.jsxs)("span",{className:"text-ink-3",children:[Q(X)," tok"]}),(0,e.jsx)("span",{className:"font-medium",children:_(v.costCents)})]})]}),(0,e.jsxs)("div",{className:"relative h-2 w-full border border-line overflow-hidden",children:[(0,e.jsx)("div",{className:"absolute inset-y-0 left-0 bg-accent/60 transition-(--tp-width) duration-150",style:{width:`${Z}%`},title:`${Math.round(Z)}% of provider tokens`}),(0,e.jsx)("div",{className:"absolute inset-y-0 left-0 bg-accent/85 transition-(--tp-width) duration-150",style:{width:`${L}%`},title:`${Math.round(L)}% of provider cost`})]})]},`${v.provider}:${v.model}`)})})]}),H&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Subscription quota"}),y&&!ae&&!k?(0,e.jsx)("span",{className:"text-(length:--text-nano) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:qt(y)}):null]}),w?(0,e.jsx)(Sa,{}):h?.length?(0,e.jsx)(fa,{accounts:h,failed:I}):ae?(0,e.jsx)(ya,{windows:f,source:y,error:u}):k?(0,e.jsx)(wa,{windows:f,source:y,error:u}):(0,e.jsxs)(e.Fragment,{children:[u?(0,e.jsx)("p",{role:"status",className:"text-xs text-ink-3",children:Mt(f.length>0)}):null,(0,e.jsx)("div",{className:"space-y-2.5",children:f.map(v=>{const X=v.usedPercent==null?null:v.usedPercent>=90?"bg-(--status-task-blocked)":v.usedPercent>=70?"bg-(--status-task-todo)":"bg-(--status-task-done)";return(0,e.jsxs)("div",{className:"space-y-1",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,e.jsx)("span",{className:"font-mono text-ink-3 shrink-0",children:v.label}),(0,e.jsx)("span",{className:"flex-1"}),v.valueLabel!=null?(0,e.jsx)("span",{className:"font-medium tabular-nums",children:v.valueLabel}):v.usedPercent!=null?(0,e.jsxs)("span",{className:"font-medium tabular-nums",children:[v.usedPercent,"% used"]}):null]}),v.usedPercent!=null&&X!=null&&(0,e.jsx)("div",{className:"h-2 w-full border border-line overflow-hidden",children:(0,e.jsx)("div",{className:`h-full transition-(--tp-width) duration-150 ${X}`,style:{width:`${v.usedPercent}%`}})}),v.detail?(0,e.jsx)("p",{className:"text-xs text-ink-3",children:v.detail}):v.resetsAt?(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:["resets ",new Date(v.resetsAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})]}):null]},v.label)})})]})]})]})]})]})}a(gs,"ProviderQuotaCard");function Sa(){return(0,e.jsxs)("div",{className:"border border-line px-4 py-4",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 border-b border-line pb-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,e.jsx)(Ue,{className:"h-3 w-36"}),(0,e.jsx)(Ue,{className:"h-4 w-64 max-w-full"})]}),(0,e.jsx)(Ue,{className:"h-7 w-28"})]}),(0,e.jsx)("div",{className:"mt-4 space-y-3",children:Array.from({length:3}).map((t,s)=>(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,e.jsx)(Ue,{className:"h-4 w-32"}),(0,e.jsx)(Ue,{className:"h-3 w-44 max-w-full"})]}),(0,e.jsx)(Ue,{className:"h-4 w-20"})]}),(0,e.jsx)(Ue,{className:"mt-3 h-2 w-full"})]},s))})]})}a(Sa,"QuotaPanelSkeleton");var Ta={mtd:"Month to Date","7d":"7 Days","30d":"30 Days",ytd:"Year to Date",all:"All Time",custom:"Custom"},Ia=["mtd","7d","30d","ytd","all","custom"];function Aa(t){const s=new Date,n=s.toISOString();switch(t){case"mtd":return{from:new Date(Date.UTC(s.getUTCFullYear(),s.getUTCMonth(),1)).toISOString(),to:n};case"7d":return{from:new Date(s.getFullYear(),s.getMonth(),s.getDate()-7,0,0,0,0).toISOString(),to:n};case"30d":return{from:new Date(s.getFullYear(),s.getMonth(),s.getDate()-30,0,0,0,0).toISOString(),to:n};case"ytd":return{from:new Date(Date.UTC(s.getUTCFullYear(),0,1)).toISOString(),to:n};case"all":case"custom":return{from:"",to:""}}}a(Aa,"computeRange");function It(t){const s=new Date(t);return s.setSeconds(0,0),s.toISOString()}a(It,"floorToMinute");function Da(){const[t,s]=(0,x.useState)("mtd"),[n,i]=(0,x.useState)(""),[r,c]=(0,x.useState)(""),l=(0,x.useRef)(null),[g,h]=(0,x.useState)(()=>It(new Date));(0,x.useEffect)(()=>{const u=new Date,y=(60-u.getSeconds())*1e3-u.getMilliseconds(),w=setTimeout(()=>{h(It(new Date)),l.current=setInterval(()=>h(It(new Date)),6e4)},y);return()=>{clearTimeout(w),l.current!=null&&clearInterval(l.current)}},[]);const{from:I,to:f}=(0,x.useMemo)(()=>{if(t!=="custom")return Aa(t);const u=n?new Date(n+"T00:00:00"):null,y=r?new Date(r+"T23:59:59.999"):null;return{from:u?u.toISOString():"",to:y?y.toISOString():""}},[t,n,r,g]);return{preset:t,setPreset:s,customFrom:n,setCustomFrom:i,customTo:r,setCustomTo:c,from:I,to:f,customReady:t!=="custom"||!!n&&!!r}}a(Da,"useDateRange");var $a="__none__";function Pa(){const t=new Date,s=t.getDay(),n=s===0?-6:1-s,i=new Date(t.getFullYear(),t.getMonth(),t.getDate()+n,0,0,0,0),r=new Date(i.getFullYear(),i.getMonth(),i.getDate()+6,23,59,59,999);return{from:i.toISOString(),to:r.toISOString()}}a(Pa,"currentWeekRange");function Ra({provider:t,rows:s}){const n=s.reduce((r,c)=>r+c.inputTokens+c.cachedInputTokens+c.outputTokens,0),i=s.reduce((r,c)=>r+c.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:ke(t)}),(0,e.jsx)("span",{className:"font-mono text-xs text-ink-3",children:Q(n)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:_(i)})]})}a(Ra,"ProviderTabLabel");function Ea({biller:t,rows:s}){const n=s.reduce((r,c)=>r+c.inputTokens+c.cachedInputTokens+c.outputTokens,0),i=s.reduce((r,c)=>r+c.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:ke(t)}),(0,e.jsx)("span",{className:"font-mono text-xs text-ink-3",children:Q(n)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:_(i)})]})}a(Ea,"BillerTabLabel");function je({label:t,value:s,subtitle:n,icon:i}){return(0,e.jsx)(ne,{className:"block p-4",children:(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:t}),(0,e.jsx)("div",{className:"mt-2 text-2xl font-semibold tabular-nums",children:s}),(0,e.jsx)("div",{className:"mt-1 text-xs leading-5 text-ink-3",children:n})]}),(0,e.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-line",children:(0,e.jsx)(i,{className:"h-4 w-4 text-ink-3"})})]})})}a(je,"MetricTile");function fs({debitCents:t,creditCents:s,netCents:n,estimatedDebitCents:i,eventCount:r}){return(0,e.jsxs)(ne,{children:[(0,e.jsxs)(ye,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(Ne,{className:"text-base",children:"Finance ledger"}),(0,e.jsx)(Ee,{children:"Account-level charges that do not map to a single inference request."})]}),(0,e.jsxs)(ue,{className:"grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4",children:[(0,e.jsx)(je,{label:"Debits",value:_(t),subtitle:`${r} total event${r===1?"":"s"} in range`,icon:ft}),(0,e.jsx)(je,{label:"Credits",value:_(s),subtitle:"Refunds, offsets, and credit returns",icon:Nn}),(0,e.jsx)(je,{label:"Net",value:_(n),subtitle:"Debit minus credit for the selected period",icon:$t}),(0,e.jsx)(je,{label:"Estimated",value:_(i),subtitle:"Estimated debits that are not yet invoice-authoritative",icon:vt})]})]})}a(fs,"FinanceSummaryCard");function vs({embedded:t=!1,initialTab:s="overview",lockTab:n=!1,hideBudgetsTab:i=!1}={}){const{selectedCompanyId:r}=Kt(),{setBreadcrumbs:c}=Xt(),l=fn(),[g,h]=Wt(),[I,f]=(0,x.useState)(s),[u,y]=(0,x.useState)("all"),[w,b]=(0,x.useState)("all"),q=!(t&&n&&s==="budgets"),{preset:$,setPreset:K,customFrom:F,setCustomFrom:z,customTo:Y,setCustomTo:D,from:V,to:N,customReady:j}=Da();(0,x.useEffect)(()=>{t||c([{label:"Costs"}])},[t,c]),(0,x.useEffect)(()=>{const o=g.get("tab");f(!n&&o&&["overview","providers","billers","finance","budgets","decisions","fast-responses"].includes(o)?o:s)},[s,n,g]);const[M,O]=(0,x.useState)(()=>new Date().toDateString()),d=(0,x.useRef)(null);(0,x.useEffect)(()=>{const o=a(()=>{const p=new Date,R=new Date(p.getFullYear(),p.getMonth(),p.getDate()+1).getTime()-p.getTime();d.current=setTimeout(()=>{O(new Date().toDateString()),o()},R)},"schedule");return o(),()=>{d.current!=null&&clearTimeout(d.current)}},[]);const U=(0,x.useMemo)(()=>Pa(),[M]),S=r??$a,le=["custom","mtd","ytd"].includes($)&&V||void 0,ae=$==="custom"?N||void 0:$,{data:k,error:H}=oe({queryKey:["cost-subscriptions",S,le,ae],queryFn:a(()=>bt.report(S,V||void 0,N||void 0),"queryFn"),enabled:!!r&&j&&q,refetchInterval:3e4}),v=a(()=>{l.invalidateQueries({queryKey:["cost-subscriptions",S]})},"invalidateSubscriptions"),X=(0,x.useRef)(null),Z=Ze({mutationFn:a(o=>bt.refresh(o),"mutationFn"),onSuccess:a((o,p)=>{l.invalidateQueries({queryKey:["cost-subscriptions",p]})},"onSuccess")});(0,x.useEffect)(()=>{!r||!q||!k?.canRefresh||X.current===r||(X.current=r,Z.mutate(r))},[r,q,k?.canRefresh,Z.mutate]);const{data:L,isLoading:pe,error:me}=oe({queryKey:J.budgets.overview(S),queryFn:a(()=>Tt.overview(S),"queryFn"),enabled:!!r&&j,refetchInterval:3e4,staleTime:5e3}),Se=a(()=>{r&&(l.invalidateQueries({queryKey:J.budgets.overview(r)}),l.invalidateQueries({queryKey:J.dashboard(r)}),l.invalidateQueries({queryKey:J.agents.list(r)}),l.invalidateQueries({queryKey:J.projects.all(r)}))},"invalidateBudgetViews"),he=Ze({mutationFn:a(({summary:o,changes:p})=>Tt.upsertPolicy(S,{scopeType:o.scopeType,scopeId:o.scopeId,metric:o.metric,windowKind:o.windowKind,...p}),"mutationFn"),onSuccess:Se}),ie=Ze({mutationFn:a(o=>Tt.resolveIncident(S,o.incidentId,o),"mutationFn"),onSuccess:Se}),{data:E,isLoading:m,error:T}=oe({queryKey:J.costs(S,le,ae),queryFn:a(async()=>{const[o,p,R,W]=await Promise.all([xe.summary(S,V||void 0,N||void 0),xe.byAgent(S,V||void 0,N||void 0),xe.byProject(S,V||void 0,N||void 0),xe.byAgentModel(S,V||void 0,N||void 0)]);return{summary:o,byAgent:p,byProject:R,byAgentModel:W}},"queryFn"),enabled:!!r&&j&&q,refetchInterval:3e4}),{data:P,error:A}=oe({queryKey:[...J.costs(S,le,ae),"by-user"],queryFn:a(()=>xe.byUser(S,V||void 0,N||void 0),"queryFn"),enabled:!!r&&j&&q&&I==="overview",refetchInterval:3e4}),{data:B,isLoading:re,error:ce}=oe({queryKey:[J.financeSummary(S,le,ae),J.financeByBiller(S,le,ae),J.financeByKind(S,le,ae),J.financeEvents(S,le,ae,18)],queryFn:a(async()=>{const[o,p,R,W]=await Promise.all([xe.financeSummary(S,V||void 0,N||void 0),xe.financeByBiller(S,V||void 0,N||void 0),xe.financeByKind(S,V||void 0,N||void 0),xe.financeEvents(S,V||void 0,N||void 0,18)]);return{summary:o,byBiller:p,byKind:R,events:W}},"queryFn"),enabled:!!r&&j&&q,refetchInterval:3e4}),[C,se]=(0,x.useState)(new Set);(0,x.useEffect)(()=>{se(new Set)},[S,$,F,Y]);function ve(o){se(p=>{const R=new Set(p);return R.has(o)?R.delete(o):R.add(o),R})}a(ve,"toggleAgent");const Ae=(0,x.useMemo)(()=>{const o=new Map;for(const p of E?.byAgentModel??[]){const R=o.get(p.agentId)??[];R.push(p),o.set(p.agentId,R)}for(const[p,R]of o)o.set(p,R.slice().sort((W,G)=>G.costCents-W.costCents));return o},[E?.byAgentModel]),{data:nt,error:Vs}=oe({queryKey:J.usageByProvider(S,le,ae),queryFn:a(()=>xe.byProvider(S,V||void 0,N||void 0),"queryFn"),enabled:!!r&&j&&(I==="providers"||I==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:Yt,error:Xs}=oe({queryKey:J.usageByBiller(S,le,ae),queryFn:a(()=>xe.byBiller(S,V||void 0,N||void 0),"queryFn"),enabled:!!r&&j&&I==="billers",refetchInterval:3e4,staleTime:1e4}),{data:Gt,error:Hs}=oe({queryKey:J.usageByProvider(S,U.from,U.to),queryFn:a(()=>xe.byProvider(S,U.from,U.to),"queryFn"),enabled:!!r&&(I==="providers"||I==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:Zt,error:Qs}=oe({queryKey:J.usageByBiller(S,U.from,U.to),queryFn:a(()=>xe.byBiller(S,U.from,U.to),"queryFn"),enabled:!!r&&I==="billers",refetchInterval:3e4,staleTime:1e4}),{data:Jt,error:Ys}=oe({queryKey:J.usageWindowSpend(S),queryFn:a(()=>xe.windowSpend(S),"queryFn"),enabled:!!r&&I==="providers",refetchInterval:3e4,staleTime:1e4}),{data:Fe,isLoading:es,error:at}=oe({queryKey:J.usageQuotaWindows(S),queryFn:a(()=>xe.quotaWindows(S),"queryFn"),structuralSharing:a((o,p)=>ga(o,p),"structuralSharing"),enabled:!!r&&I==="providers",refetchInterval:3e5,staleTime:6e4}),Ce=(0,x.useMemo)(()=>{const o=new Map;for(const p of nt??[]){const R=o.get(p.provider)??[];R.push(p),o.set(p.provider,R)}return o},[nt]),De=(0,x.useMemo)(()=>{const o=new Map;for(const p of Yt??[]){const R=o.get(p.biller)??[];R.push(p),o.set(p.biller,R)}return o},[Yt]),ts=(0,x.useMemo)(()=>{const o=new Map;for(const p of Gt??[])o.set(p.provider,(o.get(p.provider)??0)+p.costCents);return o},[Gt]),ss=(0,x.useMemo)(()=>{const o=new Map;for(const p of Zt??[])o.set(p.biller,(o.get(p.biller)??0)+p.costCents);return o},[Zt]),ns=(0,x.useMemo)(()=>{const o=new Map;for(const p of Jt??[]){const R=o.get(p.provider)??[];R.push(p),o.set(p.provider,R)}return o},[Jt]),as=(0,x.useMemo)(()=>{const o=new Map;for(const p of Fe??[])p.windows.length>0&&o.set(p.provider,p.windows);return o},[Fe]),is=(0,x.useMemo)(()=>{const o=new Map;for(const p of Fe??[])p.ok||o.set(p.provider,"unavailable");return at&&(o.set("anthropic","unavailable"),o.set("openai","unavailable")),o},[Fe,at]),rs=(0,x.useMemo)(()=>{const o=new Map;for(const p of Fe??[])typeof p.source=="string"&&p.source.length>0&&o.set(p.provider,p.source);return o},[Fe]),os=(0,x.useMemo)(()=>{const o=new Map;if($!=="mtd")return o;const p=E?.summary.budgetCents??0;if(p<=0)return o;const R=new Date,W=R.getUTCDate(),G=new Date(Date.UTC(R.getUTCFullYear(),R.getUTCMonth()+1,0)).getUTCDate();for(const[we,fe]of Ce){const ls=fe.reduce((an,rn)=>an+rn.costCents,0),nn=ls/Math.max(W,1);o.set(we,ls+nn*(G-W)>p)}return o},[$,E,Ce]),it=(0,x.useMemo)(()=>Array.from(Ce.keys()),[Ce]),rt=(0,x.useMemo)(()=>Array.from(De.keys()),[De]),ot=u==="all"||it.includes(u)?u:"all";(0,x.useEffect)(()=>{ot!==u&&y("all")},[ot,u]);const lt=w==="all"||rt.includes(w)?w:"all";(0,x.useEffect)(()=>{lt!==w&&b("all")},[lt,w]);const Gs=(0,x.useMemo)(()=>{const o=Array.from(Ce.keys()),p=o.reduce((W,G)=>W+(Ce.get(G)?.reduce((we,fe)=>we+fe.inputTokens+fe.cachedInputTokens+fe.outputTokens,0)??0),0),R=o.reduce((W,G)=>W+(Ce.get(G)?.reduce((we,fe)=>we+fe.costCents,0)??0),0);return[{value:"all",label:(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:"All providers"}),o.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-ink-3",children:Q(p)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:_(R)})]}):null]})},...o.map(W=>({value:W,label:(0,e.jsx)(Ra,{provider:W,rows:Ce.get(W)??[]})}))]},[Ce]),Zs=(0,x.useMemo)(()=>{const o=Array.from(De.keys()),p=o.reduce((W,G)=>W+(De.get(G)?.reduce((we,fe)=>we+fe.inputTokens+fe.cachedInputTokens+fe.outputTokens,0)??0),0),R=o.reduce((W,G)=>W+(De.get(G)?.reduce((we,fe)=>we+fe.costCents,0)??0),0);return[{value:"all",label:(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:"All billers"}),o.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-ink-3",children:Q(p)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:_(R)})]}):null]})},...o.map(W=>({value:W,label:(0,e.jsx)(Ea,{biller:W,rows:De.get(W)??[]})}))]},[De]),Js=B?.events??[],Ge=L?.policies??[],Le=L?.activeIncidents??[],en=(0,x.useMemo)(()=>({company:Ge.filter(o=>o.scopeType==="company"),agent:Ge.filter(o=>o.scopeType==="agent"),project:Ge.filter(o=>o.scopeType==="project")}),[Ge]);if(!r)return(0,e.jsx)(Re,{icon:St,message:"Select an organization to view costs."});const Oe=$==="custom"&&!j,tn=m&&j,sn=!E&&T;return(0,e.jsxs)("div",{className:"space-y-6",children:[q?(0,e.jsxs)("div",{className:"space-y-5",children:[(0,e.jsxs)("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[(0,e.jsx)("div",{children:t?(0,e.jsx)("h2",{className:"text-lg font-semibold text-ink",children:"Costs"}):(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:"Costs"})}),(0,e.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:Ia.map(o=>(0,e.jsx)(te,{variant:$===o?"secondary":"ghost",size:"sm",onClick:a(()=>K(o),"onClick"),"aria-pressed":$===o,children:Ta[o]},o))})]}),$==="custom"?(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 border border-line p-3",children:[(0,e.jsx)("input",{type:"date",value:F,onChange:a(o=>z(o.target.value),"onChange"),className:"h-9 rounded-md border border-line-strong bg-bg px-3 text-sm text-ink"}),(0,e.jsx)("span",{className:"text-sm text-ink-3",children:"to"}),(0,e.jsx)("input",{type:"date",value:Y,onChange:a(o=>D(o.target.value),"onChange"),className:"h-9 rounded-md border border-line-strong bg-bg px-3 text-sm text-ink"})]}):null,B?.summary.currencies?.some(o=>o.currency!=="USD")&&(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:"Finance headline totals are USD only. Other currencies are listed separately; no exchange-rate conversion is applied."}),(0,e.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-5",children:[(0,e.jsx)(je,{label:"API spend",value:k?k.api.unpricedEventCount===k.api.eventCount&&k.api.eventCount>0?"—":_(Number(k.api.costCents)):"—",subtitle:k?(0,e.jsxs)("div",{className:"space-y-1",children:[(0,e.jsx)(Us,{eventCount:k.api.eventCount,estimatedEventCount:k.api.estimatedEventCount}),(0,e.jsx)("div",{children:(0,e.jsx)(Pt,{usage:k.api})})]}):H?"API usage is unavailable":"API usage is loading",icon:St}),(0,e.jsx)(ra,{companyId:S,report:k,error:H,onChanged:v},S),(0,e.jsx)(je,{label:"Budget",value:Le.length>0?String(Le.length):E?.summary.budgetCents&&E.summary.budgetCents>0?$==="mtd"?`${E.summary.utilizationPercent}%`:_(E.summary.budgetCents):"Open",subtitle:Le.length>0?`${L?.pausedAgentCount??0} agents paused · ${L?.pausedProjectCount??0} projects paused`:E?.summary.budgetCents&&E.summary.budgetCents>0?$==="mtd"?`${_(E.summary.spendCents)} of ${_(E.summary.budgetCents)} this month`:"Monthly limit":"No monthly cap configured",icon:vt}),(0,e.jsx)(je,{label:"Recorded charges",value:B?_(B.summary.netCents):"—",subtitle:B?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("span",{className:"block whitespace-nowrap",children:[_(B.summary.debitCents)," debits"]}),(0,e.jsxs)("span",{className:"block whitespace-nowrap",children:[_(B.summary.creditCents)," credits"]})]}):"Financial data unavailable",icon:$t}),(0,e.jsx)(je,{label:"Finance events",value:B?String(B.summary.eventCount):"—",subtitle:B?`${_(B.summary.estimatedDebitCents)} estimated in range`:"Financial data unavailable",icon:ft})]}),k&&Number(k.subscription.costCents)>0&&(0,e.jsxs)("p",{className:"text-sm text-ink-3",children:["Subscription accounts also have ",_(Number(k.subscription.costCents))," in recorded usage charges for this period, separate from monthly fees."]}),k&&k.unknown.eventCount>0&&(0,e.jsxs)("p",{className:"text-sm text-ink-3",children:[Q(k.unknown.inputTokens+k.unknown.cachedInputTokens+k.unknown.outputTokens)," tokens have other or unknown billing types",Number(k.unknown.costCents)>0?`, with ${_(Number(k.unknown.costCents))} in recorded charges`:"",". They remain in the inference ledger."]}),H&&k&&(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:"Showing the last loaded API and subscription usage. Updates will resume automatically."}),Z.error&&(0,e.jsxs)("div",{role:"status",className:"flex flex-wrap items-center gap-2 text-sm text-ink-3",children:[(0,e.jsx)("p",{children:"Connected accounts could not be checked. Existing subscription estimates are still shown."}),k?.canRefresh&&(0,e.jsx)(te,{variant:"secondary",size:"sm",disabled:Z.isPending,onClick:a(()=>Z.mutate(S),"onClick"),children:"Retry account check"})]}),E?.summary.pricingComplete===!1&&(0,e.jsxs)("div",{role:"status",className:"space-y-1 text-sm text-ink-3",children:[E.summary.unpricedEventCount>0&&(0,e.jsxs)("p",{children:["Costs are unavailable for ",E.summary.unpricedEventCount," usage ",E.summary.unpricedEventCount===1?"entry":"entries"," in this period. Totals include known costs only."]}),E.summary.pendingRunCount>0&&(0,e.jsxs)("p",{children:[E.summary.pendingRunCount," ",E.summary.pendingRunCount===1?"run is":"runs are"," awaiting cost data."]})]})]}):null,me&&!L?(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:"Budget data could not be loaded. Please try again shortly."}):null,E&&T||B&&ce||L&&me||Vs||Xs||Hs||Qs||Ys?(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:"Showing the last loaded data. Updates will resume automatically."}):null,!!E?.summary.estimatedEventCount&&(0,e.jsxs)("p",{role:"status",className:"text-sm text-ink-3",children:["Includes ",E.summary.estimatedEventCount," estimated ",E.summary.estimatedEventCount===1?"charge":"charges",". Token estimates use published rates and recorded assumptions; provider bills may differ."]}),ie.error&&(0,e.jsx)("p",{role:"alert",className:"text-sm text-bad",children:"Could not update the budget. Check any pending runs or unpriced usage shown on this page, then try again."}),(0,e.jsxs)(Je,{value:I,onValueChange:a(o=>{f(o),h(p=>{const R=new URLSearchParams(p);return R.set("tab",o),R},{replace:!0})},"onValueChange"),children:[n?null:(0,e.jsx)("div",{className:"max-w-full overflow-x-auto pb-2",children:(0,e.jsxs)(Ps,{variant:"line",className:"justify-start",children:[(0,e.jsx)($e,{value:"overview",children:"Overview"}),i?null:(0,e.jsx)($e,{value:"budgets",children:"Budgets"}),(0,e.jsx)($e,{value:"providers",children:"Providers"}),(0,e.jsx)($e,{value:"billers",children:"Billers"}),(0,e.jsx)($e,{value:"finance",children:"Finance"}),(0,e.jsx)($e,{value:"decisions",children:"Decisions"}),(0,e.jsx)($e,{value:"fast-responses",children:"Fast responses"})]})}),(0,e.jsx)(Me,{value:"fast-responses",className:"mt-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):(0,e.jsx)(aa,{companyId:S,from:V,to:N})}),(0,e.jsx)(Me,{value:"decisions",className:"mt-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):(0,e.jsx)(na,{companyId:S,from:V,to:N})}),(0,e.jsx)(Me,{value:"overview",className:"mt-4 space-y-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):tn?(0,e.jsx)(xt,{variant:"costs"}):sn?(0,e.jsx)("p",{className:"text-sm text-bad",children:"Cost data could not be loaded. Please try again shortly."}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-32)",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-4",children:[(0,e.jsxs)(ne,{className:"gap-3 py-4",children:[(0,e.jsx)(ye,{className:"gap-0 px-5",children:(0,e.jsx)(Ne,{className:"text-base",children:"By agent"})}),(0,e.jsx)(ue,{className:"space-y-2 px-5",children:(E?.byAgent.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No cost events yet."}):E?.byAgent.map(o=>{const p=Ae.get(o.agentId)??[],R=C.has(o.agentId),W=p.length>0;return(0,e.jsxs)("div",{role:"group","aria-label":`${o.agentName??o.agentId??"Wardmote services"} costs`,className:"border border-line px-4 py-3",children:[(0,e.jsxs)("div",{className:wt("flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",W?"cursor-pointer select-none":""),onClick:a(()=>W&&ve(o.agentId),"onClick"),children:[(0,e.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[W?R?(0,e.jsx)(Cn,{className:"h-3 w-3 shrink-0 text-ink-3"}):(0,e.jsx)(wn,{className:"h-3 w-3 shrink-0 text-ink-3"}):(0,e.jsx)("span",{className:"h-3 w-3 shrink-0"}),o.agentId?(0,e.jsx)(Kn,{agent:{id:o.agentId,name:o.agentName??o.agentId,appearance:o.agentAppearance},size:"sm"}):(0,e.jsx)("span",{className:"font-medium",children:"Wardmote services"}),o.agentStatus==="terminated"?(0,e.jsx)(Ht,{status:"terminated"}):null]}),(0,e.jsxs)("div",{className:"text-right text-sm tabular-nums",children:[(0,e.jsx)(pt,{costCents:o.costCents,eventCount:o.eventCount,estimatedEventCount:o.estimatedEventCount}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:["in ",Q(o.inputTokens+o.cachedInputTokens)," (",Q(o.cachedInputTokens)," cached) · out ",Q(o.outputTokens)]}),o.apiRunCount>0||o.subscriptionRunCount>0?(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:["runs: ",o.apiRunCount>0?`${o.apiRunCount} api`:"0 api"," · ",o.subscriptionRunCount>0?`${o.subscriptionRunCount} sub`:"0 sub"]}):null]})]}),R&&p.length>0?(0,e.jsx)("div",{className:"mt-3 space-y-2 border-l border-line pl-4",children:p.map(G=>{const we=o.costCents>0?Math.round(G.costCents/o.costCents*100):0;return(0,e.jsxs)("div",{className:"flex flex-col gap-2 text-xs sm:flex-row sm:items-start sm:justify-between sm:gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"truncate font-medium text-ink",children:[ke(G.provider),(0,e.jsx)("span",{className:"mx-1 text-line",children:"/"}),(0,e.jsx)("span",{className:"font-mono",children:G.model})]}),(0,e.jsxs)("div",{className:"truncate text-ink-3",children:[ke(G.biller)," · ",zt(G.billingType)]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsx)(pt,{costCents:G.costCents,eventCount:G.eventCount,estimatedEventCount:G.estimatedEventCount,suffix:(0,e.jsxs)("span",{className:"ml-1 font-normal text-ink-3",children:["(",we,"%)"]})}),(0,e.jsxs)("div",{className:"text-ink-3",children:[Q(G.inputTokens+G.cachedInputTokens+G.outputTokens)," tok"]})]})]},`${G.provider}:${G.model}:${G.billingType}`)})}):null]},o.agentId??"services")})})]}),A&&(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:P?"User costs could not be refreshed. Showing the last loaded data.":"User costs could not be loaded. Please try again shortly."}),P&&(0,e.jsx)(oa,{report:P})]}),(0,e.jsx)("div",{className:"space-y-4",children:(0,e.jsxs)(ne,{className:"gap-3 py-4",children:[(0,e.jsx)(ye,{className:"gap-0 px-5",children:(0,e.jsx)(Ne,{className:"text-base",children:"By project"})}),(0,e.jsx)(ue,{className:"space-y-2 px-5",children:(E?.byProject.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No project-attributed run costs yet."}):E?.byProject.map((o,p)=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3 border border-line px-3 py-2 text-sm",children:[(0,e.jsx)("span",{className:"truncate",children:o.projectName??o.projectId??"Unattributed"}),(0,e.jsx)(pt,{costCents:o.costCents,eventCount:o.eventCount,estimatedEventCount:o.estimatedEventCount})]},o.projectId??`unattributed-${p}`))})]})})]}),Le.length>0?(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:Le.slice(0,2).map(o=>(0,e.jsx)(xs,{incident:o,isMutating:ie.isPending,onKeepPaused:a(()=>ie.mutate({incidentId:o.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:a(p=>ie.mutate({incidentId:o.id,action:"raise_budget_and_resume",amount:p}),"onRaiseAndResume")},o.id))}):null,B?(0,e.jsx)(fs,{debitCents:B.summary.debitCents,creditCents:B.summary.creditCents,netCents:B.summary.netCents,estimatedDebitCents:B.summary.estimatedDebitCents,eventCount:B.summary.eventCount}):(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:re?"Loading financial events…":"Financial events could not be loaded. Please try again shortly."})]})}),(0,e.jsxs)(Me,{value:"budgets",className:"mt-4 space-y-4",children:[he.error&&(0,e.jsx)("p",{role:"alert",className:"text-sm text-bad",children:"Could not update the budget policy. Review your settings and try again."}),pe?(0,e.jsx)(xt,{variant:"costs"}):me&&!L?null:(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(ne,{className:"border-line/70 bg-(image:--gradient-extract-2)",children:[(0,e.jsxs)(ye,{className:"px-5 pt-5 pb-3",children:[(0,e.jsx)(Ne,{className:"text-base",children:"Budget control plane"}),(0,e.jsx)(Ee,{children:"Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers."})]}),(0,e.jsxs)(ue,{className:"grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4",children:[(0,e.jsx)(je,{label:"Active incidents",value:String(Le.length),subtitle:"Open soft or hard threshold crossings",icon:$t}),(0,e.jsx)(je,{label:"Pending approvals",value:String(L?.pendingApprovalCount??0),subtitle:"Budget override approvals awaiting board action",icon:ft}),(0,e.jsx)(je,{label:"Paused agents",value:String(L?.pausedAgentCount??0),subtitle:"Agent heartbeats blocked by budget",icon:vt}),(0,e.jsx)(je,{label:"Paused projects",value:String(L?.pausedProjectCount??0),subtitle:"Project execution blocked by budget",icon:St})]})]}),Le.length>0?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold",children:"Active incidents"}),(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Resolve hard stops here by raising the budget or explicitly keeping the scope paused."})]}),(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:Le.map(o=>(0,e.jsx)(xs,{incident:o,isMutating:ie.isPending,onKeepPaused:a(()=>ie.mutate({incidentId:o.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:a(p=>ie.mutate({incidentId:o.id,action:"raise_budget_and_resume",amount:p}),"onRaiseAndResume")},o.id))})]}):null,(0,e.jsxs)("div",{className:"space-y-5",children:[["company","agent","project"].map(o=>{const p=en[o];return p.length===0?null:(0,e.jsxs)("section",{className:"space-y-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)("h2",{className:"text-lg font-semibold capitalize",children:[o==="company"?"organization":o," budgets"]}),(0,e.jsx)("p",{className:"text-sm text-ink-3",children:o==="company"?"Organization-wide monthly policy.":o==="agent"?"Recurring monthly spend policies for individual agents.":"Lifetime spend policies for execution-bound projects."})]}),(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:p.map(R=>(0,e.jsx)($n,{summary:R,onReservationChange:a(W=>he.mutate({summary:R,changes:{reservationCents:W}}),"onReservationChange"),onUnpricedUsagePolicyChange:a(W=>he.mutate({summary:R,changes:{unpricedUsagePolicy:W}}),"onUnpricedUsagePolicyChange"),isSaving:he.isPending,onSave:a(W=>he.mutate({summary:R,changes:{amount:W}}),"onSave")},R.policyId))})]},o)}),Ge.length===0?(0,e.jsx)(ne,{children:(0,e.jsx)(ue,{className:"px-5 py-8 text-sm text-ink-3",children:"No budget policies yet. Set agent and project budgets from their detail pages, or use the existing organization monthly budget control."})}):null]})]})]}),(0,e.jsx)(Me,{value:"providers",className:"mt-4 space-y-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(Je,{value:ot,onValueChange:y,children:[(0,e.jsx)(Dt,{items:Gs,value:ot}),(0,e.jsx)(Me,{value:"all",className:"mt-4",children:it.length===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No cost events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:it.map(o=>(0,e.jsx)(gs,{provider:o,rows:Ce.get(o)??[],budgetMonthlyCents:E?.summary.budgetCents??0,showBudgetUtilization:$==="mtd",totalCompanySpendCents:E?.summary.spendCents??0,weekSpendCents:ts.get(o)??0,windowRows:ns.get(o)??[],showDeficitNotch:os.get(o)??!1,quotaAccounts:Fe?.filter(p=>p.provider===o),quotaRequestFailed:!!at,quotaWindows:as.get(o)??[],quotaError:is.get(o)??null,quotaSource:rs.get(o)??null,quotaLoading:es},o))})}),it.map(o=>(0,e.jsx)(Me,{value:o,className:"mt-4",children:(0,e.jsx)(gs,{provider:o,rows:Ce.get(o)??[],budgetMonthlyCents:E?.summary.budgetCents??0,showBudgetUtilization:$==="mtd",totalCompanySpendCents:E?.summary.spendCents??0,weekSpendCents:ts.get(o)??0,windowRows:ns.get(o)??[],showDeficitNotch:os.get(o)??!1,quotaAccounts:Fe?.filter(p=>p.provider===o),quotaRequestFailed:!!at,quotaWindows:as.get(o)??[],quotaError:is.get(o)??null,quotaSource:rs.get(o)??null,quotaLoading:es})},o))]})})}),(0,e.jsx)(Me,{value:"billers",className:"mt-4 space-y-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(Je,{value:lt,onValueChange:b,children:[(0,e.jsx)(Dt,{items:Zs,value:lt}),(0,e.jsx)(Me,{value:"all",className:"mt-4",children:rt.length===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No billable events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:rt.map(o=>{const p=(De.get(o)??[])[0];if(!p)return null;const R=(nt??[]).filter(W=>W.biller===o);return(0,e.jsx)(ms,{row:p,weekSpendCents:ss.get(o)??0,budgetMonthlyCents:E?.summary.budgetCents??0,showBudgetUtilization:$==="mtd",totalCompanySpendCents:E?.summary.spendCents??0,providerRows:R},o)})})}),rt.map(o=>{const p=(De.get(o)??[])[0];if(!p)return null;const R=(nt??[]).filter(W=>W.biller===o);return(0,e.jsx)(Me,{value:o,className:"mt-4",children:(0,e.jsx)(ms,{row:p,weekSpendCents:ss.get(o)??0,budgetMonthlyCents:E?.summary.budgetCents??0,showBudgetUtilization:$==="mtd",totalCompanySpendCents:E?.summary.spendCents??0,providerRows:R})},o)})]})})}),(0,e.jsxs)(Me,{value:"finance",className:"mt-4 space-y-4",children:[B?.summary.providerReportedCentsExact!==void 0&&(0,e.jsxs)("p",{className:"text-sm text-ink-3",children:["Provider API cost reports: ",_(B.summary.providerReportedCents??0),". Report totals overlap invoices and run estimates and are shown separately from recorded charges."]}),Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):re?(0,e.jsx)(xt,{variant:"costs"}):ce&&!B?(0,e.jsx)("p",{className:"text-sm text-bad",children:"Financial events could not be loaded. Please try again shortly."}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(fs,{debitCents:B?.summary.debitCents??0,creditCents:B?.summary.creditCents??0,netCents:B?.summary.netCents??0,estimatedDebitCents:B?.summary.estimatedDebitCents??0,eventCount:B?.summary.eventCount??0}),(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-33)",children:[(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)(ne,{children:[(0,e.jsxs)(ye,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(Ne,{className:"text-base",children:"By biller"}),(0,e.jsx)(Ee,{children:"Account-level financial events grouped by who charged or credited them."})]}),(0,e.jsx)(ue,{className:"grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2",children:(B?.byBiller.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No finance events yet."}):B?.byBiller.map(o=>(0,e.jsx)(ma,{row:o},`${o.biller}:${o.currency}`))})]}),(0,e.jsx)(pa,{rows:Js})]}),(0,e.jsx)(xa,{rows:B?.byKind??[]})]})]})]})]})]})}a(vs,"Costs");function Fa(t){const s=new URLSearchParams;t.from&&s.set("from",t.from),t.to&&s.set("to",t.to),t.userId&&s.set("userId",t.userId),t.goalId&&s.set("goalId",t.goalId),t.projectId&&s.set("projectId",t.projectId),t.issueId&&s.set("issueId",t.issueId),t.limit&&s.set("limit",String(t.limit)),t.offset&&s.set("offset",String(t.offset));const n=s.toString();return n?`?${n}`:""}a(Fa,"query");var La={get:a((t,s={},n)=>de.get(`/companies/${t}/timeline${Fa(s)}`,n),"get")};function js(){const{setRouteRequestsCollapsed:t}=Pn();return(0,x.useEffect)(()=>(t(!0),()=>t(!1)),[t]),null}a(js,"RequestCollapsedSidebar");var Ba=new Set(["running","in_progress","queued","pending"]),Ua=new Set(["cancelled","canceled","aborted","skipped"]);function _a(t){return Ba.has(t)}a(_a,"isRunningStatus");function Ft(t){return Ua.has(t)}a(Ft,"isCancelledStatus");var Be={delegated:"#5b9bf6",automation:"#f4b740",cancelled:"#9aa3ad",now:"#2563eb"};function qa(t){return t.kickoff?"delegated":"automation"}a(qa,"barSourceKind");function _s(t){return Be[qa(t)]}a(_s,"barColor");function Oa(t){return t?.type??"system"}a(Oa,"actorType");function za(t){let s=0;for(let n=0;n<t.length;n++)s=s*31+t.charCodeAt(n)&4294967295;return`hsl(${Math.abs(s)%360} 62% 52%)`}a(za,"issueColor");function Wa(t){const s=t.trim().split(/\s+/).filter(Boolean);return s.length>=2?(s[0][0]+s[s.length-1][0]).toUpperCase():(t.slice(0,2)||"?").toUpperCase()}a(Wa,"shortLabel");function Pe(t){return new Date(t.start).getTime()}a(Pe,"spanStartMs$1");function Ye(t,s){return t.end?new Date(t.end).getTime():s}a(Ye,"spanEndMs$1");function Ka(t,s){return Math.abs(Pe(s)-new Date(t.at).getTime())}a(Ka,"kickoffEdgeRunDistanceMs");function bs(t,s){return`${t}\0${s}`}a(bs,"spanGroupKey");function Va(t,s){let n=null;for(const i of s){const r=Ka(t,i);(!n||r<n.distance||r===n.distance&&i.runId.localeCompare(n.span.runId)<0)&&(n={span:i,distance:r})}return n?.span.runId??null}a(Va,"closestRunForKickoffEdge");function Xa(t,s){const n=new Map;for(const r of t){const c=bs(r.actorId,r.issueId),l=n.get(c);l?l.push(r):n.set(c,[r])}const i=new Map;for(const r of s){const c=Va(r,n.get(bs(r.toActorId,r.issueId))??[]);c&&i.set(r,c)}return i}a(Xa,"buildClosestRunByKickoffEdge");function Ha(t,s,n,i){const r=Pe(t);let c=null;for(const l of s){if(l.toActorId!==t.actorId||l.issueId!==t.issueId||l.fromActorId===t.actorId)continue;const g=new Date(l.at).getTime(),h=g<=r?r-g:g-r+1e12;(!c||h<c.delta)&&(c={edge:l,delta:h})}return!c||i.get(c.edge)!==t.runId?null:n.get(c.edge.fromActorId)??null}a(Ha,"resolveKickoff");function Qa(t,s){const{pxPerMinute:n,gutter:i,rowH:r,barH:c,laneGap:l,nowMs:g}=s,h=new Date(t.window.from).getTime(),I=new Date(t.window.to).getTime(),f=new Map(t.actors.map(N=>[N.id,N])),u=Xa(t.spans,t.edges),y=a(N=>i+(N-h)/6e4*n,"x"),w=new Map,b=a((N,j)=>{const M=w.get(N);(M===void 0||j<M)&&w.set(N,j)},"noteActivity");for(const N of t.spans)b(N.actorId,Pe(N));const q=t.actors.filter(N=>w.has(N.id)).sort((N,j)=>w.get(N.id)-w.get(j.id)),$=[],K=new Map;for(const N of t.spans){const j=N.issueId;K.has(j)||($.push(j),K.set(j,N.issueIdentifier??N.issueTitle??"issue"))}const F=$.map(N=>({key:N,label:K.get(N),color:za(N)})),z=new Map,Y=[];let D=0;for(const N of q){const j=t.spans.filter(k=>k.actorId===N.id).sort((k,H)=>Pe(k)-Pe(H)),M=[],O=new Map;for(const k of j){const H=Pe(k),v=Ye(k,g);let X=-1;for(let Z=0;Z<M.length;Z++)if(M[Z]<=H){X=Z;break}X===-1?(X=M.length,M.push(v)):M[X]=v,O.set(k.runId,X)}const d=Math.max(1,M.length),U=Math.max(r,d*(c+l)+8),S=j.map(k=>{const H=O.get(k.runId)??0,v=D+6+H*(c+l),X=y(Pe(k)),Z=y(Ye(k,g)),L={span:k,x1:X,x2:Math.max(X+3,Z),yTop:v,yc:v+c/2,height:c,running:_a(k.status),kickoff:Ha(k,t.edges,f,u)};return z.set(k.runId,L),L}),le=[],ae=j.reduce((k,H)=>k+Math.max(0,Ye(H,g)-Pe(H)),0);Y.push({actor:N,y:D,h:U,laneCount:d,bars:S,markers:le,runCount:j.length,activeMs:ae}),D+=U}const V=[];for(const N of Y)for(const j of N.bars){const M=j.kickoff;if(!M||M.type==="user")continue;const O=Ya(M.id,j,z,g);O&&V.push({x1:O.x2,y1:O.yc,x2:j.x1,y2:j.yc,sourceRunId:O.span.runId,targetRunId:j.span.runId,dashed:!!j.span.retryOfRunId})}return{rows:Y,connectors:V,width:i+(I-h)/6e4*n+40,height:D+32,fromMs:h,toMs:I,gutter:i,pxPerMinute:n,issues:F}}a(Qa,"computeLayout");function Ya(t,s,n,i){const r=Pe(s.span);let c=null,l=null;for(const g of n.values()){if(g.span.actorId!==t||g===s)continue;const h=Ye(g.span,i);h>r+1||(g.span.issueId===s.span.issueId&&(!c||Ye(c.span,i)<h)&&(c=g),(!l||Ye(l.span,i)<h)&&(l=g))}return c??l}a(Ya,"nearestSourceBar");function Ga(t){const s=120/t,n=[15,30,60,120,180,360,720,1440,2880,10080];for(const i of n)if(i>=s)return i*6e4;return n[n.length-1]*6e4}a(Ga,"chooseTickStepMs");function qs(t,s){const n=Math.max(0,Math.round((s-t)/6e4));return n>=1440?`${Math.floor(n/1440)}d ${Math.floor(n%1440/60)}h`:n>=60?`${Math.floor(n/60)}h ${n%60}m`:`${n}m`}a(qs,"formatDuration");var Os={hour:60,day:1440,week:10080},Za=.08,Ja=12,et=960,ht=9e5;function yt(t){return Math.max(240,t-be.gutter-24)}a(yt,"plotViewportWidth");function ys(t,s,n){return Math.max(s,Math.min(n,t))}a(ys,"clampTime");function zs(t,s,n){const i=yt(n),r=ys(t.fromMs+s/t.pxPerMinute*6e4,t.fromMs,t.toMs),c=ys(t.fromMs+(s+i)/t.pxPerMinute*6e4,t.fromMs,t.toMs);return{fromMs:r,toMs:Math.max(r,c)}}a(zs,"visibleWindowForScroll");function Nt(t,s=et){return Ct(yt(s)/Os[t])}a(Nt,"zoomScaleForLevel");function kt(t,s=et){return Object.entries(Os).reduce((n,[i])=>Math.abs(Nt(i,s)-t)<Math.abs(Nt(n,s)-t)?i:n,"day")}a(kt,"nearestZoomForScale");function Ct(t){return Math.min(Ja,Math.max(Za,t))}a(Ct,"clampZoomScale");function Ns(t,s){const n=(s-t)/36e5;return n<=4?"hour":n<=48?"day":"week"}a(Ns,"defaultZoomForWindow");var be={gutter:176,rowH:34,barH:15,laneGap:4},Ws=11,ei=9;function Lt(t){const s=new Date(t),n=s.getMinutes()!==0;return s.toLocaleTimeString("en-US",{hour:"numeric",minute:n?"2-digit":void 0,hour12:!0})}a(Lt,"fmtClock");function ti(t,s){const n=new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric"});return s>=864e5?n:`${n}, ${Lt(t)}`}a(ti,"fmtTick");function si(t){const s=Math.max(1,Math.round(t));if(s>=10080&&s%10080===0){const n=s/10080;return`${n} week${n===1?"":"s"} visible`}if(s>=1440&&s%1440===0){const n=s/1440;return`${n} day${n===1?"":"s"} visible`}if(s>=1440){const n=Math.floor(s/1440),i=Math.round(s%1440/60);return`${n}d${i>0?` ${i}h`:""} visible`}if(s>=60&&s%60===0){const n=s/60;return`${n} hour${n===1?"":"s"} visible`}return s>=60?`${Math.floor(s/60)}h ${s%60}m visible`:`${s} minutes visible`}a(si,"formatVisibleDurationMinutes");function Qt(t,s=42){return t.length>s?`${t.slice(0,s-1)}…`:t}a(Qt,"truncate");function Bt(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}a(Bt,"svgFragmentId");function Ut({actor:t,cx:s,cy:n,r:i,clipId:r}){if(t.type==="agent"){const h=i>10?24:16,I=hn(t.appearance,t.id.replace(/^agent:/,""));return(0,e.jsx)("image",{"data-testid":"timeline-agent-icon",href:un(I,h,2),x:s-h/2,y:n-h/2,width:h,height:h,preserveAspectRatio:"xMidYMid meet"})}const c="var(--color-ink)",l=t.type==="system"?"var(--color-bg-3)":"var(--color-bg-2)",g=Wa(t.name);return t.type==="user"&&t.avatar?(0,e.jsxs)("g",{children:[(0,e.jsx)("defs",{children:(0,e.jsx)("clipPath",{id:r,children:(0,e.jsx)("circle",{cx:s,cy:n,r:i})})}),(0,e.jsx)("image",{"data-testid":"timeline-user-avatar-image",href:t.avatar,x:s-i,y:n-i,width:2*i,height:2*i,preserveAspectRatio:"xMidYMid slice",clipPath:`url(#${r})`}),(0,e.jsx)("circle",{cx:s,cy:n,r:i,fill:"none",stroke:c,strokeWidth:1.2,opacity:.5})]}):(0,e.jsxs)("g",{children:[t.type==="user"?(0,e.jsx)("rect",{x:s-i,y:n-i,width:2*i,height:2*i,rx:3,fill:l,stroke:c,strokeWidth:1.5}):(0,e.jsx)("circle",{cx:s,cy:n,r:i,fill:l,stroke:c,strokeWidth:1.5,strokeDasharray:t.type==="system"?"3 2":void 0}),(0,e.jsx)("text",{x:s,y:n+3.4,fontSize:i>10?9:8,textAnchor:"middle",fill:c,children:g})]})}a(Ut,"ActorGlyph");function ni({data:t,zoom:s,zoomScale:n,onZoomScaleChange:i,onVisibleRangeLabelChange:r,onVisibleWindowChange:c,nowMs:l}){const g=$s(),h=(0,x.useRef)(null),I=(0,x.useRef)(null),f=(0,x.useRef)(null),u=(0,x.useRef)(null),y=(0,x.useRef)(null),[w,b]=(0,x.useState)(null),[q,$]=(0,x.useState)(null),[K,F]=(0,x.useState)(0),[z,Y]=(0,x.useState)(0),[D,V]=(0,x.useState)(null),N=a(()=>{y.current?.(),y.current=null},"clearDocumentDrag"),j=a((m,T)=>{N();const P=a(A=>{N(),T(A)},"handleUp");document.addEventListener("mousemove",m),document.addEventListener("mouseup",P),y.current=()=>{document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",P)}},"setDocumentDrag");(0,x.useEffect)(()=>()=>N(),[]),u.current==null&&(u.current=Date.now());const M=l??u.current,O=n??Nt(s,z||et),d=(0,x.useMemo)(()=>Qa(t,{...be,pxPerMinute:O,nowMs:M}),[t,O,M]),U=(0,x.useMemo)(()=>{if(!q)return null;const m=new Set([q]);let T=!0;for(;T;){T=!1;for(const P of d.connectors)m.has(P.sourceRunId)&&!m.has(P.targetRunId)&&(m.add(P.targetRunId),T=!0),m.has(P.targetRunId)&&!m.has(P.sourceRunId)&&(m.add(P.sourceRunId),T=!0)}return m},[q,d.connectors]),S=(0,x.useMemo)(()=>U?d.connectors.filter(m=>U.has(m.sourceRunId)&&U.has(m.targetRunId)):[],[U,d.connectors]),le=yn(g.pathname),ae=a((m,T)=>{const P=d.gutter+(m-d.fromMs)/6e4*d.pxPerMinute;return Math.max(0,Math.min(d.width-T,P-T/2))},"timeToScrollLeft"),k=a(m=>{const T=m.scrollLeft+m.clientWidth/2;return d.fromMs+(T-d.gutter)/d.pxPerMinute*6e4},"scrollCenterMs");(0,x.useEffect)(()=>{const m=h.current;if(!m)return;const T=m.clientWidth;T>0&&T!==z&&Y(T);const P=`${t.window.from}:${t.window.to}`;if(I.current!==P){I.current=P;const A=Math.max(0,d.width-T);m.scrollLeft=A,F(A),f.current=k(m);return}if(f.current!=null){const A=ae(f.current,T);m.scrollLeft=A,F(A)}},[t.window.from,t.window.to,d.fromMs,d.gutter,d.pxPerMinute,d.toMs,d.width,z]),(0,x.useEffect)(()=>{r&&r(si(yt(z||et)/d.pxPerMinute))},[d.pxPerMinute,r,z]),(0,x.useEffect)(()=>{!c||z<=0||c(zs(d,K,z))},[d.fromMs,d.toMs,d.pxPerMinute,c,K,z]);const H=Ga(d.pxPerMinute),v=[],X=Math.ceil(d.fromMs/H)*H;for(let m=X;m<=d.toMs;m+=H)v.push(m);const Z=a(m=>{const T=jn(`/issues/${encodeURIComponent(m)}`,le);window.open(T,"_blank","noopener,noreferrer")},"openIssue"),L=a((m,T)=>{if(!i)return;const P=h.current,A=Math.max(d.fromMs,Math.min(d.toMs,m)),B=Math.max(d.fromMs,Math.min(d.toMs,T)),re=Math.min(A,B),ce=Math.max(ht,Math.max(A,B)-re),C=re+ce/2,se=P?.clientWidth||z||et,ve=Ct(yt(se)/(ce/6e4));f.current=C,i(ve,kt(ve,se))},"updateVisibleRange"),pe=a((m,T)=>{const P=T.getBoundingClientRect();if(P.width<=0)return d.gutter;const A=(m-P.left)/P.width*d.width;return Math.max(d.gutter,Math.min(d.width-40,A))},"svgXFromClientX"),me=a(m=>d.fromMs+(m-d.gutter)/d.pxPerMinute*6e4,"msFromSvgX"),Se=a(m=>{if(!i||m.button!==0)return;const T=m.currentTarget,P=pe(m.clientX,T);m.preventDefault(),b(null),$(null),V({anchorX:P,currentX:P}),j(a(re=>{V(ce=>ce&&{...ce,currentX:pe(re.clientX,T)})},"move"),a(re=>{const ce=pe(re.clientX,T);if(V(null),Math.abs(ce-P)<8)return;const C=Math.min(me(P),me(ce)),se=Math.max(me(P),me(ce));L(C,se)},"up"))},"handlePlotMouseDown"),he=a(m=>{const T=d.connectors.filter(P=>P.sourceRunId===m.span.runId||P.targetRunId===m.span.runId);return T.length===0?null:T.some(P=>P.dashed)?"dashed handoff: retry or changes requested":"solid handoff: delegation or assignment"},"connectorHintForBar"),ie=a((m,T)=>{$(T.span.runId),b({x:m.clientX,y:m.clientY,bar:T,connectorHint:he(T)})},"showTooltip"),E=a(m=>{if(!i||!(m.ctrlKey||m.metaKey||m.altKey))return;m.preventDefault();const T=h.current;T&&(f.current=k(T));const P=Ct(d.pxPerMinute*Math.exp(-m.deltaY*.001));i(P,kt(P,T?.clientWidth??z))},"handleWheel");return(0,e.jsxs)("div",{className:"relative",children:[(0,e.jsx)("div",{ref:h,className:"max-h-(--sz-70vh) overflow-auto","data-testid":"work-timeline-scroll",onScroll:a(m=>{F(m.currentTarget.scrollLeft),f.current=k(m.currentTarget)},"onScroll"),onWheel:E,children:(0,e.jsxs)("div",{className:"relative",style:{width:d.width,height:d.height},children:[(0,e.jsx)(ai,{rows:d.rows,height:d.height}),(0,e.jsxs)("svg",{width:d.width,height:d.height,viewBox:`0 0 ${d.width} ${d.height}`,className:"absolute inset-0 block select-none",onMouseDown:Se,ref:a(m=>{m&&z===0&&h.current&&Y(h.current.clientWidth)},"ref"),children:[(0,e.jsx)("defs",{children:(0,e.jsxs)("linearGradient",{id:"tl-fade",x1:"0",y1:"0",x2:"1",y2:"0",children:[(0,e.jsx)("stop",{offset:"0%",stopColor:"var(--color-ink)",stopOpacity:.28}),(0,e.jsx)("stop",{offset:"100%",stopColor:"var(--color-ink)",stopOpacity:0})]})}),d.rows.map((m,T)=>(0,e.jsx)("rect",{x:0,y:m.y+32,width:d.width,height:m.h,fill:T%2?"var(--color-bg-3)":"transparent",opacity:T%2?.35:1},`bg-${m.actor.id}`)),v.map(m=>{const T=d.gutter+(m-d.fromMs)/6e4*d.pxPerMinute;return(0,e.jsx)("g",{children:(0,e.jsx)("line",{x1:T,y1:32,x2:T,y2:d.height,stroke:"var(--color-line)",strokeWidth:1})},`tick-${m}`)}),M>=d.fromMs&&M<=d.toMs&&(0,e.jsx)("line",{x1:d.gutter+(M-d.fromMs)/6e4*d.pxPerMinute,y1:32,x2:d.gutter+(M-d.fromMs)/6e4*d.pxPerMinute,y2:d.height,stroke:Be.now,strokeWidth:1.5,strokeDasharray:"2 3",opacity:.9}),(0,e.jsx)("line",{x1:d.gutter,y1:0,x2:d.gutter,y2:d.height,stroke:"var(--color-ink)",strokeWidth:1.5}),(0,e.jsx)("line",{x1:0,y1:32,x2:d.width,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5}),S.map((m,T)=>{const P=m.y1+32,A=m.y2+32,B=m.x2>=m.x1?`M${m.x2},${A} l-10,-5 l0,10 z`:`M${m.x2},${A} l10,-5 l0,10 z`;return(0,e.jsxs)("g",{"data-testid":"timeline-connector",opacity:.86,children:[(0,e.jsx)("path",{d:`M${m.x1},${P} V${A} H${m.x2}`,fill:"none",stroke:"var(--color-ink)",strokeWidth:2.2,strokeDasharray:m.dashed?"5 4":void 0}),(0,e.jsx)("circle",{cx:m.x1,cy:P,r:3.2,fill:"var(--color-ink)"}),(0,e.jsx)("path",{d:B,fill:"var(--color-ink)"})]},`edge-${m.sourceRunId}-${m.targetRunId}-${T}`)}),d.rows.map(m=>{const T=m.y+32+m.h/2,P=Bt(`plot-${m.actor.id}`);return(0,e.jsxs)("g",{children:[(0,e.jsx)(Ut,{actor:m.actor,cx:26,cy:T,r:Ws,clipId:P}),(0,e.jsx)("text",{x:47,y:T+4,fontSize:13,fill:"var(--color-ink)",children:Qt(m.actor.name,18)}),Array.from({length:m.laneCount}).map((A,B)=>{const re=m.y+32+6+B*(be.barH+be.laneGap)+be.barH/2;return(0,e.jsx)("line",{x1:d.gutter,y1:re,x2:d.width-8,y2:re,stroke:"var(--color-line)",strokeWidth:1,strokeDasharray:"2 4",opacity:.6},`lane-${m.actor.id}-${B}`)}),m.bars.map(A=>{const B=A.yTop+32,re=A.x2-A.x1,ce=Ft(A.span.status),C=_s(A),se=U==null?"idle":U.has(A.span.runId)?"connected":"faded",ve=se==="idle"?.88:se==="connected"?1:.22;return(0,e.jsxs)("g",{opacity:se==="faded"?.42:1,children:[(0,e.jsxs)("g",{className:"cursor-pointer","data-run-id":A.span.runId,"data-connected-state":se,onMouseEnter:a(Ae=>ie(Ae,A),"onMouseEnter"),onMouseOver:a(Ae=>ie(Ae,A),"onMouseOver"),onMouseMove:a(Ae=>ie(Ae,A),"onMouseMove"),onMouseLeave:a(()=>{b(null),$(null)},"onMouseLeave"),onMouseDown:a(Ae=>Ae.stopPropagation(),"onMouseDown"),onClick:a(()=>Z(A.span.issueId),"onClick"),children:[(0,e.jsx)("rect",{x:A.x1,y:B,width:re,height:A.height,rx:3,fill:ce?"transparent":C,stroke:ce?Be.cancelled:"var(--color-ink)",strokeWidth:1.5,strokeDasharray:ce?"4 3":void 0,opacity:ve}),A.running&&!ce&&re>8&&(0,e.jsx)("rect",{x:A.x2-Math.min(re-2,26),y:B+1.5,width:Math.min(re-2,26),height:A.height-3,fill:"url(#tl-fade)"})]}),A.kickoff&&Oa(A.kickoff)==="user"&&(0,e.jsx)("g",{className:"pointer-events-none","data-testid":"timeline-kickoff-chip",children:(0,e.jsx)(Ut,{actor:A.kickoff,cx:A.x1,cy:B+A.height/2,r:ei,clipId:Bt(`kickoff-${A.span.runId}-${A.kickoff.id}`)})})]},A.span.runId)})]},`row-${m.actor.id}`)}),D&&(0,e.jsx)("rect",{"data-testid":"timeline-drag-selection",x:Math.min(D.anchorX,D.currentX),y:32,width:Math.abs(D.currentX-D.anchorX),height:d.height-32,fill:"var(--color-accent)",opacity:.16,stroke:"var(--color-accent)",strokeWidth:1.5,pointerEvents:"none"})]})]})}),(0,e.jsx)(ii,{layout:d,ticks:v,stepMs:H,scrollLeft:K}),(0,e.jsx)(oi,{layout:d,scrollRef:h,viewportW:z,scrollLeft:K,onVisibleRangeChange:L}),w&&(0,e.jsx)(ri,{tooltip:w,now:M})]})}a(ni,"WorkTimelineChart");function ai({rows:t,height:s}){return(0,e.jsxs)("svg",{"aria-hidden":"true","data-testid":"work-timeline-actor-gutter",width:be.gutter,height:s,viewBox:`0 0 ${be.gutter} ${s}`,className:"sticky left-0 z-20 block bg-bg-2",children:[(0,e.jsx)("rect",{x:0,y:0,width:be.gutter,height:s,fill:"var(--color-bg-2)"}),t.map((n,i)=>{const r=n.y+32+n.h/2,c=Bt(`gutter-${n.actor.id}`);return(0,e.jsxs)("g",{children:[(0,e.jsx)("rect",{x:0,y:n.y+32,width:be.gutter,height:n.h,fill:i%2?"var(--color-bg-3)":"var(--color-bg-2)",opacity:i%2?.35:1}),(0,e.jsx)(Ut,{actor:n.actor,cx:26,cy:r,r:Ws,clipId:c}),(0,e.jsx)("text",{x:47,y:r+4,fontSize:13,fill:"var(--color-ink)",children:Qt(n.actor.name,16)})]},`gutter-${n.actor.id}`)}),(0,e.jsx)("line",{x1:be.gutter,y1:0,x2:be.gutter,y2:s,stroke:"var(--color-ink)",strokeWidth:1.5}),(0,e.jsx)("line",{x1:0,y1:32,x2:be.gutter,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5})]})}a(ai,"ActorGutter");function ii({layout:t,ticks:s,stepMs:n,scrollLeft:i}){return(0,e.jsxs)("div",{"aria-hidden":"true","data-testid":"work-timeline-time-axis",className:"pointer-events-none absolute left-0 right-0 top-0 z-30 overflow-hidden bg-bg-2",style:{height:32},children:[(0,e.jsxs)("svg",{width:t.width,height:32,viewBox:`0 0 ${t.width} 32`,className:"block",style:{transform:`translateX(${-i}px)`},children:[(0,e.jsx)("rect",{x:0,y:0,width:t.width,height:32,fill:"var(--color-bg-2)"}),s.map(r=>{const c=t.gutter+(r-t.fromMs)/6e4*t.pxPerMinute;return(0,e.jsxs)("g",{children:[(0,e.jsx)("line",{x1:c,y1:25,x2:c,y2:32,stroke:"var(--color-line)",strokeWidth:1}),(0,e.jsx)("text",{x:c+3,y:19,fontSize:11,fill:"var(--color-ink-3)",children:ti(r,n)})]},`axis-tick-${r}`)}),(0,e.jsx)("line",{x1:0,y1:32,x2:t.width,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5})]}),(0,e.jsxs)("svg",{width:t.gutter,height:32,viewBox:`0 0 ${t.gutter} 32`,className:"absolute left-0 top-0 block bg-bg-2",children:[(0,e.jsx)("rect",{x:0,y:0,width:t.gutter,height:32,fill:"var(--color-bg-2)"}),(0,e.jsx)("line",{x1:t.gutter,y1:0,x2:t.gutter,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5}),(0,e.jsx)("line",{x1:0,y1:32,x2:t.gutter,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5})]})]})}a(ii,"TimeAxisOverlay");function ri({tooltip:t,now:s}){const{bar:n}=t,i=new Date(n.span.start).getTime(),r=n.span.end?new Date(n.span.end).getTime():s,c=n.span.issueTitle??n.span.issueIdentifier??"run",l=Math.min(t.x+14,(typeof window<"u"?window.innerWidth:1200)-300);return(0,e.jsxs)("div",{className:"pointer-events-none fixed z-50 max-w-(--sz-280px) rounded-md border border-ink bg-bg-2 px-2.5 py-2 text-xs shadow-md",style:{left:l,top:t.y+14},children:[(0,e.jsx)("div",{className:"text-(length:--text-compact) font-medium text-ink",children:Qt(c)}),(0,e.jsxs)("div",{className:"mt-0.5 text-ink-3",children:[Lt(i),"–",n.span.end?Lt(r):"now"," · ",qs(i,r)," ·"," ",(0,e.jsx)("span",{className:"font-medium text-ink",children:n.span.status})]}),n.kickoff&&(0,e.jsxs)("div",{className:"text-ink-3",children:["kicked off by: ",n.kickoff.name,n.span.retryOfRunId?" · retry":""]}),t.connectorHint&&(0,e.jsx)("div",{className:"text-ink-3",children:t.connectorHint})]})}a(ri,"Tooltip");function oi({layout:t,scrollRef:s,viewportW:n,scrollLeft:i,onVisibleRangeChange:r}){const c=(0,x.useRef)(null),l=Math.max(320,n||900),g=54,h=8,I=t.toMs-t.fromMs||1,f=a(j=>h+(j-t.fromMs)/I*(l-16),"mx"),u=new Map(t.rows.map((j,M)=>[j.actor.id,M])),y=38/Math.max(1,t.rows.length),w=zs(t,i,n||l),b=w.fromMs,q=w.toMs,$=f(b),K=Math.max(24,f(q)-$),F=14,z=a(()=>{c.current?.(),c.current=null},"clearDocumentDrag"),Y=a((j,M)=>{z();const O=a(d=>{z(),M(d)},"handleUp");document.addEventListener("mousemove",j),document.addEventListener("mouseup",O),c.current=()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",O)}},"setDocumentDrag");(0,x.useEffect)(()=>()=>z(),[]);const D=a((j,M)=>{const O=M.getBoundingClientRect(),d=Math.min(1,Math.max(0,(j-O.left-h)/(l-16)));return t.fromMs+d*I},"msAtClientX"),V=a((j,M)=>{const O=D(j,M);s.current&&(s.current.scrollLeft=t.gutter+(O-t.fromMs)/6e4*t.pxPerMinute-s.current.clientWidth/2)},"seek"),N=a((j,M)=>{M.preventDefault(),M.stopPropagation();const O=M.currentTarget.ownerSVGElement;if(!O)return;const d=b,U=q,S=Math.max(ht,U-d);Y(a(ae=>{const k=D(ae.clientX,O);if(j==="left")r(Math.min(k,U-ht),U);else if(j==="right")r(d,Math.max(k,d+ht));else{const H=Math.max(t.fromMs,Math.min(t.toMs-S,k-S/2));r(H,H+S)}},"move"),()=>{})},"startRangeDrag");return(0,e.jsx)("div",{className:"mt-2 border-t border-line bg-bg-2 px-3.5 py-2",children:(0,e.jsxs)("svg",{width:l,height:g,viewBox:`0 0 ${l} ${g}`,className:"block cursor-grab active:cursor-grabbing",onMouseDown:a(j=>{const M=j.currentTarget;V(j.clientX,M),Y(a(d=>V(d.clientX,M),"move"),()=>{})},"onMouseDown"),children:[(0,e.jsx)("rect",{x:0,y:0,width:l,height:g,fill:"var(--color-bg-2)",stroke:"var(--color-ink)",strokeWidth:1.5}),t.rows.flatMap(j=>j.bars.map(M=>{const O=new Date(M.span.start).getTime(),d=M.span.end?new Date(M.span.end).getTime():t.toMs,U=h+(u.get(j.actor.id)??0)*y;return(0,e.jsx)("rect",{x:f(O),y:U+1,width:Math.max(2,f(d)-f(O)),height:Math.max(2,y-2),fill:Ft(M.span.status)?Be.cancelled:_s(M),opacity:Ft(M.span.status)?.5:1},`mm-${M.span.runId}`)})),(0,e.jsx)("rect",{x:$,y:1,width:K,height:52,fill:"var(--color-ink)",opacity:.12,stroke:"var(--color-ink)",strokeWidth:1.5,onMouseDown:a(j=>N("move",j),"onMouseDown")}),(0,e.jsx)(ks,{x:$,y:1,height:52,width:F,testId:"timeline-minimap-left-handle",label:"Drag left edge to resize visible range",onMouseDown:a(j=>N("left",j),"onMouseDown")}),(0,e.jsx)(ks,{x:$+K,y:1,height:52,width:F,testId:"timeline-minimap-right-handle",label:"Drag right edge to resize visible range",onMouseDown:a(j=>N("right",j),"onMouseDown")})]})})}a(oi,"MiniMap");function ks({x:t,y:s,width:n,height:i,testId:r,label:c,onMouseDown:l}){const g=t-n/2,h=s+i/2-7;return(0,e.jsxs)("g",{"data-testid":r,className:"cursor-grab active:cursor-grabbing",onMouseDown:l,children:[(0,e.jsx)("title",{children:c}),(0,e.jsx)("rect",{x:g,y:s,width:n,height:i,rx:3,fill:"var(--color-ink)",opacity:.16}),(0,e.jsx)("line",{x1:t-3,y1:h,x2:t-3,y2:h+14,stroke:"var(--color-ink)",strokeWidth:1.5,opacity:.85}),(0,e.jsx)("line",{x1:t,y1:h,x2:t,y2:h+14,stroke:"var(--color-ink)",strokeWidth:1.5,opacity:.85}),(0,e.jsx)("line",{x1:t+3,y1:h,x2:t+3,y2:h+14,stroke:"var(--color-ink)",strokeWidth:1.5,opacity:.85})]})}a(ks,"MiniMapHandle");var Cs=500;function li(t){return`${t.actorId}\0${t.kind}\0${t.issueId}\0${t.at}`}a(li,"timelineEventKey");function ci(t){return`${t.fromActorId}\0${t.toActorId}\0${t.issueId}\0${t.at}\0${t.kind}`}a(ci,"timelineEdgeKey");async function di(t,s,n){const i=new Map,r=new Map,c=new Map,l=new Map;let g=0,h=null,I=0,f=!1;for(;;){const u=await La.get(t,{...s,limit:Cs,offset:g},{signal:n});h??=u,I=Math.max(I,u.pagination.totalIssues),f||=u.window.capped;for(const w of u.actors)i.set(w.id,w);for(const w of u.spans)r.set(w.runId,w);for(const w of u.events)c.set(li(w),w);for(const w of u.edges)l.set(ci(w),w);if(!u.pagination.hasMore)break;const y=u.pagination.offset+u.pagination.limit;if(y<=g)throw new Error("Timeline pagination did not advance");g=y}if(!h)throw new Error("Timeline response was empty");return{actors:Array.from(i.values()),spans:Array.from(r.values()),events:Array.from(c.values()),edges:Array.from(l.values()),pagination:{limit:Cs,offset:0,totalIssues:I,hasMore:!1},window:{...h.window,capped:f}}}a(di,"loadTimelineWindow");function ut(t){return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}a(ut,"dateInputValue");function ws(t,s=new Date){const n=new Date(s),i=new Date(s);return t==="today"?{fromDate:ut(n),toDate:ut(i)}:(n.setDate(n.getDate()-(t==="7d"?6:29)),{fromDate:ut(n),toDate:ut(i)})}a(ws,"presetRange");function Ks(t){if(!t.fromDate||!t.toDate)return null;const s=new Date(`${t.fromDate}T00:00:00`),n=new Date(`${t.toDate}T23:59:59.999`);return Number.isNaN(s.getTime())||Number.isNaN(n.getTime())||s>n?null:{from:s.toISOString(),to:n.toISOString()}}a(Ks,"rangeWindow");function ui(t){return!t.fromDate||!t.toDate?"Choose a start and end date.":Ks(t)?null:"Start date must be before end date."}a(ui,"rangeError");function Ms(t){return new Intl.NumberFormat("en-US").format(t)}a(Ms,"formatInteger");function mi(t){return new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(t)}a(mi,"formatCompactInteger");function xi(t){return new Date(t.start).getTime()}a(xi,"spanStartMs");function pi(t,s){return t.end?new Date(t.end).getTime():s}a(pi,"spanEndMs");function hi(t,s,n,i){const r=xi(t),c=pi(t,s);return{clippedMs:Math.max(0,Math.min(c,i)-Math.max(r,n)),rawMs:Math.max(0,c-r)}}a(hi,"spanWindowOverlap");function gi(t,s,n){const i=t.usage?.totalTokens??0;return i<=0||n<=0?0:s<=0||n>=s?i:Math.round(i*(n/s))}a(gi,"spanWindowTokens");function _t(t){return{fromMs:new Date(t.window.from).getTime(),toMs:new Date(t.window.to).getTime()}}a(_t,"dataWindow");function fi(t,s=_t(t)){const n=new Map(t.actors.map(f=>[f.id,f])),i=new Set,r=_t(t),c=Math.max(r.fromMs,Math.min(r.toMs,s.fromMs)),l=Math.max(c,Math.min(r.toMs,s.toMs));let g=0,h=0,I=0;for(const f of t.spans){const u=hi(f,r.toMs,c,l);u.clippedMs<=0||(I+=1,n.get(f.actorId)?.type==="agent"&&i.add(f.actorId),g+=u.clippedMs,h+=gi(f,u.rawMs,u.clippedMs))}return{runs:I,agents:i.size,activeMs:g,totalTokens:h}}a(fi,"timelineSummary");function vi({value:t,options:s,onChange:n}){return(0,e.jsx)("div",{role:"group",className:"inline-flex items-center gap-0.5 rounded-md border border-line-strong bg-bg-2 p-0.5",children:s.map(i=>(0,e.jsx)(Xn,{selected:t===i.value,onClick:a(()=>n(i.value),"onClick"),children:i.label},i.value))})}a(vi,"Segmented");function ji(){return(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-line px-3.5 py-2 text-xs text-ink-3",children:[(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{className:"h-2.5 w-4 rounded-sm",style:{backgroundColor:Be.delegated}}),"Delegated"]}),(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{className:"h-2.5 w-4 rounded-sm",style:{backgroundColor:Be.automation}}),"Automation"]}),(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{className:"h-2.5 w-4 rounded-sm border border-dashed bg-transparent",style:{borderColor:Be.cancelled}}),"Cancelled"]}),(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{className:"h-3.5 w-0.5",style:{backgroundColor:Be.now}}),"Now"]})]})}a(ji,"TimelineLegend");function bi({summary:t}){const s=[{label:"Runs",value:Ms(t.runs),icon:We},{label:"Agents",value:Ms(t.agents),icon:kn},{label:"Run time",value:qs(0,t.activeMs),icon:Yn},{label:"Tokens used",value:t.totalTokens>0?mi(t.totalTokens):"Not tracked",icon:vt}];return(0,e.jsx)("dl",{className:"grid flex-1 grid-cols-2 gap-3 border-y border-line py-3 md:grid-cols-4",children:s.map(n=>{const i=n.icon;return(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("dt",{className:"flex items-center gap-1.5 text-xs text-ink-3",children:[(0,e.jsx)(i,{className:"h-3.5 w-3.5 shrink-0"}),(0,e.jsx)("span",{children:n.label})]}),(0,e.jsx)("dd",{className:"mt-1 truncate text-lg font-semibold tabular-nums text-ink",children:n.value})]},n.label)})})}a(bi,"TimelineSummaryStats");function yi({embedded:t=!1}={}){const{selectedCompanyId:s}=Kt(),{setBreadcrumbs:n}=Xt(),i=$s(),r=(0,x.useMemo)(()=>new URLSearchParams(i.search).get("projectId")||void 0,[i.search]),[c,l]=(0,x.useState)("day"),[g,h]=(0,x.useState)(void 0),I=(0,x.useRef)(!1),[f,u]=(0,x.useState)("7d"),[y,w]=(0,x.useState)(()=>ws("7d")),[b,q]=(0,x.useState)(null);(0,x.useEffect)(()=>{t||n([{label:r?"Project Timeline":"Timeline"}])},[t,r,n]);const $=ui(y),K=(0,x.useMemo)(()=>{const d=Ks(y);return d?r?{...d,projectId:r}:d:null},[y,r]),{data:F,isLoading:z,error:Y}=oe({queryKey:[...J.workTimeline(s??""),y.fromDate,y.toDate,r??null],queryFn:a(({signal:d})=>di(s,K,d),"queryFn"),enabled:!!s&&!!K});(0,x.useEffect)(()=>{if(!F||I.current)return;const d=Ns(new Date(F.window.from).getTime(),new Date(F.window.to).getTime());l(d),h(void 0)},[F]),(0,x.useEffect)(()=>{q(null)},[F?.window.from,F?.window.to]);const D=(0,x.useCallback)(d=>{q(U=>U?.fromMs===d.fromMs&&U.toMs===d.toMs?U:d)},[]);if(!s)return(0,e.jsxs)(e.Fragment,{children:[!t&&(0,e.jsx)(js,{}),(0,e.jsx)(Re,{icon:We,message:"Select an organization to view its work timeline."})]});const V=(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(We,{className:"h-6 w-6 text-ink-3"}),(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:r?"Project Timeline":"Work Timeline"})]}),N=a(d=>{I.current=!0;const U=Ct((g??Nt(c))*d);h(U),l(kt(U))},"adjustZoom"),j=a(()=>{I.current=!0,l(F?Ns(new Date(F.window.from).getTime(),new Date(F.window.to).getTime()):"day"),h(void 0)},"resetZoom"),M=F?fi(F,b??_t(F)):null,O=(0,e.jsxs)("label",{className:"flex min-w-0 flex-wrap items-center gap-2 text-xs text-ink-3",children:["Range",(0,e.jsx)(vi,{value:f,onChange:a(d=>{d!=="custom"&&(u(d),w(ws(d)))},"onChange"),options:[{value:"today",label:"Today"},{value:"7d",label:"7 days"},{value:"30d",label:"30 days"}]}),(0,e.jsx)(qe,{type:"date",value:y.fromDate,onChange:a(d=>{u("custom"),w(U=>({...U,fromDate:d.target.value}))},"onChange"),className:"h-8 w-(--sz-150px) text-xs","aria-label":"Timeline start date"}),(0,e.jsx)("span",{children:"to"}),(0,e.jsx)(qe,{type:"date",value:y.toDate,onChange:a(d=>{u("custom"),w(U=>({...U,toDate:d.target.value}))},"onChange"),className:"h-8 w-(--sz-150px) text-xs","aria-label":"Timeline end date"})]});return(0,e.jsxs)("div",{className:"space-y-6",children:[!t&&(0,e.jsx)(js,{}),V,(0,e.jsxs)("div",{className:"flex flex-wrap items-start gap-3",children:[M&&(0,e.jsx)(bi,{summary:M}),(0,e.jsxs)("div",{className:"ml-auto flex items-center gap-1 pt-3","aria-label":"Timeline zoom controls",children:[(0,e.jsx)(te,{type:"button",variant:"secondary",size:"icon-xs",onClick:a(()=>N(.8),"onClick"),"aria-label":"Zoom out",title:"Zoom out",children:(0,e.jsx)(Mn,{className:"h-3 w-3"})}),(0,e.jsx)(te,{type:"button",variant:"secondary",size:"icon-xs",onClick:a(()=>N(1.25),"onClick"),"aria-label":"Zoom in",title:"Zoom in",children:(0,e.jsx)(Tn,{className:"h-3 w-3"})}),(0,e.jsx)(te,{type:"button",variant:"secondary",size:"icon-xs",onClick:j,"aria-label":"Reset zoom",title:"Reset zoom",children:(0,e.jsx)(In,{className:"h-3 w-3"})})]})]}),z&&(0,e.jsx)(xt,{}),$&&(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(Re,{icon:We,message:$}),(0,e.jsx)("div",{className:"flex flex-wrap items-center justify-end gap-3",children:O})]}),Y&&(0,e.jsx)(Re,{icon:We,message:"Couldn't load the timeline. The aggregation endpoint may be unavailable."}),F&&!z&&!$&&(F.spans.length===0?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(Re,{icon:We,message:r?"No project activity in this window.":"No activity in this window."}),(0,e.jsx)("div",{className:"flex flex-wrap items-center justify-end gap-3",children:O})]}):(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsxs)(ne,{className:"block py-0",children:[(0,e.jsx)(ji,{}),(0,e.jsx)(ni,{data:F,zoom:c,zoomScale:g,onVisibleWindowChange:D,onZoomScaleChange:a((d,U=kt(d))=>{I.current=!0,h(d),l(U)},"onZoomScaleChange")})]}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:[F.spans.length," run",F.spans.length===1?"":"s"," ·"," ",new Date(F.window.from).toLocaleString()," to ",new Date(F.window.to).toLocaleString(),F.window.capped?" · window capped":""]}),O]})]}))]})}a(yi,"Timeline");function Ss(t){const s=new URLSearchParams;return t.actorScope&&s.set("actorScope",t.actorScope),t.agentId&&s.set("agentId",t.agentId),t.responsibleUserId&&s.set("responsibleUserId",t.responsibleUserId),t.runId&&s.set("runId",t.runId),t.entityType&&s.set("entityType",t.entityType),t.entityId&&s.set("entityId",t.entityId),t.action&&s.set("action",t.action),t.from&&s.set("from",t.from),t.to&&s.set("to",t.to),t.actorType&&s.set("actorType",t.actorType),t.cursor&&s.set("cursor",t.cursor),t.limit!=null&&s.set("limit",String(t.limit)),s}a(Ss,"buildAuditQuery");var Ts={listAgentActions:a((t,s={})=>{const n=Ss(s).toString();return de.get(`/companies/${t}/audit/agent-actions${n?`?${n}`:""}`)},"listAgentActions"),exportAgentActionsCsv:a(async(t,s={})=>{const n=Ss(s).toString(),i=await fetch(`/api/companies/${t}/audit/agent-actions.csv${n?`?${n}`:""}`,{credentials:"include",headers:{Accept:"text/csv"}});if(!i.ok){const r=(await i.json().catch(()=>null))?.error??`Export failed: ${i.status}`;throw new Error(r)}return i.blob()},"exportAgentActionsCsv")},Ni=50,ee="__all",ki=[{value:ee,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_",label:"Apps & tools"},{value:"cost.",label:"Costs"},{value:"company.",label:"Organization"}],Ci=[{value:ee,label:"All entities"},{value:"issue",label:"Task"},{value:"agent",label:"Agent"},{value:"heartbeat_run",label:"Run"},{value:"routine",label:"Routine"},{value:"project",label:"Project"},{value:"goal",label:"Goal"},{value:"company",label:"Organization"},{value:"tool_connection",label:"Connection"}];function wi(t){if(!t)return;const s=new Date(`${t}T00:00:00.000Z`);return Number.isNaN(s.getTime())?void 0:s.toISOString()}a(wi,"toStartIso");function Mi(t){if(!t)return;const s=new Date(`${t}T23:59:59.999Z`);return Number.isNaN(s.getTime())?void 0:s.toISOString()}a(Mi,"toEndIso");function Si({record:t,agentMap:s,userProfileMap:n}){const i=t.agentId??(t.actorType==="agent"?t.actorId:null),r=i?s.get(i):null;if(r)return(0,e.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:r.name,children:[(0,e.jsx)("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-bg-3 text-ink-3",children:(0,e.jsx)(Rn,{agent:r,size:16,className:"h-3 w-3"})}),(0,e.jsx)("span",{className:"truncate font-medium text-ink",children:r.name})]});if(t.actorType==="user"&&t.actorId){const l=n.get(t.actorId);return(0,e.jsx)(At,{name:l?.label??"User",avatarUrl:l?.image??null,size:"sm",className:"font-medium text-ink"})}const c=t.actorType==="plugin"?"Plugin":t.actorType==="agent"?"Agent":t.actorType==="user"?"User":"System";return(0,e.jsx)(At,{name:c,size:"sm",className:"font-medium text-ink"})}a(Si,"AuditActor");function Ti({record:t}){const{issue:s,document:n}=t.entity,i=s?.identifier??s?.id??null;if(i)return(0,e.jsx)(_e,{to:`/issues/${i}`,className:"font-medium text-accent hover:underline",children:s?.identifier?`${s.identifier}${s.title?` · ${s.title}`:""}`:"the task"});if(n)return(0,e.jsx)("span",{className:"font-medium text-ink",children:n.key});const r=t.entityType==="tool_connection"?t.entityId:typeof t.details?.connectionId=="string"?t.details.connectionId:null;return r?(0,e.jsx)(_e,{to:`/apps/${r}/permissions`,className:"font-medium text-accent hover:underline",children:"the connection"}):(0,e.jsx)("span",{className:"text-ink-3",children:t.entityType})}a(Ti,"AuditEntityNode");function Ii({record:t,agentMap:s,userProfileMap:n}){const i=Zn(t.action,t.details,{agentMap:s,userProfileMap:n}),r=t.responsibleUserId?n.get(t.responsibleUserId):null,c=!!(t.responsibleUserId&&!(t.actorType==="user"&&t.actorId===t.responsibleUserId)),l=r?.label??(t.responsibleUserId?"a user":null),g=t.entity.comment?.excerpt?.trim(),h=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-ink",children:[(0,e.jsx)(Si,{record:t,agentMap:s,userProfileMap:n}),(0,e.jsx)("span",{className:"text-ink-3",children:i}),(0,e.jsx)(Ti,{record:t})]}),g?(0,e.jsxs)("p",{className:"line-clamp-2 border-l-2 border-line pl-2 text-ink-3",children:["“",g,"”"]}):null,h?(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:["Document ",(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro)",children:h})]}):null,(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-ink-3",children:[c&&l?(0,e.jsxs)("span",{className:"inline-flex items-center rounded-full bg-bg-3 px-2 py-0.5",children:["on behalf of ",l]}):null,t.runId&&t.agentId?(0,e.jsx)(_e,{to:`/agents/${t.agentId}/runs/${t.runId}`,className:"text-accent 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-ink-3",dateTime:t.createdAt,title:new Date(t.createdAt).toLocaleString(),children:Ot(t.createdAt)})]})})}a(Ii,"AuditRow");function Ai(){return(0,e.jsx)(ne,{children:(0,e.jsxs)(ue,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)(Dn,{className:"h-10 w-10 text-ink-3/50"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-sm font-medium text-ink",children:"Agent audit is a Wardmote Enterprise view"}),(0,e.jsxs)("p",{className:"mx-auto mt-1 max-w-md text-sm text-ink-3",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."]})]})]})})}a(Ai,"AuditUpsell");function Di({companyId:t,lockedAgentId:s,lockedRunId:n,lockedEntity:i,hideHeader:r,mode:c,onModeChange:l,actionDomain:g,onActionDomainChange:h}){const{pushToast:I}=En(),[f,u]=(0,x.useState)(ee),[y,w]=(0,x.useState)(ee),[b,q]=(0,x.useState)(ee),$=g??b,K=a(C=>{q(C),h?.(C)},"setActionDomain"),[F,z]=(0,x.useState)(ee),[Y,D]=(0,x.useState)(""),[V,N]=(0,x.useState)(""),[j,M]=(0,x.useState)(!1),[O,d]=(0,x.useState)(!1),U=oe({queryKey:J.agents.list(t),queryFn:a(()=>Rs.list(t),"queryFn")}),S=oe({queryKey:J.access.companyUserDirectory(t),queryFn:a(()=>On.listUserDirectory(t),"queryFn"),retry:!1}),le=(0,x.useMemo)(()=>new Map((U.data??[]).map(C=>[C.id,C])),[U.data]),ae=(0,x.useMemo)(()=>Gn(S.data?.users),[S.data]),k=s||n?"agents":c??"all",H=!!(s||n||i),v={actorScope:k,agentId:s??(f===ee?void 0:f),runId:n,responsibleUserId:y===ee?void 0:y,action:$===ee?void 0:$,entityType:i?.type??(F===ee?void 0:F),entityId:i?.id,from:wi(Y),to:Mi(V)},X=!!(!s&&f!==ee||y!==ee||$!==ee||F!==ee||Y||V),Z=!H&&(f!==ee||y!==ee),L=vn({queryKey:J.audit.agentActions(t,{actorScope:v.actorScope,agentId:v.agentId,runId:v.runId,responsibleUserId:v.responsibleUserId,action:v.action,entityType:v.entityType,entityId:v.entityId,from:v.from,to:v.to}),queryFn:a(({pageParam:C})=>Ts.listAgentActions(t,{...v,limit:Ni,cursor:C??void 0}),"queryFn"),initialPageParam:null,getNextPageParam:a(C=>C.nextCursor??void 0,"getNextPageParam"),retry:a((C,se)=>!(se instanceof cs&&se.status===403)&&C<2,"retry")}),pe=L.error instanceof cs&&L.error.status===403,me=L.data?.pages.some(C=>C.accessTier==="basic")??!1,Se=L.data?.pages.some(C=>C.accessTier==="full")??!1,he=(0,x.useMemo)(()=>{const C=L.data?.pages??[];return(me?C.filter(se=>se.accessTier!=="full"):C).flatMap(se=>se.items)},[L.data,me]),ie=me?"basic":L.data?.pages[0]?.accessTier,E=me&&Se,m=s||n?!0:ie==="full",T=!!(E&&O&&!L.isFetching),P=!!(!H&&!T&&(pe&&Z||E)),A=!!(pe&&!H&&k==="agents"&&l),B=!!(!H&&l&&!A);(0,x.useEffect)(()=>{A&&l?.("all")},[A,l]),(0,x.useEffect)(()=>{!H&&(ie==="basic"||P)&&(u(ee),w(ee))},[ie,H,P]),(0,x.useEffect)(()=>{if(!E){O&&d(!1);return}O||(d(!0),L.refetch())},[O,L,E]);const re=a(()=>{u(ee),w(ee),K(ee),z(ee),D(""),N("")},"clearFilters"),ce=a(async()=>{M(!0);try{const C=await Ts.exportAgentActionsCsv(t,{actorScope:v.actorScope,agentId:v.agentId,runId:v.runId,responsibleUserId:v.responsibleUserId,action:v.action,entityType:v.entityType,entityId:v.entityId,from:v.from,to:v.to}),se=URL.createObjectURL(C),ve=document.createElement("a");ve.href=se,ve.download=`${k==="agents"?"agent-audit":"activity"}-${t}.csv`,document.body.appendChild(ve),ve.click(),ve.remove(),window.setTimeout(()=>URL.revokeObjectURL(se),5e3),I({title:"Audit exported",body:"Your CSV download has started.",tone:"success"})}catch(C){I({title:"Export failed",body:C instanceof Error?C.message:"Could not export the audit log.",tone:"error"})}finally{M(!1)}},"handleExport");return pe&&!P&&!A?(0,e.jsx)(Ai,{}):(0,e.jsxs)("div",{className:"space-y-4",children:[r?null:(0,e.jsx)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold text-ink",children:"Activity"}),(0,e.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-ink-3",children:k==="agents"?"Every recorded agent action, newest first — with the responsible person and run behind each one.":"Everything happening in your organization, newest first — people, agents, and the system. Each line is one recorded action."})]})}),B?(0,e.jsx)(Je,{value:k,onValueChange:a(C=>l?.(C),"onValueChange"),children:(0,e.jsxs)(Ps,{"aria-label":"Activity scope",children:[(0,e.jsx)($e,{value:"all",children:"Activity"}),(0,e.jsx)($e,{value:"agents",disabled:ie==="basic",title:ie==="basic"?"Agent Actions requires audit access":void 0,children:"Agent Actions"})]})}):null,H?(0,e.jsx)("div",{className:"border-y border-line px-1 py-2 text-xs text-ink-3",children:n?`Scoped to run ${n.slice(0,8)}`:s?"Scoped to one agent":`Scoped to ${i?.label??i?.type??"entity"}`}):null,(0,e.jsxs)("div",{className:"flex flex-wrap items-end gap-3 border-y border-line py-3",children:[m&&!s&&!n?(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Agent"}),(0,e.jsxs)(Ke,{value:f,onValueChange:u,children:[(0,e.jsx)(Ve,{className:"w-40",children:(0,e.jsx)(He,{placeholder:"Agent"})}),(0,e.jsxs)(Xe,{children:[(0,e.jsx)(Ie,{value:ee,children:"All agents"}),(U.data??[]).map(C=>(0,e.jsx)(Ie,{value:C.id,children:C.name},C.id))]})]})]}):null,m?(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Responsible user"}),(0,e.jsxs)(Ke,{value:y,onValueChange:w,children:[(0,e.jsx)(Ve,{className:"w-52",children:(0,e.jsx)(He,{placeholder:"Responsible user"})}),(0,e.jsxs)(Xe,{children:[(0,e.jsx)(Ie,{value:ee,children:"All responsible users"}),(S.data?.users??[]).map(C=>(0,e.jsx)(Ie,{value:C.principalId,children:C.user?.name??C.user?.email??C.principalId.slice(0,8)},C.principalId))]})]})]}):null,(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Action"}),(0,e.jsxs)(Ke,{value:$,onValueChange:K,children:[(0,e.jsx)(Ve,{className:"w-40",children:(0,e.jsx)(He,{placeholder:"Action"})}),(0,e.jsx)(Xe,{children:ki.map(C=>(0,e.jsx)(Ie,{value:C.value,children:C.label},C.value))})]})]}),i?null:(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Entity"}),(0,e.jsxs)(Ke,{value:F,onValueChange:z,children:[(0,e.jsx)(Ve,{className:"w-40",children:(0,e.jsx)(He,{placeholder:"Entity"})}),(0,e.jsx)(Xe,{children:Ci.map(C=>(0,e.jsx)(Ie,{value:C.value,children:C.label},C.value))})]})]}),(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"From"}),(0,e.jsx)(qe,{type:"date","aria-label":"From date",value:Y,max:V||void 0,onChange:a(C=>D(C.target.value),"onChange"),className:"w-36"})]}),(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"To"}),(0,e.jsx)(qe,{type:"date","aria-label":"To date",value:V,min:Y||void 0,onChange:a(C=>N(C.target.value),"onChange"),className:"w-36"})]}),X?(0,e.jsx)(te,{variant:"ghost",size:"sm",onClick:re,children:"Clear filters"}):null,m?(0,e.jsxs)(te,{variant:"secondary",size:"sm",className:"ml-auto",onClick:ce,disabled:j||L.isLoading||he.length===0,children:[(0,e.jsx)(Hn,{className:"mr-1.5 h-4 w-4"}),j?"Exporting…":"Export CSV"]}):null]}),P||A?(0,e.jsx)(ne,{children:(0,e.jsx)(ue,{className:"py-14 text-center text-sm text-ink-3",children:"Refreshing audit access…"})}):L.isLoading?(0,e.jsx)(ne,{children:(0,e.jsx)(ue,{className:"py-14 text-center text-sm text-ink-3",children:"Loading…"})}):L.error?(0,e.jsx)(ne,{children:(0,e.jsxs)(ue,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-ink-3",children:L.error instanceof Error?L.error.message:"Failed to load the audit log."}),(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>L.refetch(),"onClick"),children:"Try again"})]})}):he.length===0?(0,e.jsx)(ne,{children:(0,e.jsxs)(ue,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)(An,{className:"h-10 w-10 text-ink-3/40"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-sm font-medium text-ink",children:X?"No actions match these filters":"Nothing here yet"}),(0,e.jsx)("p",{className:"mt-1 max-w-md text-sm text-ink-3",children:X?"Try a wider date range or different filters.":k==="agents"?"As soon as your agents start doing things, their actions show up here.":"As soon as anyone in your organization does something, it shows up here."})]}),X?(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:re,children:"Clear filters"}):null]})}):(0,e.jsx)("div",{className:"border-y border-line",children:(0,e.jsx)("ul",{className:wt("divide-y divide-line"),"aria-label":"Audit activity",children:he.map(C=>(0,e.jsx)(Ii,{record:C,agentMap:le,userProfileMap:ae},C.id))})}),L.hasNextPage?(0,e.jsx)("div",{className:"flex justify-center",children:(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>L.fetchNextPage(),"onClick"),disabled:L.isFetchingNextPage,children:L.isFetchingNextPage?"Loading…":"Load more"})}):null,(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Recorded by Wardmote — entries can't be edited. Sensitive values are never stored."})]})}a(Di,"AuditFeed");var ge="__all",gt=200;function $i(t){const s=t.resultJson,n=s?.summary??s?.result??t.error;return typeof n=="string"&&n.trim()?n.trim():null}a($i,"runSummary");function Pi(t){const s=t.startedAt?new Date(t.startedAt).getTime():null,n=t.finishedAt?new Date(t.finishedAt).getTime():null;if(s==null||n==null||!Number.isFinite(s)||!Number.isFinite(n))return null;const i=Math.max(0,Math.round((n-s)/1e3));return i<60?`${i}s`:`${Math.floor(i/60)}m ${i%60}s`}a(Pi,"runDuration");function tt(t){return t.replaceAll("_"," ")}a(tt,"readableSource");function Ri(t){return t.linkedIssue?.title??t.trigger?.label??"Routine run"}a(Ri,"routineRunTitle");function Ei({runs:t,isLoading:s,error:n,onRetry:i}){return s?(0,e.jsx)("div",{className:"border-y border-line py-14 text-center text-sm text-ink-3",children:"Loading routine runs…"}):n?(0,e.jsxs)("div",{className:"flex flex-col items-center gap-3 border-y border-line py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-ink-3",children:n.message}),(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:i,children:"Try again"})]}):t.length===0?(0,e.jsx)(Re,{icon:Vt,message:"No routine runs yet."}):(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold text-ink",children:"Routine runs"}),(0,e.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-ink-3",children:"Executions created by this routine, newest first."})]}),(0,e.jsx)("ul",{className:"divide-y divide-line border-y border-line","aria-label":"Routine runs",children:t.map(r=>{const c=(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)("span",{className:"font-medium text-ink",children:Ri(r)}),(0,e.jsx)(Ht,{status:r.status})]}),(0,e.jsx)("p",{className:"mt-1 truncate text-sm text-ink-3",children:r.trigger?.label??tt(r.source)})]}),(0,e.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-ink-3 sm:justify-end",children:[(0,e.jsx)("span",{className:"capitalize",children:tt(r.source)}),(0,e.jsx)("time",{dateTime:new Date(r.triggeredAt).toISOString(),children:Ot(r.triggeredAt)})]})]}),l="flex flex-col gap-2 px-1 py-3 text-inherit no-underline transition-colors hover:bg-bg-3/50 sm:flex-row sm:items-start sm:justify-between sm:px-3";return(0,e.jsx)("li",{children:r.linkedIssue?(0,e.jsx)(_e,{to:`/issues/${r.linkedIssue.identifier??r.linkedIssue.id}`,className:l,children:c}):(0,e.jsx)("div",{className:l,children:c})},r.id)})}),(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:["Showing the ",gt," most recent routine runs."]})]})}a(Ei,"RoutineScopedRuns");function Fi({companyId:t,routineId:s}){const[n,i]=Wt(),r=n.get("agentId")??ge,c=n.get("runStatus")??ge,l=oe({queryKey:J.agents.list(t),queryFn:a(()=>Rs.list(t),"queryFn"),enabled:!s}),g=oe({queryKey:J.audit.runs(t,r===ge?null:r),queryFn:a(()=>Fn.list(t,r===ge?void 0:r,gt,{summary:!0}),"queryFn"),refetchInterval:15e3,enabled:!s}),h=oe({queryKey:[...J.routines.runs(s??""),"audit"],queryFn:a(()=>mt.listRuns(s,gt),"queryFn"),enabled:!!s,refetchInterval:15e3}),I=(0,x.useMemo)(()=>new Map((l.data??[]).map(b=>[b.id,b])),[l.data]),f=(0,x.useMemo)(()=>Array.from(new Set((g.data??[]).map(b=>b.status))).sort(),[g.data]),u=(0,x.useMemo)(()=>(g.data??[]).filter(b=>c===ge||b.status===c),[g.data,c]),y=a((b,q)=>{i($=>{const K=new URLSearchParams($);return q===ge?K.delete(b):K.set(b,q),K},{replace:!0})},"updateFilter"),w=a(()=>{i(b=>{const q=new URLSearchParams(b);return q.delete("agentId"),q.delete("runStatus"),q},{replace:!0})},"clearFilters");return s?(0,e.jsx)(Ei,{runs:h.data??[],isLoading:h.isLoading,error:h.error instanceof Error?h.error:null,onRetry:a(()=>{h.refetch()},"onRetry")}):(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold text-ink",children:"Runs"}),(0,e.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-ink-3",children:"Recent agent executions across the organization. Open a run to inspect its transcript, output, and task context."})]}),(0,e.jsxs)("div",{className:"flex flex-wrap items-end gap-3 border-y border-line py-3",children:[(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Agent"}),(0,e.jsxs)(Ke,{value:r,onValueChange:a(b=>y("agentId",b),"onValueChange"),children:[(0,e.jsx)(Ve,{className:"w-48",children:(0,e.jsx)(He,{placeholder:"All agents"})}),(0,e.jsxs)(Xe,{children:[(0,e.jsx)(Ie,{value:ge,children:"All agents"}),(l.data??[]).map(b=>(0,e.jsx)(Ie,{value:b.id,children:b.name},b.id))]})]})]}),(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Status"}),(0,e.jsxs)(Ke,{value:c,onValueChange:a(b=>y("runStatus",b),"onValueChange"),children:[(0,e.jsx)(Ve,{className:"w-40",children:(0,e.jsx)(He,{placeholder:"All statuses"})}),(0,e.jsxs)(Xe,{children:[(0,e.jsx)(Ie,{value:ge,children:"All statuses"}),f.map(b=>(0,e.jsx)(Ie,{value:b,children:tt(b)},b))]})]})]}),r!==ge||c!==ge?(0,e.jsx)(te,{variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}):null]}),g.isLoading?(0,e.jsx)("div",{className:"border-y border-line py-14 text-center text-sm text-ink-3",children:"Loading runs…"}):g.error?(0,e.jsxs)("div",{className:"flex flex-col items-center gap-3 border-y border-line py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-ink-3",children:g.error instanceof Error?g.error.message:"Failed to load runs."}),(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>g.refetch(),"onClick"),children:"Try again"})]}):u.length===0?(0,e.jsx)(Re,{icon:r!==ge||c!==ge?sa:Vt,message:r!==ge||c!==ge?"No runs match these filters.":"No runs yet."}):(0,e.jsx)("ul",{className:"divide-y divide-line border-y border-line","aria-label":"Recent runs",children:u.map(b=>{const q=I.get(b.agentId),$=$i(b),K=Pi(b);return(0,e.jsx)("li",{children:(0,e.jsxs)(_e,{to:`/agents/${b.agentId}/runs/${b.id}`,className:"flex flex-col gap-2 px-1 py-3 text-inherit no-underline transition-colors hover:bg-bg-3/50 sm:flex-row sm:items-start sm:justify-between sm:px-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)("span",{className:"font-medium text-ink",children:q?.name??"Unknown agent"}),(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro) text-ink-3",children:b.id.slice(0,8)}),(0,e.jsx)(Ht,{status:b.status})]}),(0,e.jsx)("p",{className:"mt-1 truncate text-sm text-ink-3",children:$??`${tt(b.invocationSource)} run`})]}),(0,e.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-ink-3 sm:justify-end",children:[(0,e.jsx)("span",{className:"capitalize",children:tt(b.invocationSource)}),K?(0,e.jsx)("span",{children:K}):null,(0,e.jsx)("time",{dateTime:new Date(b.createdAt).toISOString(),children:Ot(b.createdAt)})]})]})},b.id)})}),(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:["Showing the ",gt," most recent runs."]})]})}a(Fi,"AuditRuns");function Li({companyId:t,routineId:s}){const n=oe({queryKey:[...J.routines.activity(t,s),"audit"],queryFn:a(async()=>{const[r,c]=await Promise.all([mt.get(s),mt.listRuns(s,200)]);return mt.activity(t,s,{triggerIds:r.triggers.map(l=>l.id),runIds:c.map(l=>l.id)})},"queryFn")});if(n.isLoading)return(0,e.jsx)("div",{className:"border-y border-line py-14 text-center text-sm text-ink-3",children:"Loading routine activity…"});if(n.error)return(0,e.jsxs)("div",{className:"flex flex-col items-center gap-3 border-y border-line py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-ink-3",children:n.error instanceof Error?n.error.message:"Failed to load routine activity."}),(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>n.refetch(),"onClick"),children:"Try again"})]});const i=n.data??[];return i.length===0?(0,e.jsx)(Re,{icon:Vt,message:"No routine activity yet."}):(0,e.jsx)("div",{className:"border-y border-line","aria-label":"Routine activity",children:i.map(r=>(0,e.jsx)(ta,{event:r},r.id))})}a(Li,"RoutineAuditActivity");function Rr({section:t}){const s=bn(),{selectedCompanyId:n}=Kt(),{setBreadcrumbs:i}=Xt(),[r,c]=Wt(),l=zn(r),g=l.mode==="agents"?"agents":"all",h=l.entityType==="routine"?l.entityId??void 0:void 0,I=r.get("action"),f=["issue.","agent.","heartbeat.","approval.","project.","goal.","tool_","cost.","company."].includes(I??"")?I:"__all";(0,x.useEffect)(()=>{const w=ds.find(b=>b.value===t);i([{label:"Audit",href:t==="activity"?void 0:"/activity"},...t==="activity"||!w?[]:[{label:w.label}]])},[t,i]);const u=(0,x.useCallback)(w=>{c(b=>{const q=new URLSearchParams(b);return w==="agents"?q.set("mode","agents"):q.delete("mode"),q},{replace:!0})},[c]),y=(0,x.useCallback)(w=>{c(b=>{const q=new URLSearchParams(b);return w==="__all"?q.delete("action"):q.set("action",w),q},{replace:!0})},[c]);return n?(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsx)("div",{children:(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight text-ink",children:"Audit"})}),(0,e.jsx)(Je,{value:t,onValueChange:a(w=>{s(Wn(w,l))},"onValueChange"),children:(0,e.jsx)(Dt,{items:ds,value:t,align:"start"})}),t==="activity"&&h?(0,e.jsx)(Li,{companyId:n,routineId:h}):t==="activity"?(0,e.jsx)(Di,{companyId:n,hideHeader:!0,mode:g,onModeChange:u,actionDomain:f,onActionDomainChange:y,lockedAgentId:l.agentId??void 0,lockedRunId:l.runId??void 0,lockedEntity:l.entityType&&l.entityId?{type:l.entityType,id:l.entityId}:void 0}):t==="runs"?(0,e.jsx)(Fi,{companyId:n,routineId:h}):t==="budgets"?(0,e.jsx)(vs,{embedded:!0,initialTab:"budgets",lockTab:!0}):t==="timeline"?(0,e.jsx)(yi,{embedded:!0}):(0,e.jsx)(vs,{embedded:!0,initialTab:"overview",hideBudgetsTab:!0})]}):(0,e.jsx)(Re,{icon:Vn,message:"Select an organization to view Audit."})}a(Rr,"AuditHub");export{Rr as AuditHub};
|
|
1
|
+
var on=Object.defineProperty;var a=(t,s)=>on(t,"name",{value:s,configurable:!0});import{i as Is}from"./rolldown-runtime-ZpX3ckPj.js";import{D as qt,E as ke,Mt as ln,O as Ot,bn as cn,c as zt,d as As,f as _,g as dn,h as Qe,l as wt,mn as un,na as mn,t as Ds,ta as xn,u as pn,vn as hn,x as Q,yn as gn}from"./createLucideIcon-B-uEJvX6.js";import{h as $s,y as Wt}from"./star-BXywPGTx.js";import{X as fn,_ as Ze,n as cs,r as de,t as J,v as oe}from"./queryKeys-yuC-YxZI.js";import{t as vn}from"./useInfiniteQuery-KaGSl9U6.js";import{n as Kt}from"./CompanyContext-DDgccGSs.js";import{l as jn,o as bn,t as _e,u as yn}from"./router-2HX_SyKK.js";import{t as ze}from"./label-CPQI5V7i.js";import{i as $e,n as Me,r as Ps,t as Je}from"./tabs-BP71y3CO.js";import{t as Vt}from"./activity-BwjvcZxv.js";import{t as Nn}from"./arrow-down-left-Bbtqoesi.js";import{t as ft}from"./arrow-up-right-Who3c6Eu.js";import{t as kn}from"./bot-B76w73ks.js";import{t as Cn}from"./chevron-down-B_rMrTLq.js";import{t as wn}from"./chevron-right-DDmPvaMb.js";import{t as vt}from"./coins-DOScIoKX.js";import{t as te}from"./button-D3bYvq4T.js";import{t as Mn}from"./minus-BICJQjhd.js";import{t as Sn}from"./octagon-alert-GkcxkXei.js";import{t as Tn}from"./plus-BbX1VFl1.js";import{t as In}from"./rotate-ccw-axI90MQW.js";import{t as An}from"./scroll-text-DkybSLN1.js";import{t as Dn}from"./shield-alert-CE3cG15R.js";import{t as $n}from"./BudgetPolicyCard-B6DX8U3d.js";import{r as Pn}from"./SidebarContext-CQAYTXv1.js";import{t as st}from"./badge-Dz4tmpgp.js";import"./agent-avatar-url-BIEMYowR.js";import{t as At}from"./Identity-J7JnIwUT.js";import{t as Rn}from"./AgentAvatar-B4hORIPc.js";import{a as En}from"./ToastContext-BL2cptrZ.js";import{t as Rs}from"./agents-DjsXf9UL.js";import{t as Fn}from"./heartbeats-xPg7ZEsm.js";import{a as Ln,n as Bn,r as Un,s as _n,t as qn}from"./dialog-DlsqN-fP.js";import{t as qe}from"./input-It0utqV7.js";import{t as On}from"./access-RvWIoVKp.js";import{t as Ue}from"./skeleton-BrYUg3zU.js";import{n as zn,r as Wn,t as ds}from"./audit-navigation-IalprBz0.js";import{t as mt}from"./routines-5Q3z9LWd.js";import{n as Xt}from"./BreadcrumbContext-_dNLeVnD.js";import{t as Kn}from"./AgentIdentity-DysUzsFa.js";import{i as Ie,n as Ke,o as Ve,r as Xe,s as He}from"./select-DKYWrP8G.js";import{i as Ee,o as ye,r as ue,s as Ne,t as ne}from"./card-CtkberpO.js";import{Dn as Ht,E as Re,Ra as Vn,Yt as Xn,eo as Hn,io as Qn,no as Yn,oi as Dt,si as Es,sr as Gn,to as St,v as xt,za as $t}from"./index-CSIXA5y5.js";import{t as Zn}from"./activity-format-BNHOXlUD.js";import{t as Jn}from"./decision-models-DGwWNl8R.js";import{t as ea}from"./fast-responses-DfTJsIyW.js";import{t as Tt}from"./budgets-Dh83JquC.js";import{t as ta}from"./RoutineActivityRow-BKtWtOsg.js";import{t as jt}from"./QuotaBar-t5jmdx0g.js";var Fs={name:"circle-dot-dashed",size:24,node:[["path",{d:"M10.1 2.18a9.93 9.93 0 0 1 3.8 0",key:"1qdqn0"}],["path",{d:"M17.6 3.71a9.95 9.95 0 0 1 2.69 2.7",key:"1bq7p6"}],["path",{d:"M21.82 10.1a9.93 9.93 0 0 1 0 3.8",key:"1rlaqf"}],["path",{d:"M20.29 17.6a9.95 9.95 0 0 1-2.7 2.69",key:"1xk03u"}],["path",{d:"M13.9 21.82a9.94 9.94 0 0 1-3.8 0",key:"l7re25"}],["path",{d:"M6.4 20.29a9.95 9.95 0 0 1-2.69-2.7",key:"1v18p6"}],["path",{d:"M2.18 13.9a9.93 9.93 0 0 1 0-3.8",key:"xdo6bj"}],["path",{d:"M3.71 6.4a9.95 9.95 0 0 1 2.7-2.69",key:"1jjmaz"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]};Fs.node;var sa=Ds(Fs),Ls={name:"square-chart-gantt",size:24,node:[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 8h7",key:"kbo1nt"}],["path",{d:"M8 12h6",key:"ikassy"}],["path",{d:"M11 16h5",key:"oq65wt"}]],aliases:["gantt-chart-square","square-gantt-chart"]};Ls.node;var We=Ds(Ls),x=Is(mn(),1),e=Is(xn(),1);function Bs({entries:t,fastResponse:s=!1,connectionsEnabled:n=!0}){return t.length?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Recent requests. Inputs are not retained."}),(0,e.jsx)("div",{className:"overflow-x-auto",children:(0,e.jsxs)("table",{className:"w-full text-sm","aria-label":s?"Fast responses":"Decision requests",children:[(0,e.jsx)("thead",{children:(0,e.jsx)("tr",{className:"border-b border-line text-ink-3",children:["When / feature","Responsible","Task",...s?["Connection"]:[],"Model","Status","Duration","Tokens in / out","Cost"].map(i=>(0,e.jsx)("th",{className:"px-3 py-2 text-left font-medium",children:i},i))})}),(0,e.jsx)("tbody",{children:t.map(i=>(0,e.jsxs)("tr",{className:"border-b border-line last:border-0",children:[(0,e.jsxs)("td",{className:"px-3 py-3",children:[(0,e.jsx)("div",{className:"whitespace-nowrap",children:Qe(i.startedAt)}),(0,e.jsx)("div",{className:"text-xs text-ink-3",children:i.feature==="settings.test"?"Setup test":i.feature})]}),(0,e.jsx)("td",{className:"px-3 py-3",children:i.actorType==="system"?"Wardmote services":i.userName??(i.responsibleUserId==="local-board"?"Board":"Former user")}),(0,e.jsx)("td",{className:"px-3 py-3",children:i.issueId?(0,e.jsx)(_e,{className:"underline underline-offset-4",to:`/issues/${i.issueIdentifier??i.issueId}`,children:i.issueIdentifier??"View task"}):"—"}),s&&(0,e.jsx)("td",{className:"px-3 py-3",children:i.connectionName??(i.connectionId?"Removed connection":"—")}),(0,e.jsx)("td",{className:"px-3 py-3 font-mono text-xs",children:i.model}),(0,e.jsxs)("td",{className:"px-3 py-3",children:[(0,e.jsx)("div",{children:i.status==="succeeded"?"Succeeded":i.status==="running"?"Running":i.status==="unknown"?"Unresolved":i.status==="skipped"?"Skipped":i.status==="pending"?"Pending":"Failed"}),i.publicationStatus&&(0,e.jsx)("div",{className:"text-xs text-ink-3",children:i.publicationStatus}),i.errorCode&&(0,e.jsx)("div",{className:"text-xs text-ink-3",children:i.errorCode.replaceAll("_"," ")})]}),(0,e.jsx)("td",{className:"px-3 py-3 font-mono",children:i.durationMs===null?"—":`${(i.durationMs/1e3).toFixed(1)}s`}),(0,e.jsxs)("td",{className:"whitespace-nowrap px-3 py-3 font-mono",children:[i.inputTokens===null?"—":Q(i.inputTokens)," / ",i.outputTokens===null?"—":Q(i.outputTokens)]}),(0,e.jsxs)("td",{className:"px-3 py-3 font-mono",children:[(0,e.jsx)("div",{children:i.costCents===null?"Unknown":dn(i.costCents)}),i.costStatus!=="unpriced"&&i.costStatus&&(0,e.jsx)("span",{className:"text-xs text-ink-3",children:i.costStatus==="estimated"?"Estimated":"Reported"})]})]},i.id))})]})})]}):(0,e.jsxs)("p",{className:"text-sm text-ink-3",children:[s?"No fast responses in this period.":"No decision requests in this period."," ",(0,e.jsx)(_e,{to:n?"/company/settings/connections":s?"/company/settings/instance/features":"/company/settings",className:"underline underline-offset-4",children:s?n?"Configure fast response":"Turn on fast replies":"Configure a decision model"})," to run a test."]})}a(Bs,"DecisionHistoryTable");function na({companyId:t,from:s,to:n}){const{enabled:i}=Es(),r=oe({queryKey:["decision-history",t,s,n],queryFn:a(()=>Jn.history(t,s,n),"queryFn"),refetchInterval:a(c=>c.state.data?.some(l=>l.status==="running")?5e3:!1,"refetchInterval")});return r.isPending?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Loading decision requests…"}):r.error?(0,e.jsxs)("div",{role:"alert",className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-sm text-bad",children:"Could not load decision requests."}),(0,e.jsx)(te,{variant:"secondary",onClick:a(()=>{r.refetch()},"onClick"),children:"Try again"})]}):(0,e.jsx)(Bs,{entries:r.data??[],connectionsEnabled:i})}a(na,"DecisionHistory");function aa({companyId:t,from:s,to:n}){const{enabled:i}=Es(),r=oe({queryKey:["fast-response-history",t,s,n],queryFn:a(()=>ea.history(t,s??void 0,n??void 0),"queryFn"),refetchInterval:a(c=>c.state.data?.some(l=>["pending","running"].includes(l.status)||["pending","streaming","retry"].includes(l.publicationStatus))?3e3:!1,"refetchInterval")});return r.isPending?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Loading fast responses…"}):r.error?(0,e.jsxs)("div",{role:"alert",children:[(0,e.jsx)("p",{className:"text-sm text-bad",children:"Could not load fast responses."}),(0,e.jsx)(te,{variant:"secondary",onClick:a(()=>{r.refetch()},"onClick"),children:"Try again"})]}):(0,e.jsx)(Bs,{entries:r.data??[],fastResponse:!0,connectionsEnabled:i})}a(aa,"FastResponseHistory");var bt={report(t,s,n){const i=new URLSearchParams;return s&&i.set("from",s),n&&i.set("to",n),!s&&!n&&i.set("period","all"),de.get(`/companies/${t}/costs/subscriptions?${i}`)},refresh:a(t=>de.post(`/companies/${t}/costs/subscriptions/refresh`,{}),"refresh"),update:a((t,s,n)=>de.patch(`/companies/${t}/costs/subscriptions/${s}`,n),"update"),link:a((t,s,n,i,r)=>de.post(`/companies/${t}/costs/subscriptions/${s}/link`,{targetId:n,expectedRevision:i,targetRevision:r}),"link")};function us(t,s){return s==="USD"?_(Number(t)):new Intl.NumberFormat(void 0,{style:"currency",currency:s,currencyDisplay:"code"}).format(Number(t)/100)}a(us,"subscriptionMoney");function Pt({usage:t}){return(0,e.jsxs)("span",{className:"font-mono text-xs text-ink-3",children:[Q(t.inputTokens+t.cachedInputTokens)," in · ",Q(t.outputTokens)," out",t.cachedInputTokens>0&&(0,e.jsxs)("span",{className:"block",children:[Q(t.cachedInputTokens)," input cached"]})]})}a(Pt,"SubscriptionTokenUsage");function ia({account:t,accounts:s,companyId:n,onDone:i}){const[r,c]=(0,x.useState)(t.price.plan),[l,g]=(0,x.useState)(t.price.amountCents==null?"":gn(t.price.amountCents).replace(/\.?0+$/,"")),[h,I]=(0,x.useState)(t.price.currency),[f,u]=(0,x.useState)(t.price.cadence),[y,w]=(0,x.useState)(t.price.status),[b,q]=(0,x.useState)(""),$=Ze({mutationFn:a(()=>bt.update(n,t.id,{expectedRevision:t.price.revision,plan:r,amountCents:l.trim()?cn(l.trim()):null,currency:h,cadence:f,status:y}),"mutationFn"),onSuccess:i}),K=Ze({mutationFn:a(()=>bt.link(n,t.id,b,t.price.revision,s.find(D=>D.id===b).price.revision),"mutationFn"),onSuccess:i}),F=s.filter(D=>D.id!==t.id&&D.provider===t.provider&&D.canEdit),z=$.isPending||K.isPending,Y="h-9 rounded-md border border-line-strong bg-bg px-3 text-sm";return(0,e.jsxs)("div",{className:"space-y-5",children:[(0,e.jsxs)("form",{className:"space-y-4",onSubmit:a(D=>{D.preventDefault(),$.mutate()},"onSubmit"),children:[(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-plan",children:"Plan"}),(0,e.jsx)(qe,{id:"subscription-plan",value:r,onChange:a(D=>c(D.target.value),"onChange"),required:!0,maxLength:100})]}),(0,e.jsxs)("div",{className:"grid gap-4 sm:grid-cols-2",children:[(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-price",children:"Price per billing period"}),(0,e.jsx)(qe,{id:"subscription-price",type:"number",min:"0",step:"any",value:l,placeholder:"Unknown",onChange:a(D=>g(D.target.value),"onChange")})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-currency",children:"Currency"}),(0,e.jsx)("select",{id:"subscription-currency",className:Y,value:h,onChange:a(D=>I(D.target.value),"onChange"),children:ln.map(D=>(0,e.jsx)("option",{children:D},D))})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-cadence",children:"Billed"}),(0,e.jsxs)("select",{id:"subscription-cadence",className:Y,value:f,onChange:a(D=>u(D.target.value),"onChange"),children:[(0,e.jsx)("option",{value:"month",children:"Monthly"}),(0,e.jsx)("option",{value:"year",children:"Annually"})]})]}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)(ze,{htmlFor:"subscription-status",children:"Tracking"}),(0,e.jsxs)("select",{id:"subscription-status",className:Y,value:y,onChange:a(D=>w(D.target.value),"onChange"),children:[(0,e.jsx)("option",{value:"active",children:"Active"}),(0,e.jsx)("option",{value:"ended",children:"Subscription ended"}),(0,e.jsx)("option",{value:"excluded",children:"Exclude from this organization"})]})]})]}),(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Enter the full amount for one account or seat. Annual prices are divided by 12. Changes apply from now. Ending tracking here does not cancel your provider subscription."}),$.error&&(0,e.jsx)("p",{role:"alert",className:"text-sm text-bad",children:"Could not save this price. Check the amount, or reopen the account if another person updated it."}),(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsx)(te,{type:"button",variant:"ghost",disabled:z,onClick:i,children:"Cancel"}),(0,e.jsx)(te,{type:"submit",disabled:z,children:$.isPending?"Saving…":"Save price"})]})]}),F.length>0&&(0,e.jsxs)("div",{className:"space-y-2 border-t border-line pt-4",children:[(0,e.jsx)(ze,{htmlFor:"subscription-link",children:"Same subscription as another account?"}),(0,e.jsxs)("select",{id:"subscription-link",className:Y,value:b,onChange:a(D=>q(D.target.value),"onChange"),children:[(0,e.jsx)("option",{value:"",children:"Choose an account"}),F.map(D=>(0,e.jsxs)("option",{value:D.id,children:[D.name," · ",D.price.plan]},D.id))]}),(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Linking counts these accounts once, combines their Wardmote usage, and keeps the selected account’s price. Only link the same subscription or paid seat."}),K.error&&(0,e.jsx)("p",{role:"alert",className:"text-sm text-bad",children:"Could not link these accounts. Reopen their details and try again."}),(0,e.jsx)(te,{type:"button",variant:"secondary",disabled:!b||z,onClick:a(()=>K.mutate(),"onClick"),children:"Link accounts"})]})]})}a(ia,"SubscriptionEditor");function ra({companyId:t,report:s,error:n,onChanged:i}){const[r,c]=(0,x.useState)(!1),[l,g]=(0,x.useState)(null),h=a(()=>{g(null),i()},"closeEditor"),I=s?.monthlyTotals.length,f=s?.monthlyTotals.reduce((u,y)=>u+y.estimatedCount,0)??0;return(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(ne,{className:"block p-4",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"Subscriptions"}),(0,e.jsx)("div",{className:"mt-2 font-mono text-2xl font-semibold tabular-nums",children:I?s.monthlyTotals.map(u=>(0,e.jsxs)("div",{children:[us(u.amountCents,u.currency),(0,e.jsx)("span",{className:"text-sm font-normal",children:"/month"})]},u.currency)):s&&s.activeCount===0&&s.accounts.length>0?"$0.00/month":"—"}),(0,e.jsxs)("div",{className:"mt-1 space-y-1 text-xs text-ink-3",children:[s?(0,e.jsxs)(e.Fragment,{children:[f>0&&(0,e.jsx)("div",{children:(0,e.jsx)(st,{variant:"outline",className:"font-normal text-ink-3",children:f<s.activeCount-s.unknownPriceCount?"Partially estimated":"Estimated"})}),s.unknownPriceCount>0&&!!I&&(0,e.jsx)("div",{children:"Known monthly subtotal"}),(0,e.jsx)("div",{children:s.accounts.length===0?"No visible subscriptions":(0,e.jsxs)(e.Fragment,{children:[s.activeCount," active ",s.activeCount===1?"subscription":"subscriptions",s.unknownPriceCount>0&&` · ${s.unknownPriceCount} ${s.unknownPriceCount===1?"price":"prices"} unknown`]})}),s.accounts.length>0&&(0,e.jsx)("div",{children:"Monthly fees for accounts visible to you"}),s.unidentifiedAccountCount>0&&(0,e.jsxs)("div",{children:[s.unidentifiedAccountCount," unconfirmed ",s.unidentifiedAccountCount===1?"account identity":"account identities"]}),(0,e.jsx)(Pt,{usage:s.subscription})]}):n?(0,e.jsx)("div",{children:"Subscription data is unavailable."}):(0,e.jsx)("div",{children:"Loading subscriptions…"}),s&&n?(0,e.jsx)("div",{children:"Showing last loaded subscription data."}):null]}),(0,e.jsx)(te,{variant:"link",size:"sm",className:"h-auto p-0",onClick:a(()=>c(!0),"onClick"),disabled:!s,children:"View details"})]}),(0,e.jsx)(qn,{open:r,onOpenChange:a(u=>{c(u),u||g(null)},"onOpenChange"),children:(0,e.jsxs)(Bn,{className:"max-h-(--sz-80vh) overflow-y-auto sm:max-w-3xl",children:[(0,e.jsxs)(Ln,{children:[(0,e.jsx)(_n,{children:l?"Subscription price":"Subscriptions"}),(0,e.jsx)(Un,{children:"Current monthly costs for accounts visible to you. Token totals cover company work in the selected period."})]}),l?(0,e.jsx)(ia,{companyId:t,account:l,accounts:s?.accounts??[],onDone:h},l.id):(0,e.jsxs)("div",{className:"space-y-4",children:[s?.accounts.length===0&&(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No subscriptions are visible to you yet. Connect an AI account or run an agent with a connected subscription."}),s?.accounts.map(u=>(0,e.jsxs)("div",{className:"space-y-2 border-b border-line pb-4 last:border-0",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"font-medium",children:u.name}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[u.shared?"Shared":u.ownerName??(u.ownerUserId?"Account owner":"Personal accounts")," · ",ke(u.provider)," · ",u.price.plan]})]}),(0,e.jsxs)("div",{className:"text-right",children:[(0,e.jsx)("div",{className:"font-mono",children:u.price.status!=="active"?u.price.status==="ended"?"Ended":"Excluded":u.price.monthlyCents==null?"Price unknown":`${us(u.price.monthlyCents,u.price.currency)}/month`}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[u.price.source==="catalog"?"Estimated · before tax":u.price.source==="user"?"User supplied":"",u.price.cadence==="year"?" · annual payment ÷ 12":""]})]})]}),(0,e.jsx)(Pt,{usage:u.usage}),Number(u.usage.costCents)>0&&(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[_(Number(u.usage.costCents))," recorded usage charges in selected period, separate from the subscription fee."]}),u.agents.length>0&&(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:["Used by ",u.agents.map(y=>y.name).join(", ")]}),!u.identityVerified&&(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Account identity is unconfirmed. Link duplicates if these connections use the same subscription."}),u.observedAt&&(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:["Plan checked ",Qe(u.observedAt),u.refreshStatus==="unavailable"?" · latest check unavailable":""]}),u.refreshStatus==="unavailable"&&!u.observedAt&&(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"The provider did not make plan details available. You can enter the price yourself."}),u.canEdit&&(0,e.jsx)("div",{children:(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>g(u),"onClick"),children:"Edit price"})})]},u.id)),!!s?.unattributedSubscription.eventCount&&(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Some subscription usage has no recorded account. It is included in the subscription token total."}),(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Monthly fees cover the whole account, including use outside Wardmote. They are separate from recorded charges and agent budgets. Currencies are totaled separately."})]})]})})]})}a(ra,"SubscriptionCostCard");function Us({eventCount:t,estimatedEventCount:s}){if(!s)return null;const n=s===t;return(0,e.jsx)(st,{variant:"outline",className:"font-normal text-ink-3",title:`${s} estimated ${s===1?"charge":"charges"}. Calculated from token usage and published rates; provider bills may differ.`,children:n?"Estimated":"Partially estimated"})}a(Us,"CostEstimateLabel");function pt({costCents:t,eventCount:s,estimatedEventCount:n,unpricedEventCount:i,suffix:r}){return(0,e.jsxs)("div",{className:"flex flex-col items-end gap-1 text-right",children:[(0,e.jsxs)("div",{className:"whitespace-nowrap font-mono font-medium tabular-nums",children:[t===0&&(s??0)>0&&i===s?"—":_(t),r]}),(0,e.jsx)(Us,{eventCount:s,estimatedEventCount:n})]})}a(pt,"CostAmount");function oa({report:t}){return(0,e.jsxs)(ne,{className:"gap-3 py-4",children:[(0,e.jsx)(ye,{className:"gap-0 px-5",children:(0,e.jsx)(Ne,{className:"text-base",children:"By user"})}),(0,e.jsxs)(ue,{className:"px-5",children:[(0,e.jsx)("div",{className:"overflow-x-auto",children:(0,e.jsxs)("table",{"aria-label":"Costs by user",className:"stack-table w-full text-sm",children:[(0,e.jsx)("thead",{className:"text-ink-3",children:(0,e.jsxs)("tr",{className:"border-b border-line",children:[(0,e.jsx)("th",{scope:"col",className:"py-2 pr-4 text-left font-medium",children:"User"}),(0,e.jsx)("th",{scope:"col",className:"px-4 py-2 text-right font-medium",children:"Runs"}),(0,e.jsx)("th",{scope:"col",className:"px-4 py-2 text-right font-medium",children:"Input"}),(0,e.jsx)("th",{scope:"col",className:"px-4 py-2 text-right font-medium",children:"Output"}),(0,e.jsx)("th",{scope:"col",className:"py-2 pl-4 text-right font-medium",children:"Cost"})]})}),(0,e.jsxs)("tbody",{children:[t.rows.length===0&&(0,e.jsx)("tr",{children:(0,e.jsx)("td",{colSpan:5,"data-cell":"title",className:"py-3 text-ink-3",children:"No user-attributed costs yet."})}),t.rows.map(s=>(0,e.jsxs)("tr",{className:"border-b border-line last:border-0",children:[(0,e.jsx)("th",{scope:"row","data-cell":"title",className:"py-3 pr-4 text-left font-normal",children:s.userId?(0,e.jsx)(At,{name:s.userName??"Unknown user",avatarUrl:s.userImage}):"Unattributed"}),(0,e.jsx)("td",{"data-cell":"meta","data-label":"Runs",className:"px-4 py-3 text-right tabular-nums",children:s.runCount.toLocaleString()}),(0,e.jsxs)("td",{"data-cell":"meta","data-label":"Input",className:"px-4 py-3 text-right tabular-nums",children:[Q(s.inputTokens+s.cachedInputTokens),s.cachedInputTokens>0&&(0,e.jsxs)("div",{className:"whitespace-nowrap text-xs text-ink-3",children:[Q(s.cachedInputTokens)," cached"]})]}),(0,e.jsx)("td",{"data-cell":"meta","data-label":"Output",className:"px-4 py-3 text-right tabular-nums",children:Q(s.outputTokens)}),(0,e.jsxs)("td",{"data-cell":"end",className:"py-3 pl-4 text-right tabular-nums",children:[(0,e.jsx)(pt,{costCents:s.costCents,eventCount:s.eventCount,estimatedEventCount:s.estimatedEventCount,unpricedEventCount:s.unpricedEventCount}),s.unpricedEventCount>0&&(0,e.jsxs)("div",{className:"whitespace-nowrap text-xs text-ink-3",children:[s.unpricedEventCount," unpriced ",s.unpricedEventCount===1?"charge":"charges"]})]})]},s.userId??"unattributed"))]})]})}),t.rows.some(s=>s.userId===null)&&(0,e.jsx)("p",{className:"mt-3 text-xs text-ink-3",children:"Unattributed costs have no recorded user in this organization."})]})]})}a(oa,"CostByUserTable");function Te(t,s){const n=new URLSearchParams;!t&&!s&&n.set("period","all"),t&&n.set("from",t),s&&n.set("to",s);const i=n.toString();return i?`?${i}`:""}a(Te,"dateParams");var xe={summary:a((t,s,n)=>de.get(`/companies/${t}/costs/summary${Te(s,n)}`),"summary"),byUser:a((t,s,n)=>de.get(`/companies/${t}/costs/by-user${Te(s,n)}`),"byUser"),byAgent:a((t,s,n)=>de.get(`/companies/${t}/costs/by-agent${Te(s,n)}`),"byAgent"),byAgentModel:a((t,s,n)=>de.get(`/companies/${t}/costs/by-agent-model${Te(s,n)}`),"byAgentModel"),byProject:a((t,s,n)=>de.get(`/companies/${t}/costs/by-project${Te(s,n)}`),"byProject"),byProvider:a((t,s,n)=>de.get(`/companies/${t}/costs/by-provider${Te(s,n)}`),"byProvider"),byBiller:a((t,s,n)=>de.get(`/companies/${t}/costs/by-biller${Te(s,n)}`),"byBiller"),financeSummary:a((t,s,n)=>de.get(`/companies/${t}/costs/finance-summary${Te(s,n)}`),"financeSummary"),financeByBiller:a((t,s,n)=>de.get(`/companies/${t}/costs/finance-by-biller${Te(s,n)}`),"financeByBiller"),financeByKind:a((t,s,n)=>de.get(`/companies/${t}/costs/finance-by-kind${Te(s,n)}`),"financeByKind"),financeEvents:a((t,s,n,i=100)=>de.get(`/companies/${t}/costs/finance-events${la(s,n,i)}`),"financeEvents"),windowSpend:a(t=>de.get(`/companies/${t}/costs/window-spend`),"windowSpend"),quotaWindows:a(t=>de.get(`/companies/${t}/costs/quota-windows`),"quotaWindows")};function la(t,s,n){const i=new URLSearchParams;!t&&!s&&i.set("period","all"),t&&i.set("from",t),s&&i.set("to",s),n&&i.set("limit",String(n));const r=i.toString();return r?`?${r}`:""}a(la,"dateParamsWithLimit");function ms({row:t,weekSpendCents:s,budgetMonthlyCents:n,showBudgetUtilization:i=!0,totalCompanySpendCents:r,providerRows:c}){const l=(0,x.useMemo)(()=>{const f=new Map;for(const u of c){const y=f.get(u.provider)??{provider:u.provider,costCents:0,inputTokens:0,outputTokens:0};y.costCents+=u.costCents,y.inputTokens+=u.inputTokens+u.cachedInputTokens,y.outputTokens+=u.outputTokens,f.set(u.provider,y)}return Array.from(f.values()).sort((u,y)=>y.costCents-u.costCents)},[c]),g=(0,x.useMemo)(()=>{const f=new Map;for(const u of c)f.set(u.billingType,(f.get(u.billingType)??0)+u.costCents);return Array.from(f.entries()).sort((u,y)=>y[1]-u[1])},[c]),h=n,I=h>0?Math.min(100,t.costCents/h*100):0;return(0,e.jsxs)(ne,{children:[(0,e.jsx)(ye,{className:"px-4 pt-4 pb-0 gap-1",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)(Ne,{className:"text-sm font-semibold",children:ke(t.biller)}),(0,e.jsxs)(Ee,{className:"text-xs mt-0.5",children:[(0,e.jsx)("span",{className:"font-mono",children:Q(t.inputTokens+t.cachedInputTokens)})," in"," · ",(0,e.jsx)("span",{className:"font-mono",children:Q(t.outputTokens)})," out"," · ",t.providerCount," provider",t.providerCount===1?"":"s"," · ",t.modelCount," model",t.modelCount===1?"":"s"]})]}),(0,e.jsx)("span",{className:"text-xl font-bold tabular-nums shrink-0",children:_(t.costCents)})]})}),(0,e.jsxs)(ue,{className:"px-4 pb-4 pt-3 space-y-4",children:[i&&n>0&&(0,e.jsx)(jt,{label:"Period spend",percentUsed:I,leftLabel:_(t.costCents),rightLabel:`${Math.round(I)}% of company budget`}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[t.apiRunCount>0?`${t.apiRunCount} metered run${t.apiRunCount===1?"":"s"}`:"0 metered runs"," · ",t.subscriptionRunCount>0?`${t.subscriptionRunCount} subscription run${t.subscriptionRunCount===1?"":"s"}`:"0 subscription runs"," · ",_(s)," this week"]}),g.length>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Billing types"}),(0,e.jsx)("div",{className:"space-y-1.5",children:g.map(([f,u])=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,e.jsx)("span",{className:"text-ink-3",children:zt(f)}),(0,e.jsx)("span",{className:"font-medium tabular-nums",children:_(u)})]},f))})]})]}),l.length>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Upstream providers"}),(0,e.jsx)("div",{className:"space-y-1.5",children:l.map(f=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,e.jsx)("span",{className:"text-ink-3",children:ke(f.provider)}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsx)("div",{className:"font-medium",children:_(f.costCents)}),(0,e.jsxs)("div",{className:"text-ink-3",children:[Q(f.inputTokens+f.outputTokens)," tok"]})]})]},f.provider))})]})]})]})]})}a(ms,"BillerSpendCard");function ca(t){return(t/100).toFixed(2)}a(ca,"centsInputValue");function da(t){const s=Number(t);return!Number.isFinite(s)||s<0?null:Math.round(s*100)}a(da,"parseDollarInput");function ua(t){return t.status==="resolved"?"Resolved":t.status==="dismissed"?"Dismissed":t.approvalStatus==="revision_requested"?"Escalated":t.approvalStatus==="pending"?"Pending approval":"Open"}a(ua,"incidentStateLabel");function xs({incident:t,onRaiseAndResume:s,onKeepPaused:n,isMutating:i}){const[r,c]=(0,x.useState)(ca(Math.max(t.amountObserved+1e3,t.amountLimit))),l=da(r),g=ua(t);return(0,e.jsxs)(ne,{className:"overflow-hidden border-red-500/20 bg-(image:--gradient-extract-4)",children:[(0,e.jsx)(ye,{className:"px-5 pt-5 pb-3",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsxs)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-red-700/90 dark:text-red-200/80",children:[t.scopeType," hard stop"]}),(0,e.jsx)(st,{variant:t.status==="resolved"?"outline":"secondary",children:g})]}),(0,e.jsx)(Ne,{className:"mt-1 text-base text-red-950 dark:text-red-50",children:t.scopeName}),(0,e.jsx)(Ee,{className:"mt-1 text-red-900/75 dark:text-red-100/70",children:t.thresholdType==="hard"&&t.amountObserved<t.amountLimit?`Accounting is incomplete. Known spend is ${_(t.amountObserved)}; review pending or unpriced usage in the budget policy.`:`Spending reached ${_(t.amountObserved)} against a limit of ${_(t.amountLimit)}.`})]}),(0,e.jsx)("div",{className:"rounded-full border border-red-400/30 bg-red-500/10 p-2 text-red-600 dark:text-red-200",children:(0,e.jsx)(Sn,{className:"h-4 w-4"})})]})}),(0,e.jsxs)(ue,{className:"space-y-4 px-5 pb-5 pt-0",children:[(0,e.jsxs)("div",{className:"flex items-start gap-2 rounded-xl border border-red-400/20 bg-red-500/10 px-3 py-2 text-sm text-red-950/90 dark:text-red-50/90",children:[(0,e.jsx)(Qn,{className:"mt-0.5 h-4 w-4 shrink-0"}),(0,e.jsx)("div",{children:t.scopeType==="project"?"Project execution is paused. New work in this project will not start until you resolve the budget incident.":"This scope is paused. New heartbeats will not start until you resolve the budget incident."})]}),(0,e.jsxs)("div",{className:"rounded-xl border border-line/60 bg-bg/60 p-3",children:[(0,e.jsx)("label",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-caps) text-ink-3",children:"New budget (USD)"}),(0,e.jsxs)("div",{className:"mt-2 flex flex-col gap-3 sm:flex-row",children:[(0,e.jsx)(qe,{value:r,onChange:a(h=>c(h.target.value),"onChange"),inputMode:"decimal",placeholder:"0.00"}),(0,e.jsxs)(te,{className:"gap-2",disabled:i||l===null||l<=t.amountObserved,onClick:a(()=>{typeof l=="number"&&s(l)},"onClick"),children:[(0,e.jsx)(ft,{className:"h-4 w-4"}),i?"Applying...":"Raise budget & resume"]})]}),l!==null&&l<=t.amountObserved?(0,e.jsx)("p",{className:"mt-2 text-xs text-red-700 dark:text-red-200/80",children:"The new budget must exceed current observed spend."}):null]}),(0,e.jsx)("div",{className:"flex justify-end",children:(0,e.jsx)(te,{variant:"ghost",disabled:i,onClick:n,children:"Keep paused"})})]})]})}a(xs,"BudgetIncidentCard");function ma({row:t}){return(0,e.jsxs)(ne,{children:[(0,e.jsx)(ye,{className:"px-4 pt-4 pb-1",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)(Ne,{className:"text-base",children:ke(t.biller)}),(0,e.jsxs)(Ee,{className:"mt-1 text-xs",children:[t.eventCount," event",t.eventCount===1?"":"s"," across ",t.kindCount," kind",t.kindCount===1?"":"s"]})]}),(0,e.jsxs)("div",{className:"text-right",children:[(0,e.jsx)("div",{className:"text-lg font-semibold tabular-nums",children:_(t.netCents,t.currency)}),(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"net"})]})]})}),(0,e.jsx)(ue,{className:"space-y-3 px-4 pb-4 pt-3",children:(0,e.jsxs)("div",{className:"grid gap-2 text-sm sm:grid-cols-3",children:[(0,e.jsxs)("div",{className:"border border-line p-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"debits"}),(0,e.jsx)("div",{className:"mt-1 font-medium tabular-nums",children:_(t.debitCents,t.currency)})]}),(0,e.jsxs)("div",{className:"border border-line p-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"credits"}),(0,e.jsx)("div",{className:"mt-1 font-medium tabular-nums",children:_(t.creditCents,t.currency)})]}),(0,e.jsxs)("div",{className:"border border-line p-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:"estimated"}),(0,e.jsx)("div",{className:"mt-1 font-medium tabular-nums",children:_(t.estimatedDebitCents,t.currency)})]})]})})]})}a(ma,"FinanceBillerCard");function xa({rows:t}){return(0,e.jsxs)(ne,{children:[(0,e.jsxs)(ye,{className:"px-4 pt-4 pb-1",children:[(0,e.jsx)(Ne,{className:"text-base",children:"Financial event mix"}),(0,e.jsx)(Ee,{children:"Account-level charges grouped by event kind."})]}),(0,e.jsx)(ue,{className:"space-y-2 px-4 pb-4 pt-3",children:t.length===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No finance events in this period."}):t.map(s=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3 border border-line px-3 py-2",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"truncate text-sm font-medium",children:As(s.eventKind)}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[s.eventCount," event",s.eventCount===1?"":"s"," · ",s.billerCount," biller",s.billerCount===1?"":"s"]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsx)("div",{className:"text-sm font-medium",children:_(s.netCents,s.currency)}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:[_(s.debitCents,s.currency)," debits"]})]})]},`${s.eventKind}:${s.currency}`))})]})}a(xa,"FinanceKindCard");function pa({rows:t,emptyMessage:s="No financial events recorded in this period. Events appear when reported through the API, CLI, or a supported integration."}){return(0,e.jsxs)(ne,{children:[(0,e.jsxs)(ye,{className:"px-4 pt-4 pb-1",children:[(0,e.jsx)(Ne,{className:"text-base",children:"Recent financial events"}),(0,e.jsx)(Ee,{children:"Provider charges, subscriptions, fees, and credits. Reported separately from run-cost estimates."})]}),(0,e.jsx)(ue,{className:"space-y-3 px-4 pb-4 pt-3",children:t.length===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:s}):t.map(n=>(0,e.jsx)("div",{className:"border border-line p-3",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)(st,{variant:"secondary",children:n.metadataJson?.source==="provider_cost_report"?"Provider cost report":As(n.eventKind)}),(0,e.jsx)(st,{variant:n.direction==="credit"?"outline":"secondary",children:pn(n.direction)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:Qe(n.occurredAt)})]}),(0,e.jsxs)("div",{className:"text-sm font-medium",children:[ke(n.biller),n.provider?` -> ${ke(n.provider)}`:"",n.model?(0,e.jsx)("span",{className:"ml-1 font-mono text-xs text-ink-3",children:n.model}):null]}),(n.description||n.externalInvoiceId||n.region||n.pricingTier)&&(0,e.jsxs)("div",{className:"space-y-1 text-xs text-ink-3",children:[n.description?(0,e.jsx)("div",{children:n.description}):null,n.externalInvoiceId?(0,e.jsxs)("div",{children:["invoice ",n.externalInvoiceId]}):null,n.region?(0,e.jsxs)("div",{children:["region ",n.region]}):null,n.pricingTier?(0,e.jsxs)("div",{children:["tier ",n.pricingTier]}):null]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsx)("div",{className:"text-sm font-semibold",children:_(n.amountCents,n.currency)}),(0,e.jsx)("div",{className:"text-xs text-ink-3",children:n.currency}),n.estimated?(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-amber-600",children:"estimated"}):null]})]})},n.id))})]})}a(pa,"FinanceTimelineCard");var ha=new Set(["credentials_unavailable","authentication_required","refresh_token_reused","refresh_token_expired","refresh_token_invalidated"]);function ga(t,s){return s.map(n=>{if(n.ok||n.errorFamily&&ha.has(n.errorFamily))return n;const i=t?.find(r=>r.provider===n.provider&&r.accountKey===n.accountKey);return i?.windows.length?{...n,windows:i.windows,source:i.source,capturedAt:i.capturedAt}:n})}a(ga,"retainQuotaWindows");function Mt(t){return t?"Showing the last available quota. Updates will resume automatically.":"Subscription quota is currently unavailable. Check usage with your provider."}a(Mt,"quotaUnavailableMessage");function fa({accounts:t,failed:s}){return(0,e.jsx)("div",{className:"space-y-4",children:t.map(n=>(0,e.jsxs)("section",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-sm font-medium",children:n.accountLabel??"Subscription account"}),(s||!n.ok)&&(0,e.jsx)("p",{className:"text-sm text-ink-3",children:n.errorFamily==="credentials_unavailable"?"Connect or reconnect a subscription in AI connections to view its quota.":Mt(n.windows.length>0)}),n.windows.map((i,r)=>i.usedPercent==null?(0,e.jsxs)("div",{className:"space-y-1 text-sm",children:[(0,e.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,e.jsx)("span",{children:i.label}),(0,e.jsx)("span",{className:"font-mono text-ink-3",children:i.valueLabel??"Usage not reported"})]}),i.resetsAt&&(0,e.jsxs)("p",{className:"text-xs font-mono text-ink-3",children:["Resets ",Qe(i.resetsAt)]})]},`${i.label}:${r}`):(0,e.jsx)(jt,{className:"font-mono",label:i.label,percentUsed:i.usedPercent,leftLabel:i.valueLabel??(i.usedPercent===null?"Usage not reported":`${i.usedPercent}% used`),rightLabel:i.resetsAt?`Resets ${Qe(i.resetsAt)}`:void 0},`${i.label}:${r}`)),n.capturedAt&&(0,e.jsxs)("p",{className:"text-xs font-mono text-ink-3",children:["Last checked ",Qe(n.capturedAt)]})]},n.accountKey??n.provider))})}a(fa,"AccountQuotaPanels");var ct=["currentsession","currentweekallmodels","currentweeksonnetonly","currentweeksonnet","currentweekopusonly","currentweekopus","extrausage"];function Rt(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}a(Rt,"normalizeLabel$1");function va(t){return typeof t.detail=="string"&&t.detail.trim().length>0?t.detail.trim():t.resetsAt?`Resets ${new Date(t.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}`:null}a(va,"detailText$1");function ja(t){return[...t].sort((s,n)=>{const i=ct.indexOf(Rt(s.label)),r=ct.indexOf(Rt(n.label));return(i===-1?ct.length:i)-(r===-1?ct.length:r)})}a(ja,"orderedWindows$1");function ba(t){return t==null?"bg-zinc-700":t>=90?"bg-(--status-task-blocked)":t>=70?"bg-(--status-task-todo)":"bg-accent/70"}a(ba,"fillClass$1");function ya({windows:t,source:s=null,error:n=null}){const i=ja(t);return(0,e.jsxs)("div",{className:"border border-line px-4 py-4",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 border-b border-line pb-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-ink-3",children:"Anthropic subscription"}),(0,e.jsx)("div",{className:"mt-1 text-sm text-ink-3",children:"Quota from the Claude subscription connected to this server."})]}),s?(0,e.jsx)("span",{className:"shrink-0 border border-line px-2.5 py-1 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-eyebrow) text-ink-3",children:qt(s)}):null]}),n?(0,e.jsx)("div",{role:"status",className:"mt-4 text-sm text-ink-3",children:Mt(t.length>0)}):null,(0,e.jsx)("div",{className:"mt-4 space-y-4",children:i.map(r=>{const c=Rt(r.label),l=va(r);if(c==="extrausage")return(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:r.label}),r.valueLabel?(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:r.valueLabel}):null]}),l?(0,e.jsx)("div",{className:"mt-2 text-sm text-ink-3",children:l}):null]},r.label);const g=Math.min(100,Math.max(0,r.usedPercent??0));return(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:r.label}),l?(0,e.jsx)("div",{className:"mt-1 text-xs text-ink-3",children:l}):null]}),r.usedPercent!=null?(0,e.jsxs)("div",{className:"shrink-0 text-sm font-semibold tabular-nums text-ink",children:[r.usedPercent,"% used"]}):null]}),(0,e.jsx)("div",{className:"mt-3 h-2 overflow-hidden bg-bg-3",children:(0,e.jsx)("div",{className:wt("h-full transition-(--tp-width) duration-200",ba(r.usedPercent)),style:{width:`${g}%`}})})]},r.label)})})]})}a(ya,"ClaudeSubscriptionPanel");var dt=["5hlimit","weeklylimit","credits"];function Et(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}a(Et,"normalizeLabel");function Na(t){return[...t].sort((s,n)=>{const i=Et(s.label).replace(/^gpt53codexspark/,""),r=Et(n.label).replace(/^gpt53codexspark/,""),c=dt.indexOf(i),l=dt.indexOf(r);return(c===-1?dt.length:c)-(l===-1?dt.length:l)})}a(Na,"orderedWindows");function ka(t){return typeof t.detail=="string"&&t.detail.trim().length>0?t.detail.trim():t.resetsAt?`Resets ${new Date(t.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}`:null}a(ka,"detailText");function Ca(t){return t==null?"bg-zinc-700":t>=90?"bg-(--status-task-blocked)":t>=70?"bg-(--status-task-todo)":"bg-accent/70"}a(Ca,"fillClass");function ps(t){const s=Et(t);return s.includes("gpt53codexspark")||s.includes("gpt5")}a(ps,"isModelSpecific");function wa({windows:t,source:s=null,error:n=null}){const i=Na(t),r=i.filter(l=>!ps(l.label)),c=i.filter(l=>ps(l.label));return(0,e.jsxs)("div",{className:"border border-line px-4 py-4",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 border-b border-line pb-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-ink-3",children:"Codex subscription"}),(0,e.jsx)("div",{className:"mt-1 text-sm text-ink-3",children:"Quota from the Codex subscription connected to this server."})]}),s?(0,e.jsx)("span",{className:"shrink-0 border border-line px-2.5 py-1 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-eyebrow) text-ink-3",children:qt(s)}):null]}),n?(0,e.jsx)("div",{role:"status",className:"mt-4 text-sm text-ink-3",children:Mt(t.length>0)}):null,(0,e.jsxs)("div",{className:"mt-4 space-y-5",children:[(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-ink-3",children:"Account windows"}),(0,e.jsx)("div",{className:"space-y-3",children:r.map(l=>(0,e.jsx)(hs,{window:l},l.label))})]}),c.length>0?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) font-semibold uppercase tracking-(--tracking-caps) text-ink-3",children:"Model windows"}),(0,e.jsx)("div",{className:"space-y-3",children:c.map(l=>(0,e.jsx)(hs,{window:l},l.label))})]}):null]})]})}a(wa,"CodexSubscriptionPanel");function hs({window:t}){const s=ka(t);return t.usedPercent==null?(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:t.label}),t.valueLabel?(0,e.jsx)("div",{className:"text-sm font-semibold tabular-nums text-ink",children:t.valueLabel}):null]}),s?(0,e.jsx)("div",{className:"mt-2 text-xs text-ink-3",children:s}):null]}):(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-sm font-medium text-ink",children:t.label}),s?(0,e.jsx)("div",{className:"mt-1 text-xs text-ink-3",children:s}):null]}),(0,e.jsxs)("div",{className:"shrink-0 text-sm font-semibold tabular-nums text-ink",children:[t.usedPercent,"% used"]})]}),(0,e.jsx)("div",{className:"mt-3 h-2 overflow-hidden bg-bg-3",children:(0,e.jsx)("div",{className:wt("h-full transition-(--tp-width) duration-200",Ca(t.usedPercent)),style:{width:`${Math.max(0,Math.min(100,t.usedPercent))}%`}})})]})}a(hs,"QuotaWindowRow");var Ma=["5h","24h","7d"];function gs({provider:t,rows:s,budgetMonthlyCents:n,showBudgetUtilization:i=!0,totalCompanySpendCents:r,weekSpendCents:c,windowRows:l,showDeficitNotch:g,quotaAccounts:h,quotaRequestFailed:I,quotaWindows:f=[],quotaError:u=null,quotaSource:y=null,quotaLoading:w=!1}){const{totalInputTokens:b,totalOutputTokens:q,totalTokens:$,totalCostCents:K,totalApiRuns:F,totalSubRuns:z,totalSubInputTokens:Y,totalSubOutputTokens:D,totalSubTokens:V,subSharePct:N}=(0,x.useMemo)(()=>{let v=0,X=0,Z=0,L=0,pe=0,me=0,Se=0;for(const m of s)v+=m.inputTokens+m.cachedInputTokens,X+=m.outputTokens,Z+=m.costCents,L+=m.apiRunCount,pe+=m.subscriptionRunCount,me+=m.subscriptionInputTokens+m.subscriptionCachedInputTokens,Se+=m.subscriptionOutputTokens;const he=v+X,ie=me+Se,E=he;return{totalInputTokens:v,totalOutputTokens:X,totalTokens:he,totalCostCents:Z,totalApiRuns:L,totalSubRuns:pe,totalSubInputTokens:me,totalSubOutputTokens:Se,totalSubTokens:ie,subSharePct:E>0?ie/E*100:0}},[s]),j=n,M=j>0?Math.min(100,K/j*100):0,O=j>0?j/4.33:0,d=O>0?Math.min(100,c/O*100):0,U=i&&n>0,S=(0,x.useMemo)(()=>new Map(l.map(v=>[v.window,v])),[l]),le=(0,x.useMemo)(()=>Math.max(...l.map(v=>v.costCents),0),[l]),ae=t==="anthropic",k=t==="openai"&&y?.startsWith("codex-"),H=(t==="anthropic"||t==="openai")&&(w||!!h?.length||f.length>0||u!=null);return(0,e.jsxs)(ne,{children:[(0,e.jsx)(ye,{className:"px-4 pt-4 pb-0 gap-1",children:(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)(Ne,{className:"text-sm font-semibold",children:ke(t)}),(0,e.jsxs)(Ee,{className:"text-xs mt-0.5",children:[(0,e.jsx)("span",{className:"font-mono",children:Q(b)})," in"," · ",(0,e.jsx)("span",{className:"font-mono",children:Q(q)})," out",(F>0||z>0)&&(0,e.jsxs)("span",{className:"ml-1.5",children:["·"," ",F>0&&`~${F} api`,F>0&&z>0&&" / ",z>0&&`~${z} sub`," runs"]})]})]}),(0,e.jsx)("span",{className:"text-xl font-bold tabular-nums shrink-0",children:_(K)})]})}),(0,e.jsxs)(ue,{className:"px-4 pb-4 pt-3 space-y-4",children:[U&&(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(jt,{label:"Period spend",percentUsed:M,leftLabel:_(K),rightLabel:`${Math.round(M)}% of company budget`,showDeficitNotch:g}),(0,e.jsx)(jt,{label:"This week",percentUsed:d,leftLabel:_(c),rightLabel:`~${_(Math.round(O))} / wk`,showDeficitNotch:d>=100})]}),l.length>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Rolling windows"}),(0,e.jsx)("div",{className:"space-y-2.5",children:Ma.map(v=>{const X=S.get(v);if(!X)return null;const Z=X.costCents,L=X.inputTokens+X.cachedInputTokens+X.outputTokens,pe=le>0?Z/le*100:0;return(0,e.jsxs)("div",{className:"space-y-1",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,e.jsx)("span",{className:"font-mono text-ink-3 w-6 shrink-0",children:v}),(0,e.jsxs)("span",{className:"text-ink-3 font-mono flex-1",children:[Q(L)," tok"]}),(0,e.jsx)("span",{className:"font-medium tabular-nums",children:_(Z)})]}),(0,e.jsx)("div",{className:"h-2 w-full border border-line overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-accent/60 transition-(--tp-width) duration-150",style:{width:`${pe}%`}})})]},v)})})]})]}),z>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Subscription"}),(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:[(0,e.jsx)("span",{className:"font-mono text-ink",children:z})," runs"," · ",V>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-ink",children:Q(V)})," total"," · "]}),(0,e.jsx)("span",{className:"font-mono text-ink",children:Q(Y)})," in"," · ",(0,e.jsx)("span",{className:"font-mono text-ink",children:Q(D)})," out"]}),N>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"h-1.5 w-full border border-line overflow-hidden",children:(0,e.jsx)("div",{className:"h-full bg-accent/60 transition-(--tp-width) duration-150",style:{width:`${N}%`}})}),(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:[Math.round(N),"% of token usage via subscription"]})]})]})]}),s.length>0&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsx)("div",{className:"space-y-3",children:s.map(v=>{const X=v.inputTokens+v.cachedInputTokens+v.outputTokens,Z=$>0?X/$*100:0,L=K>0?v.costCents/K*100:0;return(0,e.jsxs)("div",{className:"space-y-1.5",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("span",{className:"text-xs text-ink-3 truncate font-mono block",children:v.model}),(0,e.jsxs)("span",{className:"text-(length:--text-micro) text-ink-3 truncate block",children:[ke(v.biller)," · ",zt(v.billingType)]})]}),(0,e.jsxs)("div",{className:"flex items-center gap-3 shrink-0 tabular-nums text-xs",children:[(0,e.jsxs)("span",{className:"text-ink-3",children:[Q(X)," tok"]}),(0,e.jsx)("span",{className:"font-medium",children:_(v.costCents)})]})]}),(0,e.jsxs)("div",{className:"relative h-2 w-full border border-line overflow-hidden",children:[(0,e.jsx)("div",{className:"absolute inset-y-0 left-0 bg-accent/60 transition-(--tp-width) duration-150",style:{width:`${Z}%`},title:`${Math.round(Z)}% of provider tokens`}),(0,e.jsx)("div",{className:"absolute inset-y-0 left-0 bg-accent/85 transition-(--tp-width) duration-150",style:{width:`${L}%`},title:`${Math.round(L)}% of provider cost`})]})]},`${v.provider}:${v.model}`)})})]}),H&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"border-t border-line"}),(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsx)("p",{className:"text-xs font-semibold text-ink-3 uppercase tracking-wide",children:"Subscription quota"}),y&&!ae&&!k?(0,e.jsx)("span",{className:"text-(length:--text-nano) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:qt(y)}):null]}),w?(0,e.jsx)(Sa,{}):h?.length?(0,e.jsx)(fa,{accounts:h,failed:I}):ae?(0,e.jsx)(ya,{windows:f,source:y,error:u}):k?(0,e.jsx)(wa,{windows:f,source:y,error:u}):(0,e.jsxs)(e.Fragment,{children:[u?(0,e.jsx)("p",{role:"status",className:"text-xs text-ink-3",children:Mt(f.length>0)}):null,(0,e.jsx)("div",{className:"space-y-2.5",children:f.map(v=>{const X=v.usedPercent==null?null:v.usedPercent>=90?"bg-(--status-task-blocked)":v.usedPercent>=70?"bg-(--status-task-todo)":"bg-(--status-task-done)";return(0,e.jsxs)("div",{className:"space-y-1",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs",children:[(0,e.jsx)("span",{className:"font-mono text-ink-3 shrink-0",children:v.label}),(0,e.jsx)("span",{className:"flex-1"}),v.valueLabel!=null?(0,e.jsx)("span",{className:"font-medium tabular-nums",children:v.valueLabel}):v.usedPercent!=null?(0,e.jsxs)("span",{className:"font-medium tabular-nums",children:[v.usedPercent,"% used"]}):null]}),v.usedPercent!=null&&X!=null&&(0,e.jsx)("div",{className:"h-2 w-full border border-line overflow-hidden",children:(0,e.jsx)("div",{className:`h-full transition-(--tp-width) duration-150 ${X}`,style:{width:`${v.usedPercent}%`}})}),v.detail?(0,e.jsx)("p",{className:"text-xs text-ink-3",children:v.detail}):v.resetsAt?(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:["resets ",new Date(v.resetsAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})]}):null]},v.label)})})]})]})]})]})]})}a(gs,"ProviderQuotaCard");function Sa(){return(0,e.jsxs)("div",{className:"border border-line px-4 py-4",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 border-b border-line pb-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,e.jsx)(Ue,{className:"h-3 w-36"}),(0,e.jsx)(Ue,{className:"h-4 w-64 max-w-full"})]}),(0,e.jsx)(Ue,{className:"h-7 w-28"})]}),(0,e.jsx)("div",{className:"mt-4 space-y-3",children:Array.from({length:3}).map((t,s)=>(0,e.jsxs)("div",{className:"border border-line px-3.5 py-3",children:[(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-2",children:[(0,e.jsx)(Ue,{className:"h-4 w-32"}),(0,e.jsx)(Ue,{className:"h-3 w-44 max-w-full"})]}),(0,e.jsx)(Ue,{className:"h-4 w-20"})]}),(0,e.jsx)(Ue,{className:"mt-3 h-2 w-full"})]},s))})]})}a(Sa,"QuotaPanelSkeleton");var Ta={mtd:"Month to Date","7d":"7 Days","30d":"30 Days",ytd:"Year to Date",all:"All Time",custom:"Custom"},Ia=["mtd","7d","30d","ytd","all","custom"];function Aa(t){const s=new Date,n=s.toISOString();switch(t){case"mtd":return{from:new Date(Date.UTC(s.getUTCFullYear(),s.getUTCMonth(),1)).toISOString(),to:n};case"7d":return{from:new Date(s.getFullYear(),s.getMonth(),s.getDate()-7,0,0,0,0).toISOString(),to:n};case"30d":return{from:new Date(s.getFullYear(),s.getMonth(),s.getDate()-30,0,0,0,0).toISOString(),to:n};case"ytd":return{from:new Date(Date.UTC(s.getUTCFullYear(),0,1)).toISOString(),to:n};case"all":case"custom":return{from:"",to:""}}}a(Aa,"computeRange");function It(t){const s=new Date(t);return s.setSeconds(0,0),s.toISOString()}a(It,"floorToMinute");function Da(){const[t,s]=(0,x.useState)("mtd"),[n,i]=(0,x.useState)(""),[r,c]=(0,x.useState)(""),l=(0,x.useRef)(null),[g,h]=(0,x.useState)(()=>It(new Date));(0,x.useEffect)(()=>{const u=new Date,y=(60-u.getSeconds())*1e3-u.getMilliseconds(),w=setTimeout(()=>{h(It(new Date)),l.current=setInterval(()=>h(It(new Date)),6e4)},y);return()=>{clearTimeout(w),l.current!=null&&clearInterval(l.current)}},[]);const{from:I,to:f}=(0,x.useMemo)(()=>{if(t!=="custom")return Aa(t);const u=n?new Date(n+"T00:00:00"):null,y=r?new Date(r+"T23:59:59.999"):null;return{from:u?u.toISOString():"",to:y?y.toISOString():""}},[t,n,r,g]);return{preset:t,setPreset:s,customFrom:n,setCustomFrom:i,customTo:r,setCustomTo:c,from:I,to:f,customReady:t!=="custom"||!!n&&!!r}}a(Da,"useDateRange");var $a="__none__";function Pa(){const t=new Date,s=t.getDay(),n=s===0?-6:1-s,i=new Date(t.getFullYear(),t.getMonth(),t.getDate()+n,0,0,0,0),r=new Date(i.getFullYear(),i.getMonth(),i.getDate()+6,23,59,59,999);return{from:i.toISOString(),to:r.toISOString()}}a(Pa,"currentWeekRange");function Ra({provider:t,rows:s}){const n=s.reduce((r,c)=>r+c.inputTokens+c.cachedInputTokens+c.outputTokens,0),i=s.reduce((r,c)=>r+c.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:ke(t)}),(0,e.jsx)("span",{className:"font-mono text-xs text-ink-3",children:Q(n)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:_(i)})]})}a(Ra,"ProviderTabLabel");function Ea({biller:t,rows:s}){const n=s.reduce((r,c)=>r+c.inputTokens+c.cachedInputTokens+c.outputTokens,0),i=s.reduce((r,c)=>r+c.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:ke(t)}),(0,e.jsx)("span",{className:"font-mono text-xs text-ink-3",children:Q(n)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:_(i)})]})}a(Ea,"BillerTabLabel");function je({label:t,value:s,subtitle:n,icon:i}){return(0,e.jsx)(ne,{className:"block p-4",children:(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-ink-3",children:t}),(0,e.jsx)("div",{className:"mt-2 text-2xl font-semibold tabular-nums",children:s}),(0,e.jsx)("div",{className:"mt-1 text-xs leading-5 text-ink-3",children:n})]}),(0,e.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-line",children:(0,e.jsx)(i,{className:"h-4 w-4 text-ink-3"})})]})})}a(je,"MetricTile");function fs({debitCents:t,creditCents:s,netCents:n,estimatedDebitCents:i,eventCount:r}){return(0,e.jsxs)(ne,{children:[(0,e.jsxs)(ye,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(Ne,{className:"text-base",children:"Finance ledger"}),(0,e.jsx)(Ee,{children:"Account-level charges that do not map to a single inference request."})]}),(0,e.jsxs)(ue,{className:"grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4",children:[(0,e.jsx)(je,{label:"Debits",value:_(t),subtitle:`${r} total event${r===1?"":"s"} in range`,icon:ft}),(0,e.jsx)(je,{label:"Credits",value:_(s),subtitle:"Refunds, offsets, and credit returns",icon:Nn}),(0,e.jsx)(je,{label:"Net",value:_(n),subtitle:"Debit minus credit for the selected period",icon:$t}),(0,e.jsx)(je,{label:"Estimated",value:_(i),subtitle:"Estimated debits that are not yet invoice-authoritative",icon:vt})]})]})}a(fs,"FinanceSummaryCard");function vs({embedded:t=!1,initialTab:s="overview",lockTab:n=!1,hideBudgetsTab:i=!1}={}){const{selectedCompanyId:r}=Kt(),{setBreadcrumbs:c}=Xt(),l=fn(),[g,h]=Wt(),[I,f]=(0,x.useState)(s),[u,y]=(0,x.useState)("all"),[w,b]=(0,x.useState)("all"),q=!(t&&n&&s==="budgets"),{preset:$,setPreset:K,customFrom:F,setCustomFrom:z,customTo:Y,setCustomTo:D,from:V,to:N,customReady:j}=Da();(0,x.useEffect)(()=>{t||c([{label:"Costs"}])},[t,c]),(0,x.useEffect)(()=>{const o=g.get("tab");f(!n&&o&&["overview","providers","billers","finance","budgets","decisions","fast-responses"].includes(o)?o:s)},[s,n,g]);const[M,O]=(0,x.useState)(()=>new Date().toDateString()),d=(0,x.useRef)(null);(0,x.useEffect)(()=>{const o=a(()=>{const p=new Date,R=new Date(p.getFullYear(),p.getMonth(),p.getDate()+1).getTime()-p.getTime();d.current=setTimeout(()=>{O(new Date().toDateString()),o()},R)},"schedule");return o(),()=>{d.current!=null&&clearTimeout(d.current)}},[]);const U=(0,x.useMemo)(()=>Pa(),[M]),S=r??$a,le=["custom","mtd","ytd"].includes($)&&V||void 0,ae=$==="custom"?N||void 0:$,{data:k,error:H}=oe({queryKey:["cost-subscriptions",S,le,ae],queryFn:a(()=>bt.report(S,V||void 0,N||void 0),"queryFn"),enabled:!!r&&j&&q,refetchInterval:3e4}),v=a(()=>{l.invalidateQueries({queryKey:["cost-subscriptions",S]})},"invalidateSubscriptions"),X=(0,x.useRef)(null),Z=Ze({mutationFn:a(o=>bt.refresh(o),"mutationFn"),onSuccess:a((o,p)=>{l.invalidateQueries({queryKey:["cost-subscriptions",p]})},"onSuccess")});(0,x.useEffect)(()=>{!r||!q||!k?.canRefresh||X.current===r||(X.current=r,Z.mutate(r))},[r,q,k?.canRefresh,Z.mutate]);const{data:L,isLoading:pe,error:me}=oe({queryKey:J.budgets.overview(S),queryFn:a(()=>Tt.overview(S),"queryFn"),enabled:!!r&&j,refetchInterval:3e4,staleTime:5e3}),Se=a(()=>{r&&(l.invalidateQueries({queryKey:J.budgets.overview(r)}),l.invalidateQueries({queryKey:J.dashboard(r)}),l.invalidateQueries({queryKey:J.agents.list(r)}),l.invalidateQueries({queryKey:J.projects.all(r)}))},"invalidateBudgetViews"),he=Ze({mutationFn:a(({summary:o,changes:p})=>Tt.upsertPolicy(S,{scopeType:o.scopeType,scopeId:o.scopeId,metric:o.metric,windowKind:o.windowKind,...p}),"mutationFn"),onSuccess:Se}),ie=Ze({mutationFn:a(o=>Tt.resolveIncident(S,o.incidentId,o),"mutationFn"),onSuccess:Se}),{data:E,isLoading:m,error:T}=oe({queryKey:J.costs(S,le,ae),queryFn:a(async()=>{const[o,p,R,W]=await Promise.all([xe.summary(S,V||void 0,N||void 0),xe.byAgent(S,V||void 0,N||void 0),xe.byProject(S,V||void 0,N||void 0),xe.byAgentModel(S,V||void 0,N||void 0)]);return{summary:o,byAgent:p,byProject:R,byAgentModel:W}},"queryFn"),enabled:!!r&&j&&q,refetchInterval:3e4}),{data:P,error:A}=oe({queryKey:[...J.costs(S,le,ae),"by-user"],queryFn:a(()=>xe.byUser(S,V||void 0,N||void 0),"queryFn"),enabled:!!r&&j&&q&&I==="overview",refetchInterval:3e4}),{data:B,isLoading:re,error:ce}=oe({queryKey:[J.financeSummary(S,le,ae),J.financeByBiller(S,le,ae),J.financeByKind(S,le,ae),J.financeEvents(S,le,ae,18)],queryFn:a(async()=>{const[o,p,R,W]=await Promise.all([xe.financeSummary(S,V||void 0,N||void 0),xe.financeByBiller(S,V||void 0,N||void 0),xe.financeByKind(S,V||void 0,N||void 0),xe.financeEvents(S,V||void 0,N||void 0,18)]);return{summary:o,byBiller:p,byKind:R,events:W}},"queryFn"),enabled:!!r&&j&&q,refetchInterval:3e4}),[C,se]=(0,x.useState)(new Set);(0,x.useEffect)(()=>{se(new Set)},[S,$,F,Y]);function ve(o){se(p=>{const R=new Set(p);return R.has(o)?R.delete(o):R.add(o),R})}a(ve,"toggleAgent");const Ae=(0,x.useMemo)(()=>{const o=new Map;for(const p of E?.byAgentModel??[]){const R=o.get(p.agentId)??[];R.push(p),o.set(p.agentId,R)}for(const[p,R]of o)o.set(p,R.slice().sort((W,G)=>G.costCents-W.costCents));return o},[E?.byAgentModel]),{data:nt,error:Vs}=oe({queryKey:J.usageByProvider(S,le,ae),queryFn:a(()=>xe.byProvider(S,V||void 0,N||void 0),"queryFn"),enabled:!!r&&j&&(I==="providers"||I==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:Yt,error:Xs}=oe({queryKey:J.usageByBiller(S,le,ae),queryFn:a(()=>xe.byBiller(S,V||void 0,N||void 0),"queryFn"),enabled:!!r&&j&&I==="billers",refetchInterval:3e4,staleTime:1e4}),{data:Gt,error:Hs}=oe({queryKey:J.usageByProvider(S,U.from,U.to),queryFn:a(()=>xe.byProvider(S,U.from,U.to),"queryFn"),enabled:!!r&&(I==="providers"||I==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:Zt,error:Qs}=oe({queryKey:J.usageByBiller(S,U.from,U.to),queryFn:a(()=>xe.byBiller(S,U.from,U.to),"queryFn"),enabled:!!r&&I==="billers",refetchInterval:3e4,staleTime:1e4}),{data:Jt,error:Ys}=oe({queryKey:J.usageWindowSpend(S),queryFn:a(()=>xe.windowSpend(S),"queryFn"),enabled:!!r&&I==="providers",refetchInterval:3e4,staleTime:1e4}),{data:Fe,isLoading:es,error:at}=oe({queryKey:J.usageQuotaWindows(S),queryFn:a(()=>xe.quotaWindows(S),"queryFn"),structuralSharing:a((o,p)=>ga(o,p),"structuralSharing"),enabled:!!r&&I==="providers",refetchInterval:3e5,staleTime:6e4}),Ce=(0,x.useMemo)(()=>{const o=new Map;for(const p of nt??[]){const R=o.get(p.provider)??[];R.push(p),o.set(p.provider,R)}return o},[nt]),De=(0,x.useMemo)(()=>{const o=new Map;for(const p of Yt??[]){const R=o.get(p.biller)??[];R.push(p),o.set(p.biller,R)}return o},[Yt]),ts=(0,x.useMemo)(()=>{const o=new Map;for(const p of Gt??[])o.set(p.provider,(o.get(p.provider)??0)+p.costCents);return o},[Gt]),ss=(0,x.useMemo)(()=>{const o=new Map;for(const p of Zt??[])o.set(p.biller,(o.get(p.biller)??0)+p.costCents);return o},[Zt]),ns=(0,x.useMemo)(()=>{const o=new Map;for(const p of Jt??[]){const R=o.get(p.provider)??[];R.push(p),o.set(p.provider,R)}return o},[Jt]),as=(0,x.useMemo)(()=>{const o=new Map;for(const p of Fe??[])p.windows.length>0&&o.set(p.provider,p.windows);return o},[Fe]),is=(0,x.useMemo)(()=>{const o=new Map;for(const p of Fe??[])p.ok||o.set(p.provider,"unavailable");return at&&(o.set("anthropic","unavailable"),o.set("openai","unavailable")),o},[Fe,at]),rs=(0,x.useMemo)(()=>{const o=new Map;for(const p of Fe??[])typeof p.source=="string"&&p.source.length>0&&o.set(p.provider,p.source);return o},[Fe]),os=(0,x.useMemo)(()=>{const o=new Map;if($!=="mtd")return o;const p=E?.summary.budgetCents??0;if(p<=0)return o;const R=new Date,W=R.getUTCDate(),G=new Date(Date.UTC(R.getUTCFullYear(),R.getUTCMonth()+1,0)).getUTCDate();for(const[we,fe]of Ce){const ls=fe.reduce((an,rn)=>an+rn.costCents,0),nn=ls/Math.max(W,1);o.set(we,ls+nn*(G-W)>p)}return o},[$,E,Ce]),it=(0,x.useMemo)(()=>Array.from(Ce.keys()),[Ce]),rt=(0,x.useMemo)(()=>Array.from(De.keys()),[De]),ot=u==="all"||it.includes(u)?u:"all";(0,x.useEffect)(()=>{ot!==u&&y("all")},[ot,u]);const lt=w==="all"||rt.includes(w)?w:"all";(0,x.useEffect)(()=>{lt!==w&&b("all")},[lt,w]);const Gs=(0,x.useMemo)(()=>{const o=Array.from(Ce.keys()),p=o.reduce((W,G)=>W+(Ce.get(G)?.reduce((we,fe)=>we+fe.inputTokens+fe.cachedInputTokens+fe.outputTokens,0)??0),0),R=o.reduce((W,G)=>W+(Ce.get(G)?.reduce((we,fe)=>we+fe.costCents,0)??0),0);return[{value:"all",label:(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:"All providers"}),o.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-ink-3",children:Q(p)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:_(R)})]}):null]})},...o.map(W=>({value:W,label:(0,e.jsx)(Ra,{provider:W,rows:Ce.get(W)??[]})}))]},[Ce]),Zs=(0,x.useMemo)(()=>{const o=Array.from(De.keys()),p=o.reduce((W,G)=>W+(De.get(G)?.reduce((we,fe)=>we+fe.inputTokens+fe.cachedInputTokens+fe.outputTokens,0)??0),0),R=o.reduce((W,G)=>W+(De.get(G)?.reduce((we,fe)=>we+fe.costCents,0)??0),0);return[{value:"all",label:(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:"All billers"}),o.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-ink-3",children:Q(p)}),(0,e.jsx)("span",{className:"text-xs text-ink-3",children:_(R)})]}):null]})},...o.map(W=>({value:W,label:(0,e.jsx)(Ea,{biller:W,rows:De.get(W)??[]})}))]},[De]),Js=B?.events??[],Ge=L?.policies??[],Le=L?.activeIncidents??[],en=(0,x.useMemo)(()=>({company:Ge.filter(o=>o.scopeType==="company"),agent:Ge.filter(o=>o.scopeType==="agent"),project:Ge.filter(o=>o.scopeType==="project")}),[Ge]);if(!r)return(0,e.jsx)(Re,{icon:St,message:"Select an organization to view costs."});const Oe=$==="custom"&&!j,tn=m&&j,sn=!E&&T;return(0,e.jsxs)("div",{className:"space-y-6",children:[q?(0,e.jsxs)("div",{className:"space-y-5",children:[(0,e.jsxs)("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[(0,e.jsx)("div",{children:t?(0,e.jsx)("h2",{className:"text-lg font-semibold text-ink",children:"Costs"}):(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:"Costs"})}),(0,e.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:Ia.map(o=>(0,e.jsx)(te,{variant:$===o?"secondary":"ghost",size:"sm",onClick:a(()=>K(o),"onClick"),"aria-pressed":$===o,children:Ta[o]},o))})]}),$==="custom"?(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 border border-line p-3",children:[(0,e.jsx)("input",{type:"date",value:F,onChange:a(o=>z(o.target.value),"onChange"),className:"h-9 rounded-md border border-line-strong bg-bg px-3 text-sm text-ink"}),(0,e.jsx)("span",{className:"text-sm text-ink-3",children:"to"}),(0,e.jsx)("input",{type:"date",value:Y,onChange:a(o=>D(o.target.value),"onChange"),className:"h-9 rounded-md border border-line-strong bg-bg px-3 text-sm text-ink"})]}):null,B?.summary.currencies?.some(o=>o.currency!=="USD")&&(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:"Finance headline totals are USD only. Other currencies are listed separately; no exchange-rate conversion is applied."}),(0,e.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-5",children:[(0,e.jsx)(je,{label:"API spend",value:k?k.api.unpricedEventCount===k.api.eventCount&&k.api.eventCount>0?"—":_(Number(k.api.costCents)):"—",subtitle:k?(0,e.jsxs)("div",{className:"space-y-1",children:[(0,e.jsx)(Us,{eventCount:k.api.eventCount,estimatedEventCount:k.api.estimatedEventCount}),(0,e.jsx)("div",{children:(0,e.jsx)(Pt,{usage:k.api})})]}):H?"API usage is unavailable":"API usage is loading",icon:St}),(0,e.jsx)(ra,{companyId:S,report:k,error:H,onChanged:v},S),(0,e.jsx)(je,{label:"Budget",value:Le.length>0?String(Le.length):E?.summary.budgetCents&&E.summary.budgetCents>0?$==="mtd"?`${E.summary.utilizationPercent}%`:_(E.summary.budgetCents):"Open",subtitle:Le.length>0?`${L?.pausedAgentCount??0} agents paused · ${L?.pausedProjectCount??0} projects paused`:E?.summary.budgetCents&&E.summary.budgetCents>0?$==="mtd"?`${_(E.summary.spendCents)} of ${_(E.summary.budgetCents)} this month`:"Monthly limit":"No monthly cap configured",icon:vt}),(0,e.jsx)(je,{label:"Recorded charges",value:B?_(B.summary.netCents):"—",subtitle:B?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("span",{className:"block whitespace-nowrap",children:[_(B.summary.debitCents)," debits"]}),(0,e.jsxs)("span",{className:"block whitespace-nowrap",children:[_(B.summary.creditCents)," credits"]})]}):"Financial data unavailable",icon:$t}),(0,e.jsx)(je,{label:"Finance events",value:B?String(B.summary.eventCount):"—",subtitle:B?`${_(B.summary.estimatedDebitCents)} estimated in range`:"Financial data unavailable",icon:ft})]}),k&&Number(k.subscription.costCents)>0&&(0,e.jsxs)("p",{className:"text-sm text-ink-3",children:["Subscription accounts also have ",_(Number(k.subscription.costCents))," in recorded usage charges for this period, separate from monthly fees."]}),k&&k.unknown.eventCount>0&&(0,e.jsxs)("p",{className:"text-sm text-ink-3",children:[Q(k.unknown.inputTokens+k.unknown.cachedInputTokens+k.unknown.outputTokens)," tokens have other or unknown billing types",Number(k.unknown.costCents)>0?`, with ${_(Number(k.unknown.costCents))} in recorded charges`:"",". They remain in the inference ledger."]}),H&&k&&(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:"Showing the last loaded API and subscription usage. Updates will resume automatically."}),Z.error&&(0,e.jsxs)("div",{role:"status",className:"flex flex-wrap items-center gap-2 text-sm text-ink-3",children:[(0,e.jsx)("p",{children:"Connected accounts could not be checked. Existing subscription estimates are still shown."}),k?.canRefresh&&(0,e.jsx)(te,{variant:"secondary",size:"sm",disabled:Z.isPending,onClick:a(()=>Z.mutate(S),"onClick"),children:"Retry account check"})]}),E?.summary.pricingComplete===!1&&(0,e.jsxs)("div",{role:"status",className:"space-y-1 text-sm text-ink-3",children:[E.summary.unpricedEventCount>0&&(0,e.jsxs)("p",{children:["Costs are unavailable for ",E.summary.unpricedEventCount," usage ",E.summary.unpricedEventCount===1?"entry":"entries"," in this period. Totals include known costs only."]}),E.summary.pendingRunCount>0&&(0,e.jsxs)("p",{children:[E.summary.pendingRunCount," ",E.summary.pendingRunCount===1?"run is":"runs are"," awaiting cost data."]})]})]}):null,me&&!L?(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:"Budget data could not be loaded. Please try again shortly."}):null,E&&T||B&&ce||L&&me||Vs||Xs||Hs||Qs||Ys?(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:"Showing the last loaded data. Updates will resume automatically."}):null,!!E?.summary.estimatedEventCount&&(0,e.jsxs)("p",{role:"status",className:"text-sm text-ink-3",children:["Includes ",E.summary.estimatedEventCount," estimated ",E.summary.estimatedEventCount===1?"charge":"charges",". Token estimates use published rates and recorded assumptions; provider bills may differ."]}),ie.error&&(0,e.jsx)("p",{role:"alert",className:"text-sm text-bad",children:"Could not update the budget. Check any pending runs or unpriced usage shown on this page, then try again."}),(0,e.jsxs)(Je,{value:I,onValueChange:a(o=>{f(o),h(p=>{const R=new URLSearchParams(p);return R.set("tab",o),R},{replace:!0})},"onValueChange"),children:[n?null:(0,e.jsx)("div",{className:"max-w-full overflow-x-auto pb-2",children:(0,e.jsxs)(Ps,{variant:"line",className:"justify-start",children:[(0,e.jsx)($e,{value:"overview",children:"Overview"}),i?null:(0,e.jsx)($e,{value:"budgets",children:"Budgets"}),(0,e.jsx)($e,{value:"providers",children:"Providers"}),(0,e.jsx)($e,{value:"billers",children:"Billers"}),(0,e.jsx)($e,{value:"finance",children:"Finance"}),(0,e.jsx)($e,{value:"decisions",children:"Decisions"}),(0,e.jsx)($e,{value:"fast-responses",children:"Fast responses"})]})}),(0,e.jsx)(Me,{value:"fast-responses",className:"mt-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):(0,e.jsx)(aa,{companyId:S,from:V,to:N})}),(0,e.jsx)(Me,{value:"decisions",className:"mt-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):(0,e.jsx)(na,{companyId:S,from:V,to:N})}),(0,e.jsx)(Me,{value:"overview",className:"mt-4 space-y-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):tn?(0,e.jsx)(xt,{variant:"costs"}):sn?(0,e.jsx)("p",{className:"text-sm text-bad",children:"Cost data could not be loaded. Please try again shortly."}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-32)",children:[(0,e.jsxs)("div",{className:"min-w-0 space-y-4",children:[(0,e.jsxs)(ne,{className:"gap-3 py-4",children:[(0,e.jsx)(ye,{className:"gap-0 px-5",children:(0,e.jsx)(Ne,{className:"text-base",children:"By agent"})}),(0,e.jsx)(ue,{className:"space-y-2 px-5",children:(E?.byAgent.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No cost events yet."}):E?.byAgent.map(o=>{const p=Ae.get(o.agentId)??[],R=C.has(o.agentId),W=p.length>0;return(0,e.jsxs)("div",{role:"group","aria-label":`${o.agentName??o.agentId??"Wardmote services"} costs`,className:"border border-line px-4 py-3",children:[(0,e.jsxs)("div",{className:wt("flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",W?"cursor-pointer select-none":""),onClick:a(()=>W&&ve(o.agentId),"onClick"),children:[(0,e.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[W?R?(0,e.jsx)(Cn,{className:"h-3 w-3 shrink-0 text-ink-3"}):(0,e.jsx)(wn,{className:"h-3 w-3 shrink-0 text-ink-3"}):(0,e.jsx)("span",{className:"h-3 w-3 shrink-0"}),o.agentId?(0,e.jsx)(Kn,{agent:{id:o.agentId,name:o.agentName??o.agentId,appearance:o.agentAppearance},size:"sm"}):(0,e.jsx)("span",{className:"font-medium",children:"Wardmote services"}),o.agentStatus==="terminated"?(0,e.jsx)(Ht,{status:"terminated"}):null]}),(0,e.jsxs)("div",{className:"text-right text-sm tabular-nums",children:[(0,e.jsx)(pt,{costCents:o.costCents,eventCount:o.eventCount,estimatedEventCount:o.estimatedEventCount}),(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:["in ",Q(o.inputTokens+o.cachedInputTokens)," (",Q(o.cachedInputTokens)," cached) · out ",Q(o.outputTokens)]}),o.apiRunCount>0||o.subscriptionRunCount>0?(0,e.jsxs)("div",{className:"text-xs text-ink-3",children:["runs: ",o.apiRunCount>0?`${o.apiRunCount} api`:"0 api"," · ",o.subscriptionRunCount>0?`${o.subscriptionRunCount} sub`:"0 sub"]}):null]})]}),R&&p.length>0?(0,e.jsx)("div",{className:"mt-3 space-y-2 border-l border-line pl-4",children:p.map(G=>{const we=o.costCents>0?Math.round(G.costCents/o.costCents*100):0;return(0,e.jsxs)("div",{className:"flex flex-col gap-2 text-xs sm:flex-row sm:items-start sm:justify-between sm:gap-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"truncate font-medium text-ink",children:[ke(G.provider),(0,e.jsx)("span",{className:"mx-1 text-line",children:"/"}),(0,e.jsx)("span",{className:"font-mono",children:G.model})]}),(0,e.jsxs)("div",{className:"truncate text-ink-3",children:[ke(G.biller)," · ",zt(G.billingType)]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsx)(pt,{costCents:G.costCents,eventCount:G.eventCount,estimatedEventCount:G.estimatedEventCount,suffix:(0,e.jsxs)("span",{className:"ml-1 font-normal text-ink-3",children:["(",we,"%)"]})}),(0,e.jsxs)("div",{className:"text-ink-3",children:[Q(G.inputTokens+G.cachedInputTokens+G.outputTokens)," tok"]})]})]},`${G.provider}:${G.model}:${G.billingType}`)})}):null]},o.agentId??"services")})})]}),A&&(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:P?"User costs could not be refreshed. Showing the last loaded data.":"User costs could not be loaded. Please try again shortly."}),P&&(0,e.jsx)(oa,{report:P})]}),(0,e.jsx)("div",{className:"space-y-4",children:(0,e.jsxs)(ne,{className:"gap-3 py-4",children:[(0,e.jsx)(ye,{className:"gap-0 px-5",children:(0,e.jsx)(Ne,{className:"text-base",children:"By project"})}),(0,e.jsx)(ue,{className:"space-y-2 px-5",children:(E?.byProject.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No project-attributed run costs yet."}):E?.byProject.map((o,p)=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3 border border-line px-3 py-2 text-sm",children:[(0,e.jsx)("span",{className:"truncate",children:o.projectName??o.projectId??"Unattributed"}),(0,e.jsx)(pt,{costCents:o.costCents,eventCount:o.eventCount,estimatedEventCount:o.estimatedEventCount})]},o.projectId??`unattributed-${p}`))})]})})]}),Le.length>0?(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:Le.slice(0,2).map(o=>(0,e.jsx)(xs,{incident:o,isMutating:ie.isPending,onKeepPaused:a(()=>ie.mutate({incidentId:o.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:a(p=>ie.mutate({incidentId:o.id,action:"raise_budget_and_resume",amount:p}),"onRaiseAndResume")},o.id))}):null,B?(0,e.jsx)(fs,{debitCents:B.summary.debitCents,creditCents:B.summary.creditCents,netCents:B.summary.netCents,estimatedDebitCents:B.summary.estimatedDebitCents,eventCount:B.summary.eventCount}):(0,e.jsx)("p",{role:"status",className:"text-sm text-ink-3",children:re?"Loading financial events…":"Financial events could not be loaded. Please try again shortly."})]})}),(0,e.jsxs)(Me,{value:"budgets",className:"mt-4 space-y-4",children:[he.error&&(0,e.jsx)("p",{role:"alert",className:"text-sm text-bad",children:"Could not update the budget policy. Review your settings and try again."}),pe?(0,e.jsx)(xt,{variant:"costs"}):me&&!L?null:(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(ne,{className:"border-line/70 bg-(image:--gradient-extract-2)",children:[(0,e.jsxs)(ye,{className:"px-5 pt-5 pb-3",children:[(0,e.jsx)(Ne,{className:"text-base",children:"Budget control plane"}),(0,e.jsx)(Ee,{children:"Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers."})]}),(0,e.jsxs)(ue,{className:"grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4",children:[(0,e.jsx)(je,{label:"Active incidents",value:String(Le.length),subtitle:"Open soft or hard threshold crossings",icon:$t}),(0,e.jsx)(je,{label:"Pending approvals",value:String(L?.pendingApprovalCount??0),subtitle:"Budget override approvals awaiting board action",icon:ft}),(0,e.jsx)(je,{label:"Paused agents",value:String(L?.pausedAgentCount??0),subtitle:"Agent heartbeats blocked by budget",icon:vt}),(0,e.jsx)(je,{label:"Paused projects",value:String(L?.pausedProjectCount??0),subtitle:"Project execution blocked by budget",icon:St})]})]}),Le.length>0?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold",children:"Active incidents"}),(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Resolve hard stops here by raising the budget or explicitly keeping the scope paused."})]}),(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:Le.map(o=>(0,e.jsx)(xs,{incident:o,isMutating:ie.isPending,onKeepPaused:a(()=>ie.mutate({incidentId:o.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:a(p=>ie.mutate({incidentId:o.id,action:"raise_budget_and_resume",amount:p}),"onRaiseAndResume")},o.id))})]}):null,(0,e.jsxs)("div",{className:"space-y-5",children:[["company","agent","project"].map(o=>{const p=en[o];return p.length===0?null:(0,e.jsxs)("section",{className:"space-y-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsxs)("h2",{className:"text-lg font-semibold capitalize",children:[o==="company"?"organization":o," budgets"]}),(0,e.jsx)("p",{className:"text-sm text-ink-3",children:o==="company"?"Organization-wide monthly policy.":o==="agent"?"Recurring monthly spend policies for individual agents.":"Lifetime spend policies for execution-bound projects."})]}),(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:p.map(R=>(0,e.jsx)($n,{summary:R,onReservationChange:a(W=>he.mutate({summary:R,changes:{reservationCents:W}}),"onReservationChange"),onUnpricedUsagePolicyChange:a(W=>he.mutate({summary:R,changes:{unpricedUsagePolicy:W}}),"onUnpricedUsagePolicyChange"),isSaving:he.isPending,onSave:a(W=>he.mutate({summary:R,changes:{amount:W}}),"onSave")},R.policyId))})]},o)}),Ge.length===0?(0,e.jsx)(ne,{children:(0,e.jsx)(ue,{className:"px-5 py-8 text-sm text-ink-3",children:"No budget policies yet. Set agent and project budgets from their detail pages, or use the existing organization monthly budget control."})}):null]})]})]}),(0,e.jsx)(Me,{value:"providers",className:"mt-4 space-y-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(Je,{value:ot,onValueChange:y,children:[(0,e.jsx)(Dt,{items:Gs,value:ot}),(0,e.jsx)(Me,{value:"all",className:"mt-4",children:it.length===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No cost events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:it.map(o=>(0,e.jsx)(gs,{provider:o,rows:Ce.get(o)??[],budgetMonthlyCents:E?.summary.budgetCents??0,showBudgetUtilization:$==="mtd",totalCompanySpendCents:E?.summary.spendCents??0,weekSpendCents:ts.get(o)??0,windowRows:ns.get(o)??[],showDeficitNotch:os.get(o)??!1,quotaAccounts:Fe?.filter(p=>p.provider===o),quotaRequestFailed:!!at,quotaWindows:as.get(o)??[],quotaError:is.get(o)??null,quotaSource:rs.get(o)??null,quotaLoading:es},o))})}),it.map(o=>(0,e.jsx)(Me,{value:o,className:"mt-4",children:(0,e.jsx)(gs,{provider:o,rows:Ce.get(o)??[],budgetMonthlyCents:E?.summary.budgetCents??0,showBudgetUtilization:$==="mtd",totalCompanySpendCents:E?.summary.spendCents??0,weekSpendCents:ts.get(o)??0,windowRows:ns.get(o)??[],showDeficitNotch:os.get(o)??!1,quotaAccounts:Fe?.filter(p=>p.provider===o),quotaRequestFailed:!!at,quotaWindows:as.get(o)??[],quotaError:is.get(o)??null,quotaSource:rs.get(o)??null,quotaLoading:es})},o))]})})}),(0,e.jsx)(Me,{value:"billers",className:"mt-4 space-y-4",children:Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(Je,{value:lt,onValueChange:b,children:[(0,e.jsx)(Dt,{items:Zs,value:lt}),(0,e.jsx)(Me,{value:"all",className:"mt-4",children:rt.length===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No billable events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:rt.map(o=>{const p=(De.get(o)??[])[0];if(!p)return null;const R=(nt??[]).filter(W=>W.biller===o);return(0,e.jsx)(ms,{row:p,weekSpendCents:ss.get(o)??0,budgetMonthlyCents:E?.summary.budgetCents??0,showBudgetUtilization:$==="mtd",totalCompanySpendCents:E?.summary.spendCents??0,providerRows:R},o)})})}),rt.map(o=>{const p=(De.get(o)??[])[0];if(!p)return null;const R=(nt??[]).filter(W=>W.biller===o);return(0,e.jsx)(Me,{value:o,className:"mt-4",children:(0,e.jsx)(ms,{row:p,weekSpendCents:ss.get(o)??0,budgetMonthlyCents:E?.summary.budgetCents??0,showBudgetUtilization:$==="mtd",totalCompanySpendCents:E?.summary.spendCents??0,providerRows:R})},o)})]})})}),(0,e.jsxs)(Me,{value:"finance",className:"mt-4 space-y-4",children:[B?.summary.providerReportedCentsExact!==void 0&&(0,e.jsxs)("p",{className:"text-sm text-ink-3",children:["Provider API cost reports: ",_(B.summary.providerReportedCents??0),". Report totals overlap invoices and run estimates and are shown separately from recorded charges."]}),Oe?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"Select a start and end date to load data."}):re?(0,e.jsx)(xt,{variant:"costs"}):ce&&!B?(0,e.jsx)("p",{className:"text-sm text-bad",children:"Financial events could not be loaded. Please try again shortly."}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(fs,{debitCents:B?.summary.debitCents??0,creditCents:B?.summary.creditCents??0,netCents:B?.summary.netCents??0,estimatedDebitCents:B?.summary.estimatedDebitCents??0,eventCount:B?.summary.eventCount??0}),(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-33)",children:[(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)(ne,{children:[(0,e.jsxs)(ye,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(Ne,{className:"text-base",children:"By biller"}),(0,e.jsx)(Ee,{children:"Account-level financial events grouped by who charged or credited them."})]}),(0,e.jsx)(ue,{className:"grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2",children:(B?.byBiller.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-ink-3",children:"No finance events yet."}):B?.byBiller.map(o=>(0,e.jsx)(ma,{row:o},`${o.biller}:${o.currency}`))})]}),(0,e.jsx)(pa,{rows:Js})]}),(0,e.jsx)(xa,{rows:B?.byKind??[]})]})]})]})]})]})}a(vs,"Costs");function Fa(t){const s=new URLSearchParams;t.from&&s.set("from",t.from),t.to&&s.set("to",t.to),t.userId&&s.set("userId",t.userId),t.goalId&&s.set("goalId",t.goalId),t.projectId&&s.set("projectId",t.projectId),t.issueId&&s.set("issueId",t.issueId),t.limit&&s.set("limit",String(t.limit)),t.offset&&s.set("offset",String(t.offset));const n=s.toString();return n?`?${n}`:""}a(Fa,"query");var La={get:a((t,s={},n)=>de.get(`/companies/${t}/timeline${Fa(s)}`,n),"get")};function js(){const{setRouteRequestsCollapsed:t}=Pn();return(0,x.useEffect)(()=>(t(!0),()=>t(!1)),[t]),null}a(js,"RequestCollapsedSidebar");var Ba=new Set(["running","in_progress","queued","pending"]),Ua=new Set(["cancelled","canceled","aborted","skipped"]);function _a(t){return Ba.has(t)}a(_a,"isRunningStatus");function Ft(t){return Ua.has(t)}a(Ft,"isCancelledStatus");var Be={delegated:"#5b9bf6",automation:"#f4b740",cancelled:"#9aa3ad",now:"#2563eb"};function qa(t){return t.kickoff?"delegated":"automation"}a(qa,"barSourceKind");function _s(t){return Be[qa(t)]}a(_s,"barColor");function Oa(t){return t?.type??"system"}a(Oa,"actorType");function za(t){let s=0;for(let n=0;n<t.length;n++)s=s*31+t.charCodeAt(n)&4294967295;return`hsl(${Math.abs(s)%360} 62% 52%)`}a(za,"issueColor");function Wa(t){const s=t.trim().split(/\s+/).filter(Boolean);return s.length>=2?(s[0][0]+s[s.length-1][0]).toUpperCase():(t.slice(0,2)||"?").toUpperCase()}a(Wa,"shortLabel");function Pe(t){return new Date(t.start).getTime()}a(Pe,"spanStartMs$1");function Ye(t,s){return t.end?new Date(t.end).getTime():s}a(Ye,"spanEndMs$1");function Ka(t,s){return Math.abs(Pe(s)-new Date(t.at).getTime())}a(Ka,"kickoffEdgeRunDistanceMs");function bs(t,s){return`${t}\0${s}`}a(bs,"spanGroupKey");function Va(t,s){let n=null;for(const i of s){const r=Ka(t,i);(!n||r<n.distance||r===n.distance&&i.runId.localeCompare(n.span.runId)<0)&&(n={span:i,distance:r})}return n?.span.runId??null}a(Va,"closestRunForKickoffEdge");function Xa(t,s){const n=new Map;for(const r of t){const c=bs(r.actorId,r.issueId),l=n.get(c);l?l.push(r):n.set(c,[r])}const i=new Map;for(const r of s){const c=Va(r,n.get(bs(r.toActorId,r.issueId))??[]);c&&i.set(r,c)}return i}a(Xa,"buildClosestRunByKickoffEdge");function Ha(t,s,n,i){const r=Pe(t);let c=null;for(const l of s){if(l.toActorId!==t.actorId||l.issueId!==t.issueId||l.fromActorId===t.actorId)continue;const g=new Date(l.at).getTime(),h=g<=r?r-g:g-r+1e12;(!c||h<c.delta)&&(c={edge:l,delta:h})}return!c||i.get(c.edge)!==t.runId?null:n.get(c.edge.fromActorId)??null}a(Ha,"resolveKickoff");function Qa(t,s){const{pxPerMinute:n,gutter:i,rowH:r,barH:c,laneGap:l,nowMs:g}=s,h=new Date(t.window.from).getTime(),I=new Date(t.window.to).getTime(),f=new Map(t.actors.map(N=>[N.id,N])),u=Xa(t.spans,t.edges),y=a(N=>i+(N-h)/6e4*n,"x"),w=new Map,b=a((N,j)=>{const M=w.get(N);(M===void 0||j<M)&&w.set(N,j)},"noteActivity");for(const N of t.spans)b(N.actorId,Pe(N));const q=t.actors.filter(N=>w.has(N.id)).sort((N,j)=>w.get(N.id)-w.get(j.id)),$=[],K=new Map;for(const N of t.spans){const j=N.issueId;K.has(j)||($.push(j),K.set(j,N.issueIdentifier??N.issueTitle??"issue"))}const F=$.map(N=>({key:N,label:K.get(N),color:za(N)})),z=new Map,Y=[];let D=0;for(const N of q){const j=t.spans.filter(k=>k.actorId===N.id).sort((k,H)=>Pe(k)-Pe(H)),M=[],O=new Map;for(const k of j){const H=Pe(k),v=Ye(k,g);let X=-1;for(let Z=0;Z<M.length;Z++)if(M[Z]<=H){X=Z;break}X===-1?(X=M.length,M.push(v)):M[X]=v,O.set(k.runId,X)}const d=Math.max(1,M.length),U=Math.max(r,d*(c+l)+8),S=j.map(k=>{const H=O.get(k.runId)??0,v=D+6+H*(c+l),X=y(Pe(k)),Z=y(Ye(k,g)),L={span:k,x1:X,x2:Math.max(X+3,Z),yTop:v,yc:v+c/2,height:c,running:_a(k.status),kickoff:Ha(k,t.edges,f,u)};return z.set(k.runId,L),L}),le=[],ae=j.reduce((k,H)=>k+Math.max(0,Ye(H,g)-Pe(H)),0);Y.push({actor:N,y:D,h:U,laneCount:d,bars:S,markers:le,runCount:j.length,activeMs:ae}),D+=U}const V=[];for(const N of Y)for(const j of N.bars){const M=j.kickoff;if(!M||M.type==="user")continue;const O=Ya(M.id,j,z,g);O&&V.push({x1:O.x2,y1:O.yc,x2:j.x1,y2:j.yc,sourceRunId:O.span.runId,targetRunId:j.span.runId,dashed:!!j.span.retryOfRunId})}return{rows:Y,connectors:V,width:i+(I-h)/6e4*n+40,height:D+32,fromMs:h,toMs:I,gutter:i,pxPerMinute:n,issues:F}}a(Qa,"computeLayout");function Ya(t,s,n,i){const r=Pe(s.span);let c=null,l=null;for(const g of n.values()){if(g.span.actorId!==t||g===s)continue;const h=Ye(g.span,i);h>r+1||(g.span.issueId===s.span.issueId&&(!c||Ye(c.span,i)<h)&&(c=g),(!l||Ye(l.span,i)<h)&&(l=g))}return c??l}a(Ya,"nearestSourceBar");function Ga(t){const s=120/t,n=[15,30,60,120,180,360,720,1440,2880,10080];for(const i of n)if(i>=s)return i*6e4;return n[n.length-1]*6e4}a(Ga,"chooseTickStepMs");function qs(t,s){const n=Math.max(0,Math.round((s-t)/6e4));return n>=1440?`${Math.floor(n/1440)}d ${Math.floor(n%1440/60)}h`:n>=60?`${Math.floor(n/60)}h ${n%60}m`:`${n}m`}a(qs,"formatDuration");var Os={hour:60,day:1440,week:10080},Za=.08,Ja=12,et=960,ht=9e5;function yt(t){return Math.max(240,t-be.gutter-24)}a(yt,"plotViewportWidth");function ys(t,s,n){return Math.max(s,Math.min(n,t))}a(ys,"clampTime");function zs(t,s,n){const i=yt(n),r=ys(t.fromMs+s/t.pxPerMinute*6e4,t.fromMs,t.toMs),c=ys(t.fromMs+(s+i)/t.pxPerMinute*6e4,t.fromMs,t.toMs);return{fromMs:r,toMs:Math.max(r,c)}}a(zs,"visibleWindowForScroll");function Nt(t,s=et){return Ct(yt(s)/Os[t])}a(Nt,"zoomScaleForLevel");function kt(t,s=et){return Object.entries(Os).reduce((n,[i])=>Math.abs(Nt(i,s)-t)<Math.abs(Nt(n,s)-t)?i:n,"day")}a(kt,"nearestZoomForScale");function Ct(t){return Math.min(Ja,Math.max(Za,t))}a(Ct,"clampZoomScale");function Ns(t,s){const n=(s-t)/36e5;return n<=4?"hour":n<=48?"day":"week"}a(Ns,"defaultZoomForWindow");var be={gutter:176,rowH:34,barH:15,laneGap:4},Ws=11,ei=9;function Lt(t){const s=new Date(t),n=s.getMinutes()!==0;return s.toLocaleTimeString("en-US",{hour:"numeric",minute:n?"2-digit":void 0,hour12:!0})}a(Lt,"fmtClock");function ti(t,s){const n=new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric"});return s>=864e5?n:`${n}, ${Lt(t)}`}a(ti,"fmtTick");function si(t){const s=Math.max(1,Math.round(t));if(s>=10080&&s%10080===0){const n=s/10080;return`${n} week${n===1?"":"s"} visible`}if(s>=1440&&s%1440===0){const n=s/1440;return`${n} day${n===1?"":"s"} visible`}if(s>=1440){const n=Math.floor(s/1440),i=Math.round(s%1440/60);return`${n}d${i>0?` ${i}h`:""} visible`}if(s>=60&&s%60===0){const n=s/60;return`${n} hour${n===1?"":"s"} visible`}return s>=60?`${Math.floor(s/60)}h ${s%60}m visible`:`${s} minutes visible`}a(si,"formatVisibleDurationMinutes");function Qt(t,s=42){return t.length>s?`${t.slice(0,s-1)}…`:t}a(Qt,"truncate");function Bt(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}a(Bt,"svgFragmentId");function Ut({actor:t,cx:s,cy:n,r:i,clipId:r}){if(t.type==="agent"){const h=i>10?24:16,I=hn(t.appearance,t.id.replace(/^agent:/,""));return(0,e.jsx)("image",{"data-testid":"timeline-agent-icon",href:un(I,h,2),x:s-h/2,y:n-h/2,width:h,height:h,preserveAspectRatio:"xMidYMid meet"})}const c="var(--color-ink)",l=t.type==="system"?"var(--color-bg-3)":"var(--color-bg-2)",g=Wa(t.name);return t.type==="user"&&t.avatar?(0,e.jsxs)("g",{children:[(0,e.jsx)("defs",{children:(0,e.jsx)("clipPath",{id:r,children:(0,e.jsx)("circle",{cx:s,cy:n,r:i})})}),(0,e.jsx)("image",{"data-testid":"timeline-user-avatar-image",href:t.avatar,x:s-i,y:n-i,width:2*i,height:2*i,preserveAspectRatio:"xMidYMid slice",clipPath:`url(#${r})`}),(0,e.jsx)("circle",{cx:s,cy:n,r:i,fill:"none",stroke:c,strokeWidth:1.2,opacity:.5})]}):(0,e.jsxs)("g",{children:[t.type==="user"?(0,e.jsx)("rect",{x:s-i,y:n-i,width:2*i,height:2*i,rx:3,fill:l,stroke:c,strokeWidth:1.5}):(0,e.jsx)("circle",{cx:s,cy:n,r:i,fill:l,stroke:c,strokeWidth:1.5,strokeDasharray:t.type==="system"?"3 2":void 0}),(0,e.jsx)("text",{x:s,y:n+3.4,fontSize:i>10?9:8,textAnchor:"middle",fill:c,children:g})]})}a(Ut,"ActorGlyph");function ni({data:t,zoom:s,zoomScale:n,onZoomScaleChange:i,onVisibleRangeLabelChange:r,onVisibleWindowChange:c,nowMs:l}){const g=$s(),h=(0,x.useRef)(null),I=(0,x.useRef)(null),f=(0,x.useRef)(null),u=(0,x.useRef)(null),y=(0,x.useRef)(null),[w,b]=(0,x.useState)(null),[q,$]=(0,x.useState)(null),[K,F]=(0,x.useState)(0),[z,Y]=(0,x.useState)(0),[D,V]=(0,x.useState)(null),N=a(()=>{y.current?.(),y.current=null},"clearDocumentDrag"),j=a((m,T)=>{N();const P=a(A=>{N(),T(A)},"handleUp");document.addEventListener("mousemove",m),document.addEventListener("mouseup",P),y.current=()=>{document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",P)}},"setDocumentDrag");(0,x.useEffect)(()=>()=>N(),[]),u.current==null&&(u.current=Date.now());const M=l??u.current,O=n??Nt(s,z||et),d=(0,x.useMemo)(()=>Qa(t,{...be,pxPerMinute:O,nowMs:M}),[t,O,M]),U=(0,x.useMemo)(()=>{if(!q)return null;const m=new Set([q]);let T=!0;for(;T;){T=!1;for(const P of d.connectors)m.has(P.sourceRunId)&&!m.has(P.targetRunId)&&(m.add(P.targetRunId),T=!0),m.has(P.targetRunId)&&!m.has(P.sourceRunId)&&(m.add(P.sourceRunId),T=!0)}return m},[q,d.connectors]),S=(0,x.useMemo)(()=>U?d.connectors.filter(m=>U.has(m.sourceRunId)&&U.has(m.targetRunId)):[],[U,d.connectors]),le=yn(g.pathname),ae=a((m,T)=>{const P=d.gutter+(m-d.fromMs)/6e4*d.pxPerMinute;return Math.max(0,Math.min(d.width-T,P-T/2))},"timeToScrollLeft"),k=a(m=>{const T=m.scrollLeft+m.clientWidth/2;return d.fromMs+(T-d.gutter)/d.pxPerMinute*6e4},"scrollCenterMs");(0,x.useEffect)(()=>{const m=h.current;if(!m)return;const T=m.clientWidth;T>0&&T!==z&&Y(T);const P=`${t.window.from}:${t.window.to}`;if(I.current!==P){I.current=P;const A=Math.max(0,d.width-T);m.scrollLeft=A,F(A),f.current=k(m);return}if(f.current!=null){const A=ae(f.current,T);m.scrollLeft=A,F(A)}},[t.window.from,t.window.to,d.fromMs,d.gutter,d.pxPerMinute,d.toMs,d.width,z]),(0,x.useEffect)(()=>{r&&r(si(yt(z||et)/d.pxPerMinute))},[d.pxPerMinute,r,z]),(0,x.useEffect)(()=>{!c||z<=0||c(zs(d,K,z))},[d.fromMs,d.toMs,d.pxPerMinute,c,K,z]);const H=Ga(d.pxPerMinute),v=[],X=Math.ceil(d.fromMs/H)*H;for(let m=X;m<=d.toMs;m+=H)v.push(m);const Z=a(m=>{const T=jn(`/issues/${encodeURIComponent(m)}`,le);window.open(T,"_blank","noopener,noreferrer")},"openIssue"),L=a((m,T)=>{if(!i)return;const P=h.current,A=Math.max(d.fromMs,Math.min(d.toMs,m)),B=Math.max(d.fromMs,Math.min(d.toMs,T)),re=Math.min(A,B),ce=Math.max(ht,Math.max(A,B)-re),C=re+ce/2,se=P?.clientWidth||z||et,ve=Ct(yt(se)/(ce/6e4));f.current=C,i(ve,kt(ve,se))},"updateVisibleRange"),pe=a((m,T)=>{const P=T.getBoundingClientRect();if(P.width<=0)return d.gutter;const A=(m-P.left)/P.width*d.width;return Math.max(d.gutter,Math.min(d.width-40,A))},"svgXFromClientX"),me=a(m=>d.fromMs+(m-d.gutter)/d.pxPerMinute*6e4,"msFromSvgX"),Se=a(m=>{if(!i||m.button!==0)return;const T=m.currentTarget,P=pe(m.clientX,T);m.preventDefault(),b(null),$(null),V({anchorX:P,currentX:P}),j(a(re=>{V(ce=>ce&&{...ce,currentX:pe(re.clientX,T)})},"move"),a(re=>{const ce=pe(re.clientX,T);if(V(null),Math.abs(ce-P)<8)return;const C=Math.min(me(P),me(ce)),se=Math.max(me(P),me(ce));L(C,se)},"up"))},"handlePlotMouseDown"),he=a(m=>{const T=d.connectors.filter(P=>P.sourceRunId===m.span.runId||P.targetRunId===m.span.runId);return T.length===0?null:T.some(P=>P.dashed)?"dashed handoff: retry or changes requested":"solid handoff: delegation or assignment"},"connectorHintForBar"),ie=a((m,T)=>{$(T.span.runId),b({x:m.clientX,y:m.clientY,bar:T,connectorHint:he(T)})},"showTooltip"),E=a(m=>{if(!i||!(m.ctrlKey||m.metaKey||m.altKey))return;m.preventDefault();const T=h.current;T&&(f.current=k(T));const P=Ct(d.pxPerMinute*Math.exp(-m.deltaY*.001));i(P,kt(P,T?.clientWidth??z))},"handleWheel");return(0,e.jsxs)("div",{className:"relative",children:[(0,e.jsx)("div",{ref:h,className:"max-h-(--sz-70vh) overflow-auto","data-testid":"work-timeline-scroll",onScroll:a(m=>{F(m.currentTarget.scrollLeft),f.current=k(m.currentTarget)},"onScroll"),onWheel:E,children:(0,e.jsxs)("div",{className:"relative",style:{width:d.width,height:d.height},children:[(0,e.jsx)(ai,{rows:d.rows,height:d.height}),(0,e.jsxs)("svg",{width:d.width,height:d.height,viewBox:`0 0 ${d.width} ${d.height}`,className:"absolute inset-0 block select-none",onMouseDown:Se,ref:a(m=>{m&&z===0&&h.current&&Y(h.current.clientWidth)},"ref"),children:[(0,e.jsx)("defs",{children:(0,e.jsxs)("linearGradient",{id:"tl-fade",x1:"0",y1:"0",x2:"1",y2:"0",children:[(0,e.jsx)("stop",{offset:"0%",stopColor:"var(--color-ink)",stopOpacity:.28}),(0,e.jsx)("stop",{offset:"100%",stopColor:"var(--color-ink)",stopOpacity:0})]})}),d.rows.map((m,T)=>(0,e.jsx)("rect",{x:0,y:m.y+32,width:d.width,height:m.h,fill:T%2?"var(--color-bg-3)":"transparent",opacity:T%2?.35:1},`bg-${m.actor.id}`)),v.map(m=>{const T=d.gutter+(m-d.fromMs)/6e4*d.pxPerMinute;return(0,e.jsx)("g",{children:(0,e.jsx)("line",{x1:T,y1:32,x2:T,y2:d.height,stroke:"var(--color-line)",strokeWidth:1})},`tick-${m}`)}),M>=d.fromMs&&M<=d.toMs&&(0,e.jsx)("line",{x1:d.gutter+(M-d.fromMs)/6e4*d.pxPerMinute,y1:32,x2:d.gutter+(M-d.fromMs)/6e4*d.pxPerMinute,y2:d.height,stroke:Be.now,strokeWidth:1.5,strokeDasharray:"2 3",opacity:.9}),(0,e.jsx)("line",{x1:d.gutter,y1:0,x2:d.gutter,y2:d.height,stroke:"var(--color-ink)",strokeWidth:1.5}),(0,e.jsx)("line",{x1:0,y1:32,x2:d.width,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5}),S.map((m,T)=>{const P=m.y1+32,A=m.y2+32,B=m.x2>=m.x1?`M${m.x2},${A} l-10,-5 l0,10 z`:`M${m.x2},${A} l10,-5 l0,10 z`;return(0,e.jsxs)("g",{"data-testid":"timeline-connector",opacity:.86,children:[(0,e.jsx)("path",{d:`M${m.x1},${P} V${A} H${m.x2}`,fill:"none",stroke:"var(--color-ink)",strokeWidth:2.2,strokeDasharray:m.dashed?"5 4":void 0}),(0,e.jsx)("circle",{cx:m.x1,cy:P,r:3.2,fill:"var(--color-ink)"}),(0,e.jsx)("path",{d:B,fill:"var(--color-ink)"})]},`edge-${m.sourceRunId}-${m.targetRunId}-${T}`)}),d.rows.map(m=>{const T=m.y+32+m.h/2,P=Bt(`plot-${m.actor.id}`);return(0,e.jsxs)("g",{children:[(0,e.jsx)(Ut,{actor:m.actor,cx:26,cy:T,r:Ws,clipId:P}),(0,e.jsx)("text",{x:47,y:T+4,fontSize:13,fill:"var(--color-ink)",children:Qt(m.actor.name,18)}),Array.from({length:m.laneCount}).map((A,B)=>{const re=m.y+32+6+B*(be.barH+be.laneGap)+be.barH/2;return(0,e.jsx)("line",{x1:d.gutter,y1:re,x2:d.width-8,y2:re,stroke:"var(--color-line)",strokeWidth:1,strokeDasharray:"2 4",opacity:.6},`lane-${m.actor.id}-${B}`)}),m.bars.map(A=>{const B=A.yTop+32,re=A.x2-A.x1,ce=Ft(A.span.status),C=_s(A),se=U==null?"idle":U.has(A.span.runId)?"connected":"faded",ve=se==="idle"?.88:se==="connected"?1:.22;return(0,e.jsxs)("g",{opacity:se==="faded"?.42:1,children:[(0,e.jsxs)("g",{className:"cursor-pointer","data-run-id":A.span.runId,"data-connected-state":se,onMouseEnter:a(Ae=>ie(Ae,A),"onMouseEnter"),onMouseOver:a(Ae=>ie(Ae,A),"onMouseOver"),onMouseMove:a(Ae=>ie(Ae,A),"onMouseMove"),onMouseLeave:a(()=>{b(null),$(null)},"onMouseLeave"),onMouseDown:a(Ae=>Ae.stopPropagation(),"onMouseDown"),onClick:a(()=>Z(A.span.issueId),"onClick"),children:[(0,e.jsx)("rect",{x:A.x1,y:B,width:re,height:A.height,rx:3,fill:ce?"transparent":C,stroke:ce?Be.cancelled:"var(--color-ink)",strokeWidth:1.5,strokeDasharray:ce?"4 3":void 0,opacity:ve}),A.running&&!ce&&re>8&&(0,e.jsx)("rect",{x:A.x2-Math.min(re-2,26),y:B+1.5,width:Math.min(re-2,26),height:A.height-3,fill:"url(#tl-fade)"})]}),A.kickoff&&Oa(A.kickoff)==="user"&&(0,e.jsx)("g",{className:"pointer-events-none","data-testid":"timeline-kickoff-chip",children:(0,e.jsx)(Ut,{actor:A.kickoff,cx:A.x1,cy:B+A.height/2,r:ei,clipId:Bt(`kickoff-${A.span.runId}-${A.kickoff.id}`)})})]},A.span.runId)})]},`row-${m.actor.id}`)}),D&&(0,e.jsx)("rect",{"data-testid":"timeline-drag-selection",x:Math.min(D.anchorX,D.currentX),y:32,width:Math.abs(D.currentX-D.anchorX),height:d.height-32,fill:"var(--color-accent)",opacity:.16,stroke:"var(--color-accent)",strokeWidth:1.5,pointerEvents:"none"})]})]})}),(0,e.jsx)(ii,{layout:d,ticks:v,stepMs:H,scrollLeft:K}),(0,e.jsx)(oi,{layout:d,scrollRef:h,viewportW:z,scrollLeft:K,onVisibleRangeChange:L}),w&&(0,e.jsx)(ri,{tooltip:w,now:M})]})}a(ni,"WorkTimelineChart");function ai({rows:t,height:s}){return(0,e.jsxs)("svg",{"aria-hidden":"true","data-testid":"work-timeline-actor-gutter",width:be.gutter,height:s,viewBox:`0 0 ${be.gutter} ${s}`,className:"sticky left-0 z-20 block bg-bg-2",children:[(0,e.jsx)("rect",{x:0,y:0,width:be.gutter,height:s,fill:"var(--color-bg-2)"}),t.map((n,i)=>{const r=n.y+32+n.h/2,c=Bt(`gutter-${n.actor.id}`);return(0,e.jsxs)("g",{children:[(0,e.jsx)("rect",{x:0,y:n.y+32,width:be.gutter,height:n.h,fill:i%2?"var(--color-bg-3)":"var(--color-bg-2)",opacity:i%2?.35:1}),(0,e.jsx)(Ut,{actor:n.actor,cx:26,cy:r,r:Ws,clipId:c}),(0,e.jsx)("text",{x:47,y:r+4,fontSize:13,fill:"var(--color-ink)",children:Qt(n.actor.name,16)})]},`gutter-${n.actor.id}`)}),(0,e.jsx)("line",{x1:be.gutter,y1:0,x2:be.gutter,y2:s,stroke:"var(--color-ink)",strokeWidth:1.5}),(0,e.jsx)("line",{x1:0,y1:32,x2:be.gutter,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5})]})}a(ai,"ActorGutter");function ii({layout:t,ticks:s,stepMs:n,scrollLeft:i}){return(0,e.jsxs)("div",{"aria-hidden":"true","data-testid":"work-timeline-time-axis",className:"pointer-events-none absolute left-0 right-0 top-0 z-30 overflow-hidden bg-bg-2",style:{height:32},children:[(0,e.jsxs)("svg",{width:t.width,height:32,viewBox:`0 0 ${t.width} 32`,className:"block",style:{transform:`translateX(${-i}px)`},children:[(0,e.jsx)("rect",{x:0,y:0,width:t.width,height:32,fill:"var(--color-bg-2)"}),s.map(r=>{const c=t.gutter+(r-t.fromMs)/6e4*t.pxPerMinute;return(0,e.jsxs)("g",{children:[(0,e.jsx)("line",{x1:c,y1:25,x2:c,y2:32,stroke:"var(--color-line)",strokeWidth:1}),(0,e.jsx)("text",{x:c+3,y:19,fontSize:11,fill:"var(--color-ink-3)",children:ti(r,n)})]},`axis-tick-${r}`)}),(0,e.jsx)("line",{x1:0,y1:32,x2:t.width,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5})]}),(0,e.jsxs)("svg",{width:t.gutter,height:32,viewBox:`0 0 ${t.gutter} 32`,className:"absolute left-0 top-0 block bg-bg-2",children:[(0,e.jsx)("rect",{x:0,y:0,width:t.gutter,height:32,fill:"var(--color-bg-2)"}),(0,e.jsx)("line",{x1:t.gutter,y1:0,x2:t.gutter,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5}),(0,e.jsx)("line",{x1:0,y1:32,x2:t.gutter,y2:32,stroke:"var(--color-ink)",strokeWidth:1.5})]})]})}a(ii,"TimeAxisOverlay");function ri({tooltip:t,now:s}){const{bar:n}=t,i=new Date(n.span.start).getTime(),r=n.span.end?new Date(n.span.end).getTime():s,c=n.span.issueTitle??n.span.issueIdentifier??"run",l=Math.min(t.x+14,(typeof window<"u"?window.innerWidth:1200)-300);return(0,e.jsxs)("div",{className:"pointer-events-none fixed z-50 max-w-(--sz-280px) rounded-md border border-ink bg-bg-2 px-2.5 py-2 text-xs shadow-md",style:{left:l,top:t.y+14},children:[(0,e.jsx)("div",{className:"text-(length:--text-compact) font-medium text-ink",children:Qt(c)}),(0,e.jsxs)("div",{className:"mt-0.5 text-ink-3",children:[Lt(i),"–",n.span.end?Lt(r):"now"," · ",qs(i,r)," ·"," ",(0,e.jsx)("span",{className:"font-medium text-ink",children:n.span.status})]}),n.kickoff&&(0,e.jsxs)("div",{className:"text-ink-3",children:["kicked off by: ",n.kickoff.name,n.span.retryOfRunId?" · retry":""]}),t.connectorHint&&(0,e.jsx)("div",{className:"text-ink-3",children:t.connectorHint})]})}a(ri,"Tooltip");function oi({layout:t,scrollRef:s,viewportW:n,scrollLeft:i,onVisibleRangeChange:r}){const c=(0,x.useRef)(null),l=Math.max(320,n||900),g=54,h=8,I=t.toMs-t.fromMs||1,f=a(j=>h+(j-t.fromMs)/I*(l-16),"mx"),u=new Map(t.rows.map((j,M)=>[j.actor.id,M])),y=38/Math.max(1,t.rows.length),w=zs(t,i,n||l),b=w.fromMs,q=w.toMs,$=f(b),K=Math.max(24,f(q)-$),F=14,z=a(()=>{c.current?.(),c.current=null},"clearDocumentDrag"),Y=a((j,M)=>{z();const O=a(d=>{z(),M(d)},"handleUp");document.addEventListener("mousemove",j),document.addEventListener("mouseup",O),c.current=()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",O)}},"setDocumentDrag");(0,x.useEffect)(()=>()=>z(),[]);const D=a((j,M)=>{const O=M.getBoundingClientRect(),d=Math.min(1,Math.max(0,(j-O.left-h)/(l-16)));return t.fromMs+d*I},"msAtClientX"),V=a((j,M)=>{const O=D(j,M);s.current&&(s.current.scrollLeft=t.gutter+(O-t.fromMs)/6e4*t.pxPerMinute-s.current.clientWidth/2)},"seek"),N=a((j,M)=>{M.preventDefault(),M.stopPropagation();const O=M.currentTarget.ownerSVGElement;if(!O)return;const d=b,U=q,S=Math.max(ht,U-d);Y(a(ae=>{const k=D(ae.clientX,O);if(j==="left")r(Math.min(k,U-ht),U);else if(j==="right")r(d,Math.max(k,d+ht));else{const H=Math.max(t.fromMs,Math.min(t.toMs-S,k-S/2));r(H,H+S)}},"move"),()=>{})},"startRangeDrag");return(0,e.jsx)("div",{className:"mt-2 border-t border-line bg-bg-2 px-3.5 py-2",children:(0,e.jsxs)("svg",{width:l,height:g,viewBox:`0 0 ${l} ${g}`,className:"block cursor-grab active:cursor-grabbing",onMouseDown:a(j=>{const M=j.currentTarget;V(j.clientX,M),Y(a(d=>V(d.clientX,M),"move"),()=>{})},"onMouseDown"),children:[(0,e.jsx)("rect",{x:0,y:0,width:l,height:g,fill:"var(--color-bg-2)",stroke:"var(--color-ink)",strokeWidth:1.5}),t.rows.flatMap(j=>j.bars.map(M=>{const O=new Date(M.span.start).getTime(),d=M.span.end?new Date(M.span.end).getTime():t.toMs,U=h+(u.get(j.actor.id)??0)*y;return(0,e.jsx)("rect",{x:f(O),y:U+1,width:Math.max(2,f(d)-f(O)),height:Math.max(2,y-2),fill:Ft(M.span.status)?Be.cancelled:_s(M),opacity:Ft(M.span.status)?.5:1},`mm-${M.span.runId}`)})),(0,e.jsx)("rect",{x:$,y:1,width:K,height:52,fill:"var(--color-ink)",opacity:.12,stroke:"var(--color-ink)",strokeWidth:1.5,onMouseDown:a(j=>N("move",j),"onMouseDown")}),(0,e.jsx)(ks,{x:$,y:1,height:52,width:F,testId:"timeline-minimap-left-handle",label:"Drag left edge to resize visible range",onMouseDown:a(j=>N("left",j),"onMouseDown")}),(0,e.jsx)(ks,{x:$+K,y:1,height:52,width:F,testId:"timeline-minimap-right-handle",label:"Drag right edge to resize visible range",onMouseDown:a(j=>N("right",j),"onMouseDown")})]})})}a(oi,"MiniMap");function ks({x:t,y:s,width:n,height:i,testId:r,label:c,onMouseDown:l}){const g=t-n/2,h=s+i/2-7;return(0,e.jsxs)("g",{"data-testid":r,className:"cursor-grab active:cursor-grabbing",onMouseDown:l,children:[(0,e.jsx)("title",{children:c}),(0,e.jsx)("rect",{x:g,y:s,width:n,height:i,rx:3,fill:"var(--color-ink)",opacity:.16}),(0,e.jsx)("line",{x1:t-3,y1:h,x2:t-3,y2:h+14,stroke:"var(--color-ink)",strokeWidth:1.5,opacity:.85}),(0,e.jsx)("line",{x1:t,y1:h,x2:t,y2:h+14,stroke:"var(--color-ink)",strokeWidth:1.5,opacity:.85}),(0,e.jsx)("line",{x1:t+3,y1:h,x2:t+3,y2:h+14,stroke:"var(--color-ink)",strokeWidth:1.5,opacity:.85})]})}a(ks,"MiniMapHandle");var Cs=500;function li(t){return`${t.actorId}\0${t.kind}\0${t.issueId}\0${t.at}`}a(li,"timelineEventKey");function ci(t){return`${t.fromActorId}\0${t.toActorId}\0${t.issueId}\0${t.at}\0${t.kind}`}a(ci,"timelineEdgeKey");async function di(t,s,n){const i=new Map,r=new Map,c=new Map,l=new Map;let g=0,h=null,I=0,f=!1;for(;;){const u=await La.get(t,{...s,limit:Cs,offset:g},{signal:n});h??=u,I=Math.max(I,u.pagination.totalIssues),f||=u.window.capped;for(const w of u.actors)i.set(w.id,w);for(const w of u.spans)r.set(w.runId,w);for(const w of u.events)c.set(li(w),w);for(const w of u.edges)l.set(ci(w),w);if(!u.pagination.hasMore)break;const y=u.pagination.offset+u.pagination.limit;if(y<=g)throw new Error("Timeline pagination did not advance");g=y}if(!h)throw new Error("Timeline response was empty");return{actors:Array.from(i.values()),spans:Array.from(r.values()),events:Array.from(c.values()),edges:Array.from(l.values()),pagination:{limit:Cs,offset:0,totalIssues:I,hasMore:!1},window:{...h.window,capped:f}}}a(di,"loadTimelineWindow");function ut(t){return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}a(ut,"dateInputValue");function ws(t,s=new Date){const n=new Date(s),i=new Date(s);return t==="today"?{fromDate:ut(n),toDate:ut(i)}:(n.setDate(n.getDate()-(t==="7d"?6:29)),{fromDate:ut(n),toDate:ut(i)})}a(ws,"presetRange");function Ks(t){if(!t.fromDate||!t.toDate)return null;const s=new Date(`${t.fromDate}T00:00:00`),n=new Date(`${t.toDate}T23:59:59.999`);return Number.isNaN(s.getTime())||Number.isNaN(n.getTime())||s>n?null:{from:s.toISOString(),to:n.toISOString()}}a(Ks,"rangeWindow");function ui(t){return!t.fromDate||!t.toDate?"Choose a start and end date.":Ks(t)?null:"Start date must be before end date."}a(ui,"rangeError");function Ms(t){return new Intl.NumberFormat("en-US").format(t)}a(Ms,"formatInteger");function mi(t){return new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(t)}a(mi,"formatCompactInteger");function xi(t){return new Date(t.start).getTime()}a(xi,"spanStartMs");function pi(t,s){return t.end?new Date(t.end).getTime():s}a(pi,"spanEndMs");function hi(t,s,n,i){const r=xi(t),c=pi(t,s);return{clippedMs:Math.max(0,Math.min(c,i)-Math.max(r,n)),rawMs:Math.max(0,c-r)}}a(hi,"spanWindowOverlap");function gi(t,s,n){const i=t.usage?.totalTokens??0;return i<=0||n<=0?0:s<=0||n>=s?i:Math.round(i*(n/s))}a(gi,"spanWindowTokens");function _t(t){return{fromMs:new Date(t.window.from).getTime(),toMs:new Date(t.window.to).getTime()}}a(_t,"dataWindow");function fi(t,s=_t(t)){const n=new Map(t.actors.map(f=>[f.id,f])),i=new Set,r=_t(t),c=Math.max(r.fromMs,Math.min(r.toMs,s.fromMs)),l=Math.max(c,Math.min(r.toMs,s.toMs));let g=0,h=0,I=0;for(const f of t.spans){const u=hi(f,r.toMs,c,l);u.clippedMs<=0||(I+=1,n.get(f.actorId)?.type==="agent"&&i.add(f.actorId),g+=u.clippedMs,h+=gi(f,u.rawMs,u.clippedMs))}return{runs:I,agents:i.size,activeMs:g,totalTokens:h}}a(fi,"timelineSummary");function vi({value:t,options:s,onChange:n}){return(0,e.jsx)("div",{role:"group",className:"inline-flex items-center gap-0.5 rounded-md border border-line-strong bg-bg-2 p-0.5",children:s.map(i=>(0,e.jsx)(Xn,{selected:t===i.value,onClick:a(()=>n(i.value),"onClick"),children:i.label},i.value))})}a(vi,"Segmented");function ji(){return(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-line px-3.5 py-2 text-xs text-ink-3",children:[(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{className:"h-2.5 w-4 rounded-sm",style:{backgroundColor:Be.delegated}}),"Delegated"]}),(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{className:"h-2.5 w-4 rounded-sm",style:{backgroundColor:Be.automation}}),"Automation"]}),(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{className:"h-2.5 w-4 rounded-sm border border-dashed bg-transparent",style:{borderColor:Be.cancelled}}),"Cancelled"]}),(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{className:"h-3.5 w-0.5",style:{backgroundColor:Be.now}}),"Now"]})]})}a(ji,"TimelineLegend");function bi({summary:t}){const s=[{label:"Runs",value:Ms(t.runs),icon:We},{label:"Agents",value:Ms(t.agents),icon:kn},{label:"Run time",value:qs(0,t.activeMs),icon:Yn},{label:"Tokens used",value:t.totalTokens>0?mi(t.totalTokens):"Not tracked",icon:vt}];return(0,e.jsx)("dl",{className:"grid flex-1 grid-cols-2 gap-3 border-y border-line py-3 md:grid-cols-4",children:s.map(n=>{const i=n.icon;return(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("dt",{className:"flex items-center gap-1.5 text-xs text-ink-3",children:[(0,e.jsx)(i,{className:"h-3.5 w-3.5 shrink-0"}),(0,e.jsx)("span",{children:n.label})]}),(0,e.jsx)("dd",{className:"mt-1 truncate text-lg font-semibold tabular-nums text-ink",children:n.value})]},n.label)})})}a(bi,"TimelineSummaryStats");function yi({embedded:t=!1}={}){const{selectedCompanyId:s}=Kt(),{setBreadcrumbs:n}=Xt(),i=$s(),r=(0,x.useMemo)(()=>new URLSearchParams(i.search).get("projectId")||void 0,[i.search]),[c,l]=(0,x.useState)("day"),[g,h]=(0,x.useState)(void 0),I=(0,x.useRef)(!1),[f,u]=(0,x.useState)("7d"),[y,w]=(0,x.useState)(()=>ws("7d")),[b,q]=(0,x.useState)(null);(0,x.useEffect)(()=>{t||n([{label:r?"Project Timeline":"Timeline"}])},[t,r,n]);const $=ui(y),K=(0,x.useMemo)(()=>{const d=Ks(y);return d?r?{...d,projectId:r}:d:null},[y,r]),{data:F,isLoading:z,error:Y}=oe({queryKey:[...J.workTimeline(s??""),y.fromDate,y.toDate,r??null],queryFn:a(({signal:d})=>di(s,K,d),"queryFn"),enabled:!!s&&!!K});(0,x.useEffect)(()=>{if(!F||I.current)return;const d=Ns(new Date(F.window.from).getTime(),new Date(F.window.to).getTime());l(d),h(void 0)},[F]),(0,x.useEffect)(()=>{q(null)},[F?.window.from,F?.window.to]);const D=(0,x.useCallback)(d=>{q(U=>U?.fromMs===d.fromMs&&U.toMs===d.toMs?U:d)},[]);if(!s)return(0,e.jsxs)(e.Fragment,{children:[!t&&(0,e.jsx)(js,{}),(0,e.jsx)(Re,{icon:We,message:"Select an organization to view its work timeline."})]});const V=(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(We,{className:"h-6 w-6 text-ink-3"}),(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:r?"Project Timeline":"Work Timeline"})]}),N=a(d=>{I.current=!0;const U=Ct((g??Nt(c))*d);h(U),l(kt(U))},"adjustZoom"),j=a(()=>{I.current=!0,l(F?Ns(new Date(F.window.from).getTime(),new Date(F.window.to).getTime()):"day"),h(void 0)},"resetZoom"),M=F?fi(F,b??_t(F)):null,O=(0,e.jsxs)("label",{className:"flex min-w-0 flex-wrap items-center gap-2 text-xs text-ink-3",children:["Range",(0,e.jsx)(vi,{value:f,onChange:a(d=>{d!=="custom"&&(u(d),w(ws(d)))},"onChange"),options:[{value:"today",label:"Today"},{value:"7d",label:"7 days"},{value:"30d",label:"30 days"}]}),(0,e.jsx)(qe,{type:"date",value:y.fromDate,onChange:a(d=>{u("custom"),w(U=>({...U,fromDate:d.target.value}))},"onChange"),className:"h-8 w-(--sz-150px) text-xs","aria-label":"Timeline start date"}),(0,e.jsx)("span",{children:"to"}),(0,e.jsx)(qe,{type:"date",value:y.toDate,onChange:a(d=>{u("custom"),w(U=>({...U,toDate:d.target.value}))},"onChange"),className:"h-8 w-(--sz-150px) text-xs","aria-label":"Timeline end date"})]});return(0,e.jsxs)("div",{className:"space-y-6",children:[!t&&(0,e.jsx)(js,{}),V,(0,e.jsxs)("div",{className:"flex flex-wrap items-start gap-3",children:[M&&(0,e.jsx)(bi,{summary:M}),(0,e.jsxs)("div",{className:"ml-auto flex items-center gap-1 pt-3","aria-label":"Timeline zoom controls",children:[(0,e.jsx)(te,{type:"button",variant:"secondary",size:"icon-xs",onClick:a(()=>N(.8),"onClick"),"aria-label":"Zoom out",title:"Zoom out",children:(0,e.jsx)(Mn,{className:"h-3 w-3"})}),(0,e.jsx)(te,{type:"button",variant:"secondary",size:"icon-xs",onClick:a(()=>N(1.25),"onClick"),"aria-label":"Zoom in",title:"Zoom in",children:(0,e.jsx)(Tn,{className:"h-3 w-3"})}),(0,e.jsx)(te,{type:"button",variant:"secondary",size:"icon-xs",onClick:j,"aria-label":"Reset zoom",title:"Reset zoom",children:(0,e.jsx)(In,{className:"h-3 w-3"})})]})]}),z&&(0,e.jsx)(xt,{}),$&&(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(Re,{icon:We,message:$}),(0,e.jsx)("div",{className:"flex flex-wrap items-center justify-end gap-3",children:O})]}),Y&&(0,e.jsx)(Re,{icon:We,message:"Couldn't load the timeline. The aggregation endpoint may be unavailable."}),F&&!z&&!$&&(F.spans.length===0?(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsx)(Re,{icon:We,message:r?"No project activity in this window.":"No activity in this window."}),(0,e.jsx)("div",{className:"flex flex-wrap items-center justify-end gap-3",children:O})]}):(0,e.jsxs)("div",{className:"space-y-3",children:[(0,e.jsxs)(ne,{className:"block py-0",children:[(0,e.jsx)(ji,{}),(0,e.jsx)(ni,{data:F,zoom:c,zoomScale:g,onVisibleWindowChange:D,onZoomScaleChange:a((d,U=kt(d))=>{I.current=!0,h(d),l(U)},"onZoomScaleChange")})]}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:[F.spans.length," run",F.spans.length===1?"":"s"," ·"," ",new Date(F.window.from).toLocaleString()," to ",new Date(F.window.to).toLocaleString(),F.window.capped?" · window capped":""]}),O]})]}))]})}a(yi,"Timeline");function Ss(t){const s=new URLSearchParams;return t.actorScope&&s.set("actorScope",t.actorScope),t.agentId&&s.set("agentId",t.agentId),t.responsibleUserId&&s.set("responsibleUserId",t.responsibleUserId),t.runId&&s.set("runId",t.runId),t.entityType&&s.set("entityType",t.entityType),t.entityId&&s.set("entityId",t.entityId),t.action&&s.set("action",t.action),t.from&&s.set("from",t.from),t.to&&s.set("to",t.to),t.actorType&&s.set("actorType",t.actorType),t.cursor&&s.set("cursor",t.cursor),t.limit!=null&&s.set("limit",String(t.limit)),s}a(Ss,"buildAuditQuery");var Ts={listAgentActions:a((t,s={})=>{const n=Ss(s).toString();return de.get(`/companies/${t}/audit/agent-actions${n?`?${n}`:""}`)},"listAgentActions"),exportAgentActionsCsv:a(async(t,s={})=>{const n=Ss(s).toString(),i=await fetch(`/api/companies/${t}/audit/agent-actions.csv${n?`?${n}`:""}`,{credentials:"include",headers:{Accept:"text/csv"}});if(!i.ok){const r=(await i.json().catch(()=>null))?.error??`Export failed: ${i.status}`;throw new Error(r)}return i.blob()},"exportAgentActionsCsv")},Ni=50,ee="__all",ki=[{value:ee,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_",label:"Apps & tools"},{value:"cost.",label:"Costs"},{value:"company.",label:"Organization"}],Ci=[{value:ee,label:"All entities"},{value:"issue",label:"Task"},{value:"agent",label:"Agent"},{value:"heartbeat_run",label:"Run"},{value:"routine",label:"Routine"},{value:"project",label:"Project"},{value:"goal",label:"Goal"},{value:"company",label:"Organization"},{value:"tool_connection",label:"Connection"}];function wi(t){if(!t)return;const s=new Date(`${t}T00:00:00.000Z`);return Number.isNaN(s.getTime())?void 0:s.toISOString()}a(wi,"toStartIso");function Mi(t){if(!t)return;const s=new Date(`${t}T23:59:59.999Z`);return Number.isNaN(s.getTime())?void 0:s.toISOString()}a(Mi,"toEndIso");function Si({record:t,agentMap:s,userProfileMap:n}){const i=t.agentId??(t.actorType==="agent"?t.actorId:null),r=i?s.get(i):null;if(r)return(0,e.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:r.name,children:[(0,e.jsx)("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-bg-3 text-ink-3",children:(0,e.jsx)(Rn,{agent:r,size:16,className:"h-3 w-3"})}),(0,e.jsx)("span",{className:"truncate font-medium text-ink",children:r.name})]});if(t.actorType==="user"&&t.actorId){const l=n.get(t.actorId);return(0,e.jsx)(At,{name:l?.label??"User",avatarUrl:l?.image??null,size:"sm",className:"font-medium text-ink"})}const c=t.actorType==="plugin"?"Plugin":t.actorType==="agent"?"Agent":t.actorType==="user"?"User":"System";return(0,e.jsx)(At,{name:c,size:"sm",className:"font-medium text-ink"})}a(Si,"AuditActor");function Ti({record:t}){const{issue:s,document:n}=t.entity,i=s?.identifier??s?.id??null;if(i)return(0,e.jsx)(_e,{to:`/issues/${i}`,className:"font-medium text-accent hover:underline",children:s?.identifier?`${s.identifier}${s.title?` · ${s.title}`:""}`:"the task"});if(n)return(0,e.jsx)("span",{className:"font-medium text-ink",children:n.key});const r=t.entityType==="tool_connection"?t.entityId:typeof t.details?.connectionId=="string"?t.details.connectionId:null;return r?(0,e.jsx)(_e,{to:`/apps/${r}/permissions`,className:"font-medium text-accent hover:underline",children:"the connection"}):(0,e.jsx)("span",{className:"text-ink-3",children:t.entityType})}a(Ti,"AuditEntityNode");function Ii({record:t,agentMap:s,userProfileMap:n}){const i=Zn(t.action,t.details,{agentMap:s,userProfileMap:n}),r=t.responsibleUserId?n.get(t.responsibleUserId):null,c=!!(t.responsibleUserId&&!(t.actorType==="user"&&t.actorId===t.responsibleUserId)),l=r?.label??(t.responsibleUserId?"a user":null),g=t.entity.comment?.excerpt?.trim(),h=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-ink",children:[(0,e.jsx)(Si,{record:t,agentMap:s,userProfileMap:n}),(0,e.jsx)("span",{className:"text-ink-3",children:i}),(0,e.jsx)(Ti,{record:t})]}),g?(0,e.jsxs)("p",{className:"line-clamp-2 border-l-2 border-line pl-2 text-ink-3",children:["“",g,"”"]}):null,h?(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:["Document ",(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro)",children:h})]}):null,(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs text-ink-3",children:[c&&l?(0,e.jsxs)("span",{className:"inline-flex items-center rounded-full bg-bg-3 px-2 py-0.5",children:["on behalf of ",l]}):null,t.runId&&t.agentId?(0,e.jsx)(_e,{to:`/agents/${t.agentId}/runs/${t.runId}`,className:"text-accent 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-ink-3",dateTime:t.createdAt,title:new Date(t.createdAt).toLocaleString(),children:Ot(t.createdAt)})]})})}a(Ii,"AuditRow");function Ai(){return(0,e.jsx)(ne,{children:(0,e.jsxs)(ue,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)(Dn,{className:"h-10 w-10 text-ink-3/50"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-sm font-medium text-ink",children:"Agent audit is a Wardmote Enterprise view"}),(0,e.jsxs)("p",{className:"mx-auto mt-1 max-w-md text-sm text-ink-3",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."]})]})]})})}a(Ai,"AuditUpsell");function Di({companyId:t,lockedAgentId:s,lockedRunId:n,lockedEntity:i,hideHeader:r,mode:c,onModeChange:l,actionDomain:g,onActionDomainChange:h}){const{pushToast:I}=En(),[f,u]=(0,x.useState)(ee),[y,w]=(0,x.useState)(ee),[b,q]=(0,x.useState)(ee),$=g??b,K=a(C=>{q(C),h?.(C)},"setActionDomain"),[F,z]=(0,x.useState)(ee),[Y,D]=(0,x.useState)(""),[V,N]=(0,x.useState)(""),[j,M]=(0,x.useState)(!1),[O,d]=(0,x.useState)(!1),U=oe({queryKey:J.agents.list(t),queryFn:a(()=>Rs.list(t),"queryFn")}),S=oe({queryKey:J.access.companyUserDirectory(t),queryFn:a(()=>On.listUserDirectory(t),"queryFn"),retry:!1}),le=(0,x.useMemo)(()=>new Map((U.data??[]).map(C=>[C.id,C])),[U.data]),ae=(0,x.useMemo)(()=>Gn(S.data?.users),[S.data]),k=s||n?"agents":c??"all",H=!!(s||n||i),v={actorScope:k,agentId:s??(f===ee?void 0:f),runId:n,responsibleUserId:y===ee?void 0:y,action:$===ee?void 0:$,entityType:i?.type??(F===ee?void 0:F),entityId:i?.id,from:wi(Y),to:Mi(V)},X=!!(!s&&f!==ee||y!==ee||$!==ee||F!==ee||Y||V),Z=!H&&(f!==ee||y!==ee),L=vn({queryKey:J.audit.agentActions(t,{actorScope:v.actorScope,agentId:v.agentId,runId:v.runId,responsibleUserId:v.responsibleUserId,action:v.action,entityType:v.entityType,entityId:v.entityId,from:v.from,to:v.to}),queryFn:a(({pageParam:C})=>Ts.listAgentActions(t,{...v,limit:Ni,cursor:C??void 0}),"queryFn"),initialPageParam:null,getNextPageParam:a(C=>C.nextCursor??void 0,"getNextPageParam"),retry:a((C,se)=>!(se instanceof cs&&se.status===403)&&C<2,"retry")}),pe=L.error instanceof cs&&L.error.status===403,me=L.data?.pages.some(C=>C.accessTier==="basic")??!1,Se=L.data?.pages.some(C=>C.accessTier==="full")??!1,he=(0,x.useMemo)(()=>{const C=L.data?.pages??[];return(me?C.filter(se=>se.accessTier!=="full"):C).flatMap(se=>se.items)},[L.data,me]),ie=me?"basic":L.data?.pages[0]?.accessTier,E=me&&Se,m=s||n?!0:ie==="full",T=!!(E&&O&&!L.isFetching),P=!!(!H&&!T&&(pe&&Z||E)),A=!!(pe&&!H&&k==="agents"&&l),B=!!(!H&&l&&!A);(0,x.useEffect)(()=>{A&&l?.("all")},[A,l]),(0,x.useEffect)(()=>{!H&&(ie==="basic"||P)&&(u(ee),w(ee))},[ie,H,P]),(0,x.useEffect)(()=>{if(!E){O&&d(!1);return}O||(d(!0),L.refetch())},[O,L,E]);const re=a(()=>{u(ee),w(ee),K(ee),z(ee),D(""),N("")},"clearFilters"),ce=a(async()=>{M(!0);try{const C=await Ts.exportAgentActionsCsv(t,{actorScope:v.actorScope,agentId:v.agentId,runId:v.runId,responsibleUserId:v.responsibleUserId,action:v.action,entityType:v.entityType,entityId:v.entityId,from:v.from,to:v.to}),se=URL.createObjectURL(C),ve=document.createElement("a");ve.href=se,ve.download=`${k==="agents"?"agent-audit":"activity"}-${t}.csv`,document.body.appendChild(ve),ve.click(),ve.remove(),window.setTimeout(()=>URL.revokeObjectURL(se),5e3),I({title:"Audit exported",body:"Your CSV download has started.",tone:"success"})}catch(C){I({title:"Export failed",body:C instanceof Error?C.message:"Could not export the audit log.",tone:"error"})}finally{M(!1)}},"handleExport");return pe&&!P&&!A?(0,e.jsx)(Ai,{}):(0,e.jsxs)("div",{className:"space-y-4",children:[r?null:(0,e.jsx)("div",{className:"flex flex-wrap items-start justify-between gap-3",children:(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold text-ink",children:"Activity"}),(0,e.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-ink-3",children:k==="agents"?"Every recorded agent action, newest first — with the responsible person and run behind each one.":"Everything happening in your organization, newest first — people, agents, and the system. Each line is one recorded action."})]})}),B?(0,e.jsx)(Je,{value:k,onValueChange:a(C=>l?.(C),"onValueChange"),children:(0,e.jsxs)(Ps,{"aria-label":"Activity scope",children:[(0,e.jsx)($e,{value:"all",children:"Activity"}),(0,e.jsx)($e,{value:"agents",disabled:ie==="basic",title:ie==="basic"?"Agent Actions requires audit access":void 0,children:"Agent Actions"})]})}):null,H?(0,e.jsx)("div",{className:"border-y border-line px-1 py-2 text-xs text-ink-3",children:n?`Scoped to run ${n.slice(0,8)}`:s?"Scoped to one agent":`Scoped to ${i?.label??i?.type??"entity"}`}):null,(0,e.jsxs)("div",{className:"flex flex-wrap items-end gap-3 border-y border-line py-3",children:[m&&!s&&!n?(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Agent"}),(0,e.jsxs)(Ke,{value:f,onValueChange:u,children:[(0,e.jsx)(Ve,{className:"w-40",children:(0,e.jsx)(He,{placeholder:"Agent"})}),(0,e.jsxs)(Xe,{children:[(0,e.jsx)(Ie,{value:ee,children:"All agents"}),(U.data??[]).map(C=>(0,e.jsx)(Ie,{value:C.id,children:C.name},C.id))]})]})]}):null,m?(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Responsible user"}),(0,e.jsxs)(Ke,{value:y,onValueChange:w,children:[(0,e.jsx)(Ve,{className:"w-52",children:(0,e.jsx)(He,{placeholder:"Responsible user"})}),(0,e.jsxs)(Xe,{children:[(0,e.jsx)(Ie,{value:ee,children:"All responsible users"}),(S.data?.users??[]).map(C=>(0,e.jsx)(Ie,{value:C.principalId,children:C.user?.name??C.user?.email??C.principalId.slice(0,8)},C.principalId))]})]})]}):null,(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Action"}),(0,e.jsxs)(Ke,{value:$,onValueChange:K,children:[(0,e.jsx)(Ve,{className:"w-40",children:(0,e.jsx)(He,{placeholder:"Action"})}),(0,e.jsx)(Xe,{children:ki.map(C=>(0,e.jsx)(Ie,{value:C.value,children:C.label},C.value))})]})]}),i?null:(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Entity"}),(0,e.jsxs)(Ke,{value:F,onValueChange:z,children:[(0,e.jsx)(Ve,{className:"w-40",children:(0,e.jsx)(He,{placeholder:"Entity"})}),(0,e.jsx)(Xe,{children:Ci.map(C=>(0,e.jsx)(Ie,{value:C.value,children:C.label},C.value))})]})]}),(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"From"}),(0,e.jsx)(qe,{type:"date","aria-label":"From date",value:Y,max:V||void 0,onChange:a(C=>D(C.target.value),"onChange"),className:"w-36"})]}),(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"To"}),(0,e.jsx)(qe,{type:"date","aria-label":"To date",value:V,min:Y||void 0,onChange:a(C=>N(C.target.value),"onChange"),className:"w-36"})]}),X?(0,e.jsx)(te,{variant:"ghost",size:"sm",onClick:re,children:"Clear filters"}):null,m?(0,e.jsxs)(te,{variant:"secondary",size:"sm",className:"ml-auto",onClick:ce,disabled:j||L.isLoading||he.length===0,children:[(0,e.jsx)(Hn,{className:"mr-1.5 h-4 w-4"}),j?"Exporting…":"Export CSV"]}):null]}),P||A?(0,e.jsx)(ne,{children:(0,e.jsx)(ue,{className:"py-14 text-center text-sm text-ink-3",children:"Refreshing audit access…"})}):L.isLoading?(0,e.jsx)(ne,{children:(0,e.jsx)(ue,{className:"py-14 text-center text-sm text-ink-3",children:"Loading…"})}):L.error?(0,e.jsx)(ne,{children:(0,e.jsxs)(ue,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-ink-3",children:L.error instanceof Error?L.error.message:"Failed to load the audit log."}),(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>L.refetch(),"onClick"),children:"Try again"})]})}):he.length===0?(0,e.jsx)(ne,{children:(0,e.jsxs)(ue,{className:"flex flex-col items-center gap-3 py-14 text-center",children:[(0,e.jsx)(An,{className:"h-10 w-10 text-ink-3/40"}),(0,e.jsxs)("div",{children:[(0,e.jsx)("p",{className:"text-sm font-medium text-ink",children:X?"No actions match these filters":"Nothing here yet"}),(0,e.jsx)("p",{className:"mt-1 max-w-md text-sm text-ink-3",children:X?"Try a wider date range or different filters.":k==="agents"?"As soon as your agents start doing things, their actions show up here.":"As soon as anyone in your organization does something, it shows up here."})]}),X?(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:re,children:"Clear filters"}):null]})}):(0,e.jsx)("div",{className:"border-y border-line",children:(0,e.jsx)("ul",{className:wt("divide-y divide-line"),"aria-label":"Audit activity",children:he.map(C=>(0,e.jsx)(Ii,{record:C,agentMap:le,userProfileMap:ae},C.id))})}),L.hasNextPage?(0,e.jsx)("div",{className:"flex justify-center",children:(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>L.fetchNextPage(),"onClick"),disabled:L.isFetchingNextPage,children:L.isFetchingNextPage?"Loading…":"Load more"})}):null,(0,e.jsx)("p",{className:"text-xs text-ink-3",children:"Recorded by Wardmote — entries can't be edited. Sensitive values are never stored."})]})}a(Di,"AuditFeed");var ge="__all",gt=200;function $i(t){const s=t.resultJson,n=s?.summary??s?.result??t.error;return typeof n=="string"&&n.trim()?n.trim():null}a($i,"runSummary");function Pi(t){const s=t.startedAt?new Date(t.startedAt).getTime():null,n=t.finishedAt?new Date(t.finishedAt).getTime():null;if(s==null||n==null||!Number.isFinite(s)||!Number.isFinite(n))return null;const i=Math.max(0,Math.round((n-s)/1e3));return i<60?`${i}s`:`${Math.floor(i/60)}m ${i%60}s`}a(Pi,"runDuration");function tt(t){return t.replaceAll("_"," ")}a(tt,"readableSource");function Ri(t){return t.linkedIssue?.title??t.trigger?.label??"Routine run"}a(Ri,"routineRunTitle");function Ei({runs:t,isLoading:s,error:n,onRetry:i}){return s?(0,e.jsx)("div",{className:"border-y border-line py-14 text-center text-sm text-ink-3",children:"Loading routine runs…"}):n?(0,e.jsxs)("div",{className:"flex flex-col items-center gap-3 border-y border-line py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-ink-3",children:n.message}),(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:i,children:"Try again"})]}):t.length===0?(0,e.jsx)(Re,{icon:Vt,message:"No routine runs yet."}):(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold text-ink",children:"Routine runs"}),(0,e.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-ink-3",children:"Executions created by this routine, newest first."})]}),(0,e.jsx)("ul",{className:"divide-y divide-line border-y border-line","aria-label":"Routine runs",children:t.map(r=>{const c=(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)("span",{className:"font-medium text-ink",children:Ri(r)}),(0,e.jsx)(Ht,{status:r.status})]}),(0,e.jsx)("p",{className:"mt-1 truncate text-sm text-ink-3",children:r.trigger?.label??tt(r.source)})]}),(0,e.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-ink-3 sm:justify-end",children:[(0,e.jsx)("span",{className:"capitalize",children:tt(r.source)}),(0,e.jsx)("time",{dateTime:new Date(r.triggeredAt).toISOString(),children:Ot(r.triggeredAt)})]})]}),l="flex flex-col gap-2 px-1 py-3 text-inherit no-underline transition-colors hover:bg-bg-3/50 sm:flex-row sm:items-start sm:justify-between sm:px-3";return(0,e.jsx)("li",{children:r.linkedIssue?(0,e.jsx)(_e,{to:`/issues/${r.linkedIssue.identifier??r.linkedIssue.id}`,className:l,children:c}):(0,e.jsx)("div",{className:l,children:c})},r.id)})}),(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:["Showing the ",gt," most recent routine runs."]})]})}a(Ei,"RoutineScopedRuns");function Fi({companyId:t,routineId:s}){const[n,i]=Wt(),r=n.get("agentId")??ge,c=n.get("runStatus")??ge,l=oe({queryKey:J.agents.list(t),queryFn:a(()=>Rs.list(t),"queryFn"),enabled:!s}),g=oe({queryKey:J.audit.runs(t,r===ge?null:r),queryFn:a(()=>Fn.list(t,r===ge?void 0:r,gt,{summary:!0}),"queryFn"),refetchInterval:15e3,enabled:!s}),h=oe({queryKey:[...J.routines.runs(s??""),"audit"],queryFn:a(()=>mt.listRuns(s,gt),"queryFn"),enabled:!!s,refetchInterval:15e3}),I=(0,x.useMemo)(()=>new Map((l.data??[]).map(b=>[b.id,b])),[l.data]),f=(0,x.useMemo)(()=>Array.from(new Set((g.data??[]).map(b=>b.status))).sort(),[g.data]),u=(0,x.useMemo)(()=>(g.data??[]).filter(b=>c===ge||b.status===c),[g.data,c]),y=a((b,q)=>{i($=>{const K=new URLSearchParams($);return q===ge?K.delete(b):K.set(b,q),K},{replace:!0})},"updateFilter"),w=a(()=>{i(b=>{const q=new URLSearchParams(b);return q.delete("agentId"),q.delete("runStatus"),q},{replace:!0})},"clearFilters");return s?(0,e.jsx)(Ei,{runs:h.data??[],isLoading:h.isLoading,error:h.error instanceof Error?h.error:null,onRetry:a(()=>{h.refetch()},"onRetry")}):(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("h2",{className:"text-lg font-semibold text-ink",children:"Runs"}),(0,e.jsx)("p",{className:"mt-1 max-w-2xl text-sm text-ink-3",children:"Recent agent executions across the organization. Open a run to inspect its transcript, output, and task context."})]}),(0,e.jsxs)("div",{className:"flex flex-wrap items-end gap-3 border-y border-line py-3",children:[(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Agent"}),(0,e.jsxs)(Ke,{value:r,onValueChange:a(b=>y("agentId",b),"onValueChange"),children:[(0,e.jsx)(Ve,{className:"w-48",children:(0,e.jsx)(He,{placeholder:"All agents"})}),(0,e.jsxs)(Xe,{children:[(0,e.jsx)(Ie,{value:ge,children:"All agents"}),(l.data??[]).map(b=>(0,e.jsx)(Ie,{value:b.id,children:b.name},b.id))]})]})]}),(0,e.jsxs)("label",{className:"grid gap-1 text-(length:--text-micro) font-medium text-ink-3",children:[(0,e.jsx)("span",{children:"Status"}),(0,e.jsxs)(Ke,{value:c,onValueChange:a(b=>y("runStatus",b),"onValueChange"),children:[(0,e.jsx)(Ve,{className:"w-40",children:(0,e.jsx)(He,{placeholder:"All statuses"})}),(0,e.jsxs)(Xe,{children:[(0,e.jsx)(Ie,{value:ge,children:"All statuses"}),f.map(b=>(0,e.jsx)(Ie,{value:b,children:tt(b)},b))]})]})]}),r!==ge||c!==ge?(0,e.jsx)(te,{variant:"ghost",size:"sm",onClick:w,children:"Clear filters"}):null]}),g.isLoading?(0,e.jsx)("div",{className:"border-y border-line py-14 text-center text-sm text-ink-3",children:"Loading runs…"}):g.error?(0,e.jsxs)("div",{className:"flex flex-col items-center gap-3 border-y border-line py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-ink-3",children:g.error instanceof Error?g.error.message:"Failed to load runs."}),(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>g.refetch(),"onClick"),children:"Try again"})]}):u.length===0?(0,e.jsx)(Re,{icon:r!==ge||c!==ge?sa:Vt,message:r!==ge||c!==ge?"No runs match these filters.":"No runs yet."}):(0,e.jsx)("ul",{className:"divide-y divide-line border-y border-line","aria-label":"Recent runs",children:u.map(b=>{const q=I.get(b.agentId),$=$i(b),K=Pi(b);return(0,e.jsx)("li",{children:(0,e.jsxs)(_e,{to:`/agents/${b.agentId}/runs/${b.id}`,className:"flex flex-col gap-2 px-1 py-3 text-inherit no-underline transition-colors hover:bg-bg-3/50 sm:flex-row sm:items-start sm:justify-between sm:px-3",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)("span",{className:"font-medium text-ink",children:q?.name??"Unknown agent"}),(0,e.jsx)("span",{className:"font-mono text-(length:--text-micro) text-ink-3",children:b.id.slice(0,8)}),(0,e.jsx)(Ht,{status:b.status})]}),(0,e.jsx)("p",{className:"mt-1 truncate text-sm text-ink-3",children:$??`${tt(b.invocationSource)} run`})]}),(0,e.jsxs)("div",{className:"flex shrink-0 items-center gap-2 text-xs text-ink-3 sm:justify-end",children:[(0,e.jsx)("span",{className:"capitalize",children:tt(b.invocationSource)}),K?(0,e.jsx)("span",{children:K}):null,(0,e.jsx)("time",{dateTime:new Date(b.createdAt).toISOString(),children:Ot(b.createdAt)})]})]})},b.id)})}),(0,e.jsxs)("p",{className:"text-xs text-ink-3",children:["Showing the ",gt," most recent runs."]})]})}a(Fi,"AuditRuns");function Li({companyId:t,routineId:s}){const n=oe({queryKey:[...J.routines.activity(t,s),"audit"],queryFn:a(async()=>{const[r,c]=await Promise.all([mt.get(s),mt.listRuns(s,200)]);return mt.activity(t,s,{triggerIds:r.triggers.map(l=>l.id),runIds:c.map(l=>l.id)})},"queryFn")});if(n.isLoading)return(0,e.jsx)("div",{className:"border-y border-line py-14 text-center text-sm text-ink-3",children:"Loading routine activity…"});if(n.error)return(0,e.jsxs)("div",{className:"flex flex-col items-center gap-3 border-y border-line py-14 text-center",children:[(0,e.jsx)("p",{className:"text-sm text-ink-3",children:n.error instanceof Error?n.error.message:"Failed to load routine activity."}),(0,e.jsx)(te,{variant:"secondary",size:"sm",onClick:a(()=>n.refetch(),"onClick"),children:"Try again"})]});const i=n.data??[];return i.length===0?(0,e.jsx)(Re,{icon:Vt,message:"No routine activity yet."}):(0,e.jsx)("div",{className:"border-y border-line","aria-label":"Routine activity",children:i.map(r=>(0,e.jsx)(ta,{event:r},r.id))})}a(Li,"RoutineAuditActivity");function Rr({section:t}){const s=bn(),{selectedCompanyId:n}=Kt(),{setBreadcrumbs:i}=Xt(),[r,c]=Wt(),l=zn(r),g=l.mode==="agents"?"agents":"all",h=l.entityType==="routine"?l.entityId??void 0:void 0,I=r.get("action"),f=["issue.","agent.","heartbeat.","approval.","project.","goal.","tool_","cost.","company."].includes(I??"")?I:"__all";(0,x.useEffect)(()=>{const w=ds.find(b=>b.value===t);i([{label:"Audit",href:t==="activity"?void 0:"/activity"},...t==="activity"||!w?[]:[{label:w.label}]])},[t,i]);const u=(0,x.useCallback)(w=>{c(b=>{const q=new URLSearchParams(b);return w==="agents"?q.set("mode","agents"):q.delete("mode"),q},{replace:!0})},[c]),y=(0,x.useCallback)(w=>{c(b=>{const q=new URLSearchParams(b);return w==="__all"?q.delete("action"):q.set("action",w),q},{replace:!0})},[c]);return n?(0,e.jsxs)("div",{className:"space-y-6",children:[(0,e.jsx)("div",{children:(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight text-ink",children:"Audit"})}),(0,e.jsx)(Je,{value:t,onValueChange:a(w=>{s(Wn(w,l))},"onValueChange"),children:(0,e.jsx)(Dt,{items:ds,value:t,align:"start"})}),t==="activity"&&h?(0,e.jsx)(Li,{companyId:n,routineId:h}):t==="activity"?(0,e.jsx)(Di,{companyId:n,hideHeader:!0,mode:g,onModeChange:u,actionDomain:f,onActionDomainChange:y,lockedAgentId:l.agentId??void 0,lockedRunId:l.runId??void 0,lockedEntity:l.entityType&&l.entityId?{type:l.entityType,id:l.entityId}:void 0}):t==="runs"?(0,e.jsx)(Fi,{companyId:n,routineId:h}):t==="budgets"?(0,e.jsx)(vs,{embedded:!0,initialTab:"budgets",lockTab:!0}):t==="timeline"?(0,e.jsx)(yi,{embedded:!0}):(0,e.jsx)(vs,{embedded:!0,initialTab:"overview",hideBudgetsTab:!0})]}):(0,e.jsx)(Re,{icon:Vn,message:"Select an organization to view Audit."})}a(Rr,"AuditHub");export{Rr as AuditHub};
|