@tickernelz/paperclip-pro-server 2026.929.0 → 2026.929.2

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.
Files changed (57) hide show
  1. package/dist/build-info.json +1 -1
  2. package/dist/index.js +2 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/middleware/http-log-redaction.d.ts +1 -1
  5. package/dist/middleware/http-log-redaction.d.ts.map +1 -1
  6. package/dist/middleware/http-log-redaction.js +5 -0
  7. package/dist/middleware/http-log-redaction.js.map +1 -1
  8. package/dist/routes/access.d.ts.map +1 -1
  9. package/dist/routes/access.js +6 -0
  10. package/dist/routes/access.js.map +1 -1
  11. package/dist/routes/openapi.d.ts.map +1 -1
  12. package/dist/routes/openapi.js +7 -4
  13. package/dist/routes/openapi.js.map +1 -1
  14. package/dist/services/execution-workspace-policy.d.ts.map +1 -1
  15. package/dist/services/execution-workspace-policy.js +18 -10
  16. package/dist/services/execution-workspace-policy.js.map +1 -1
  17. package/dist/services/execution-workspaces.d.ts.map +1 -1
  18. package/dist/services/execution-workspaces.js +3 -0
  19. package/dist/services/execution-workspaces.js.map +1 -1
  20. package/dist/services/heartbeat.d.ts +1 -0
  21. package/dist/services/heartbeat.d.ts.map +1 -1
  22. package/dist/services/heartbeat.js +79 -7
  23. package/dist/services/heartbeat.js.map +1 -1
  24. package/dist/services/paperclip-cloud-connector.d.ts +1 -1
  25. package/dist/services/paperclip-cloud-connector.d.ts.map +1 -1
  26. package/dist/services/paperclip-cloud-connector.js +55 -2
  27. package/dist/services/paperclip-cloud-connector.js.map +1 -1
  28. package/dist/services/paperclip-cloud-connector.test.js +88 -0
  29. package/dist/services/paperclip-cloud-connector.test.js.map +1 -1
  30. package/dist/services/recovery/service.d.ts +9 -0
  31. package/dist/services/recovery/service.d.ts.map +1 -1
  32. package/dist/services/recovery/service.js +132 -2
  33. package/dist/services/recovery/service.js.map +1 -1
  34. package/dist/services/run-identity.d.ts.map +1 -1
  35. package/dist/services/run-identity.js +12 -6
  36. package/dist/services/run-identity.js.map +1 -1
  37. package/dist/services/work-products.d.ts.map +1 -1
  38. package/dist/services/work-products.js +18 -1
  39. package/dist/services/work-products.js.map +1 -1
  40. package/package.json +21 -21
  41. package/ui-dist/assets/{Agents.production-BeDi727Q.js → Agents.production-DXVQbH40.js} +2 -2
  42. package/ui-dist/assets/{CompanyActivity.production-Qt-mLMpq.js → CompanyActivity.production-CinmmGVv.js} +1 -1
  43. package/ui-dist/assets/{CompanyExport-Dq2gmciJ.js → CompanyExport-DaS-YmqD.js} +1 -1
  44. package/ui-dist/assets/{CompanySkills.production-C4smxeMX.js → CompanySkills.production-DayJEg3Z.js} +1 -1
  45. package/ui-dist/assets/{Costs.production-CDsWvATt.js → Costs.production-qBNyNNRY.js} +1 -1
  46. package/ui-dist/assets/{MarkdownBody-DJQ35hak.js → MarkdownBody-NJwkQWmo.js} +2 -2
  47. package/ui-dist/assets/{OrgChart.production-uQij-DWC.js → OrgChart.production-7-WQ0htv.js} +1 -1
  48. package/ui-dist/assets/{RoutineDetail.production-DmubEXM7.js → RoutineDetail.production-CEF8wtwL.js} +1 -1
  49. package/ui-dist/assets/{RoutineRunVariablesDialog-Bt4KAWCh.js → RoutineRunVariablesDialog-B1KRZJIl.js} +2 -2
  50. package/ui-dist/assets/{Routines.production-_siggo5J.js → Routines.production-C15V_czC.js} +1 -1
  51. package/ui-dist/assets/StatusIcon-DgMlA1TU.js +1 -0
  52. package/ui-dist/assets/{definition-DroCAncf.js → definition-C_4HgU9U.js} +1 -1
  53. package/ui-dist/assets/{index-BCClSQew.js → index-DMN58MRe.js} +163 -160
  54. package/ui-dist/assets/{index-J-4PQOv1.css → index-Dkjt7SQK.css} +1 -1
  55. package/ui-dist/index.html +5 -5
  56. package/ui-dist/sw.js +1 -1
  57. package/ui-dist/assets/StatusIcon-BuUYMqqU.js +0 -1
@@ -1,4 +1,4 @@
1
- var ze=Object.defineProperty;var d=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{i as we}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as De,Ht as _e,Jn as te,Lr as Ue,S as ne,U as We,X as qe,Y as G,at as Ke,nr as X,tr as pe}from"./createLucideIcon-r3v6fbGz.js";import{it as Ye,o as Ze,p as Ge}from"./router-Bb8nJWyv.js";import{Q as Xe}from"./mention-chips-DXumPrOR.js";import{l as He,p as z}from"./zap-P-cXfK28.js";import{t as Je}from"./agents-BlSzFh-1.js";import{g as Qe}from"./StatusIcon-BuUYMqqU.js";import{r as Ve,t as D}from"./EmptyState-DPcc0zYh.js";import{t as H}from"./button-CAPbz11u.js";import{t as fe}from"./MarkdownBody-DJQ35hak.js";import{t as et}from"./loader-circle-BD9wx-lw.js";import{t as me}from"./rotate-ccw-CRAQ3Xng.js";import{t as tt}from"./PageSkeleton-DHjTwRT3.js";import{Ct as st,Pn as nt,St as rt,Ut as ot,a as at,bt as he,fn as it,i as ct,ln as lt,n as dt,r as ut,t as je,tn as pt,vt as ft,xt as mt,yt as ht}from"./index-BCClSQew.js";var h=we(Ue(),1),xt=["agents","projects","skills","routines","tasks","attachments"],gt={agents:"Agents",projects:"Projects",skills:"Skills",routines:"Routines",tasks:"Tasks",attachments:"Attachments"};function bt(){return{agents:!0,projects:!0,skills:!0,routines:!0,tasks:!0,attachments:!0}}d(bt,"buildDefaultExportCategorySelection");function ye(e){return e.tasks||e.routines}d(ye,"isAttachmentsCategoryEnabled");function ve(e){const r=new Set;for(const a of e){if(!a.recurring)continue;const n=a.path.trim();if(!n)continue;r.add(n);const o=n.lastIndexOf("/");o>=0&&r.add(`${n.slice(0,o+1)}`)}return r}d(ve,"buildRecurringTaskPrefixes");function wt(e,r){for(const a of r)if(e===a||e.startsWith(a))return!0;return!1}d(wt,"isRecurringTaskFile");function jt(e){const r=new Set,a=new Set;for(const n of e)for(const o of n.attachments??[]){const c=o.sha256.trim().toLowerCase();c&&(n.recurring?r:a).add(c)}return{recurring:r,oneOff:a}}d(jt,"buildAttachmentShaOwnership");var yt=new Set(["agents","projects","skills","routines","tasks"]);function vt(e){const r=new Map;for(const a of e){const n=a.sha256.trim().toLowerCase();if(!n)continue;const o=r.get(n)??new Set,c=a.ownedBy&&a.ownedBy.length>0?a.ownedBy:["always"];for(const p of c)o.add(p);r.set(n,o)}return r}d(vt,"buildEmbeddedAssetShaOwnership");function kt(e,r){for(const a of e)if(!yt.has(a)||r[a])return!0;return!1}d(kt,"isEmbeddedAssetBlobIncluded");function ke(e,r){return e.startsWith("agents/")?"agents":e.startsWith("projects/")?"projects":e.startsWith("skills/")?"skills":e.startsWith("tasks/")?wt(e,r)?"routines":"tasks":e.startsWith("blobs/")?"attachments":null}d(ke,"categorizeExportFile");function St(e,r){const a=ve(r),n={agents:0,projects:0,skills:0,routines:0,tasks:0,attachments:0};for(const o of e){const c=ke(o,a);c&&(n[c]+=1)}return n}d(St,"countExportFilesByCategory");function Ct(e){const{filePaths:r,issues:a,categories:n}=e,o=ve(a),c=jt(a),p=vt(e.embeddedAssets??[]),f=n.attachments&&ye(n),x=new Set;for(const l of r){const b=ke(l,o);if(b===null){x.add(l);continue}if(b==="attachments"){const i=l.slice(6).trim().toLowerCase(),g=p.get(i);if(g&&kt(g,n)){x.add(l);continue}if(!f)continue;const j=c.recurring.has(i),y=c.oneOff.has(i);!j&&!y?g||x.add(l):(y&&n.tasks||j&&n.routines)&&x.add(l);continue}n[b]&&x.add(l)}return x}d(Ct,"buildExportCheckedFiles");function Se(e,r){if(!r.has(e))return r.add(e),e;let a=2;for(;;){const n=`${e}-${a}`;if(!r.has(n))return r.add(n),n;a+=1}}d(Se,"uniqueSlug");function Et(e){const r=new Set,a=new Map,n=[...e].sort((o,c)=>o.name.localeCompare(c.name));for(const o of n){const c=_e(o.name)??"agent";a.set(o.id,Se(c,r))}return a}d(Et,"buildPortableAgentSlugMap");function Nt(e){const r=new Set,a=new Map,n=[...e].sort((o,c)=>o.name.localeCompare(c.name));for(const o of n){const c=Ke(o.name,o.name);a.set(o.id,Se(c,r))}return a}d(Nt,"buildPortableProjectSlugMap");function At(e){const r=Et(e.agents),a=Nt(e.projects),n={agents:e.orderedAgents.map(o=>r.get(o.id)).filter(o=>!!o),projects:e.orderedProjects.map(o=>a.get(o.id)).filter(o=>!!o)};return n.agents.length>0||n.projects.length>0?n:void 0}d(At,"buildPortableSidebarOrder");var t=we(De(),1);function Ce(e){const r=new Set,a=new Set,n=new Set;for(const o of e){const c=o.match(/^agents\/([^/]+)\//);c&&r.add(c[1]);const p=o.match(/^projects\/([^/]+)\//);p&&a.add(p[1]);const f=o.match(/^tasks\/([^/]+)\//);f&&n.add(f[1])}return{agents:r,projects:a,tasks:n,routines:new Set(n)}}d(Ce,"checkedSlugs");function Pt(e,r){const a=Ce(r),n=e.split(`
1
+ var ze=Object.defineProperty;var d=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{i as we}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as De,Ht as _e,Jn as te,Lr as Ue,S as ne,U as We,X as qe,Y as G,at as Ke,nr as X,tr as pe}from"./createLucideIcon-r3v6fbGz.js";import{it as Ye,o as Ze,p as Ge}from"./router-Bb8nJWyv.js";import{Q as Xe}from"./mention-chips-DXumPrOR.js";import{l as He,p as z}from"./zap-P-cXfK28.js";import{t as Je}from"./agents-BlSzFh-1.js";import{g as Qe}from"./StatusIcon-DgMlA1TU.js";import{r as Ve,t as D}from"./EmptyState-DPcc0zYh.js";import{t as H}from"./button-CAPbz11u.js";import{t as fe}from"./MarkdownBody-NJwkQWmo.js";import{t as et}from"./loader-circle-BD9wx-lw.js";import{t as me}from"./rotate-ccw-CRAQ3Xng.js";import{t as tt}from"./PageSkeleton-DHjTwRT3.js";import{Ct as st,Pn as nt,St as rt,Ut as ot,a as at,bt as he,fn as it,i as ct,ln as lt,n as dt,r as ut,t as je,tn as pt,vt as ft,xt as mt,yt as ht}from"./index-DMN58MRe.js";var h=we(Ue(),1),xt=["agents","projects","skills","routines","tasks","attachments"],gt={agents:"Agents",projects:"Projects",skills:"Skills",routines:"Routines",tasks:"Tasks",attachments:"Attachments"};function bt(){return{agents:!0,projects:!0,skills:!0,routines:!0,tasks:!0,attachments:!0}}d(bt,"buildDefaultExportCategorySelection");function ye(e){return e.tasks||e.routines}d(ye,"isAttachmentsCategoryEnabled");function ve(e){const r=new Set;for(const a of e){if(!a.recurring)continue;const n=a.path.trim();if(!n)continue;r.add(n);const o=n.lastIndexOf("/");o>=0&&r.add(`${n.slice(0,o+1)}`)}return r}d(ve,"buildRecurringTaskPrefixes");function wt(e,r){for(const a of r)if(e===a||e.startsWith(a))return!0;return!1}d(wt,"isRecurringTaskFile");function jt(e){const r=new Set,a=new Set;for(const n of e)for(const o of n.attachments??[]){const c=o.sha256.trim().toLowerCase();c&&(n.recurring?r:a).add(c)}return{recurring:r,oneOff:a}}d(jt,"buildAttachmentShaOwnership");var yt=new Set(["agents","projects","skills","routines","tasks"]);function vt(e){const r=new Map;for(const a of e){const n=a.sha256.trim().toLowerCase();if(!n)continue;const o=r.get(n)??new Set,c=a.ownedBy&&a.ownedBy.length>0?a.ownedBy:["always"];for(const p of c)o.add(p);r.set(n,o)}return r}d(vt,"buildEmbeddedAssetShaOwnership");function kt(e,r){for(const a of e)if(!yt.has(a)||r[a])return!0;return!1}d(kt,"isEmbeddedAssetBlobIncluded");function ke(e,r){return e.startsWith("agents/")?"agents":e.startsWith("projects/")?"projects":e.startsWith("skills/")?"skills":e.startsWith("tasks/")?wt(e,r)?"routines":"tasks":e.startsWith("blobs/")?"attachments":null}d(ke,"categorizeExportFile");function St(e,r){const a=ve(r),n={agents:0,projects:0,skills:0,routines:0,tasks:0,attachments:0};for(const o of e){const c=ke(o,a);c&&(n[c]+=1)}return n}d(St,"countExportFilesByCategory");function Ct(e){const{filePaths:r,issues:a,categories:n}=e,o=ve(a),c=jt(a),p=vt(e.embeddedAssets??[]),f=n.attachments&&ye(n),x=new Set;for(const l of r){const b=ke(l,o);if(b===null){x.add(l);continue}if(b==="attachments"){const i=l.slice(6).trim().toLowerCase(),g=p.get(i);if(g&&kt(g,n)){x.add(l);continue}if(!f)continue;const j=c.recurring.has(i),y=c.oneOff.has(i);!j&&!y?g||x.add(l):(y&&n.tasks||j&&n.routines)&&x.add(l);continue}n[b]&&x.add(l)}return x}d(Ct,"buildExportCheckedFiles");function Se(e,r){if(!r.has(e))return r.add(e),e;let a=2;for(;;){const n=`${e}-${a}`;if(!r.has(n))return r.add(n),n;a+=1}}d(Se,"uniqueSlug");function Et(e){const r=new Set,a=new Map,n=[...e].sort((o,c)=>o.name.localeCompare(c.name));for(const o of n){const c=_e(o.name)??"agent";a.set(o.id,Se(c,r))}return a}d(Et,"buildPortableAgentSlugMap");function Nt(e){const r=new Set,a=new Map,n=[...e].sort((o,c)=>o.name.localeCompare(c.name));for(const o of n){const c=Ke(o.name,o.name);a.set(o.id,Se(c,r))}return a}d(Nt,"buildPortableProjectSlugMap");function At(e){const r=Et(e.agents),a=Nt(e.projects),n={agents:e.orderedAgents.map(o=>r.get(o.id)).filter(o=>!!o),projects:e.orderedProjects.map(o=>a.get(o.id)).filter(o=>!!o)};return n.agents.length>0||n.projects.length>0?n:void 0}d(At,"buildPortableSidebarOrder");var t=we(De(),1);function Ce(e){const r=new Set,a=new Set,n=new Set;for(const o of e){const c=o.match(/^agents\/([^/]+)\//);c&&r.add(c[1]);const p=o.match(/^projects\/([^/]+)\//);p&&a.add(p[1]);const f=o.match(/^tasks\/([^/]+)\//);f&&n.add(f[1])}return{agents:r,projects:a,tasks:n,routines:new Set(n)}}d(Ce,"checkedSlugs");function Pt(e,r){const a=Ce(r),n=e.split(`
2
2
  `),o=[],c=new Set(["agents","projects","tasks","routines"]),p=new Set(["agents","projects"]);let f=null,x=null,l=!0,b=null,i=null,g=[],j=null,y=[];function T(){i!==null&&g.length>0&&(y.push(i),y.push(...g)),i=null,g=[]}d(T,"flushSidebarSection");function N(){T(),j!==null&&y.length>0&&(o.push(j),o.push(...y)),j=null,y=[]}d(N,"flushSection");for(const w of n){const U=w.match(/^([a-zA-Z_][\w-]*):\s*(.*)$/);if(U&&!w.startsWith(" ")){N(),x=null,l=!0;const E=U[0].split(":")[0];if(c.has(E)){f=E,j=w;continue}else if(E==="sidebar"){f=E,b=null,j=w;continue}else{f=null,o.push(w);continue}}if(f==="sidebar"){const E=w.match(/^ ([\w-]+):\s*$/);if(E&&!w.startsWith(" ")){T();const A=E[1];b=A&&p.has(A)?A:null,i=b?w:null;continue}const L=w.match(/^ - ["']?([^"'\n]+)["']?\s*$/);if(L&&b){const A=L[1],W=a[b];A&&W.has(A)&&g.push(w);continue}if(b){g.push(w);continue}}if(f&&c.has(f)){const E=w.match(/^ ([\w][\w-]*):\s*(.*)$/);if(E&&!w.startsWith(" ")){const L=E[1];x=L,l=a[f].has(L),l&&y.push(w);continue}if(x!==null){l&&y.push(w);continue}y.push(w);continue}o.push(w)}N();let C=o.join(`
3
3
  `);const _=C.match(/^\s{2}logoPath:\s*["']?([^"'\n]+)["']?\s*$/m);return _&&!r.has(_[1])&&(C=C.replace(/^\s{2}logoPath:\s*["']?([^"'\n]+)["']?\s*\n?/m,"")),C}d(Pt,"filterPaperclipYaml");function Ee(e,r){if(!r)return e;const a=r.toLowerCase();return e.map(n=>{if(n.kind==="file")return n.name.toLowerCase().includes(a)||n.path.toLowerCase().includes(a)?n:null;const o=Ee(n.children,r);return o.length>0?{...n,children:o}:null}).filter(n=>n!==null)}d(Ee,"filterTree");function Rt(e,r){const a=new Set,n=r.toLowerCase();function o(c,p){if(c.kind==="file"){if(c.name.toLowerCase().includes(n)||c.path.toLowerCase().includes(n))for(const f of p)a.add(f)}else for(const f of c.children)o(f,[...p,c.path])}d(o,"walk");for(const c of e)o(c,[]);return a}d(Rt,"collectMatchedParentDirs");var xe=10;function Tt(e,r,a,n){let o=0,c=0;return{nodes:e.map(p=>{if(p.kind==="dir"&&p.name==="tasks"){o=p.children.length;const f=[],x=[],l=a.toLowerCase();for(const g of p.children){const j=mt([g],"file"),y=n!==null&&j.has(n),T=a&&(g.name.toLowerCase().includes(l)||g.path.toLowerCase().includes(l)||[...j].some(N=>N.toLowerCase().includes(l)));y||T?f.push(g):x.push(g)}const b=Math.max(0,r-f.length),i=[...f,...x.slice(0,b)];return c=i.length,{...p,children:i}}return p}),totalTaskChildren:o,visibleTaskChildren:c}}d(Tt,"paginateTaskNodes");function Ne(e,r,a){const n={};for(const o of Object.keys(e))r.has(o)&&(n[o]=a[o]??e[o]);return n}d(Ne,"filterExportForDownload");function Lt(e,r,a){const n=Ne(e.files,r,a),o=ct(n,e.rootPath),c=new ArrayBuffer(o.byteLength);new Uint8Array(c).set(o);const p=new Blob([c],{type:"application/zip"}),f=URL.createObjectURL(p),x=document.createElement("a");x.href=f,x.download=`${e.rootPath}.zip`,document.body.appendChild(x),x.click(),x.remove(),window.setTimeout(()=>URL.revokeObjectURL(f),1e3)}d(Lt,"downloadZip");function Ot({data:e,onSkillClick:r}){return(0,t.jsx)("div",{className:"rounded-md border border-border bg-accent/20 px-4 py-3 mb-4",children:(0,t.jsx)("dl",{className:"grid grid-cols-(--gtc-5) gap-x-4 gap-y-1.5 text-sm",children:Object.entries(e).map(([a,n])=>(0,t.jsxs)("div",{className:"contents",children:[(0,t.jsx)("dt",{className:"text-muted-foreground whitespace-nowrap py-0.5",children:ft[a]??a}),(0,t.jsx)("dd",{className:"py-0.5",children:Array.isArray(n)?(0,t.jsx)("div",{className:"flex flex-wrap gap-1.5",children:n.map(o=>(0,t.jsx)("button",{type:"button",className:ne("inline-flex items-center rounded-md border border-border bg-background px-2 py-0.5 text-xs",a==="skills"&&r&&"cursor-pointer hover:bg-accent/50 hover:border-foreground/30 transition-colors"),onClick:d(()=>a==="skills"&&r?.(o),"onClick"),children:o},o))}):(0,t.jsx)("span",{children:n})})]},a))})})}d(Ot,"FrontmatterCard");var Mt={ceo:"CEO",cto:"CTO",cmo:"CMO",cfo:"CFO",coo:"COO",vp:"VP",manager:"Manager",engineer:"Engineer",agent:"Agent"};function Ft(e,r,a,n){const o=Ce(r),c=e.agents.filter(i=>o.agents.has(i.slug)),p=e.projects.filter(i=>o.projects.has(i.slug)),f=e.issues.filter(i=>o.tasks.has(i.slug)),x=e.skills.filter(i=>[...r].some(g=>g.startsWith(`skills/${i.key}/`)||g.startsWith("skills/")&&g.includes(`/${i.slug}/`))),l=[];l.push(`# ${a}`),l.push(""),n&&(l.push(`> ${n}`),l.push("")),c.length>0&&(l.push("![Org Chart](images/org-chart.png)"),l.push("")),l.push("## What's Inside"),l.push(""),l.push("This is an [Agent Company](https://paperclip.ing) package."),l.push("");const b=[];if(c.length>0&&b.push(["Agents",c.length]),p.length>0&&b.push(["Projects",p.length]),x.length>0&&b.push(["Skills",x.length]),f.length>0&&b.push(["Tasks",f.length]),b.length>0){l.push("| Content | Count |"),l.push("|---------|-------|");for(const[i,g]of b)l.push(`| ${i} | ${g} |`);l.push("")}if(c.length>0){l.push("### Agents"),l.push(""),l.push("| Agent | Role | Reports To |"),l.push("|-------|------|------------|");for(const i of c){const g=Mt[i.role]??i.role,j=i.reportsToSlug??"—";l.push(`| ${i.name} | ${g} | ${j} |`)}l.push("")}if(p.length>0){l.push("### Projects"),l.push("");for(const i of p){const g=i.description?` — ${i.description}`:"";l.push(`- **${i.name}**${g}`)}l.push("")}return l.push("## Getting Started"),l.push(""),l.push("```bash"),l.push("npx @tickernelz/paperclip-pro company import this-github-url-or-folder"),l.push("```"),l.push(""),l.push("See [Paperclip](https://paperclip.ing) for more information."),l.push(""),l.push("---"),l.push(`Exported from [Paperclip](https://paperclip.ing) on ${new Date().toISOString().split("T")[0]}`),l.push(""),l.join(`
4
4
  `)}d(Ft,"generateReadmeFromSelection");function It(e){const{src:r,selectedFile:a,allFiles:n,orgChartPreviewUrl:o}=e;if(/^(?:https?:|data:)/i.test(r))return null;if(r.replace(/^\.\//,"")==="images/org-chart.png"&&o)return o;const c=(a.includes("/")?a.slice(0,a.lastIndexOf("/")+1):"")+r,p=n[c]??n[r];return p?je(c in n?c:r,p):null}d(It,"resolveExportPreviewImageSrc");function $t({selectedFile:e,content:r,allFiles:a,orgChartPreviewUrl:n,onSkillClick:o}){if(!e||r===null)return(0,t.jsx)(D,{icon:z,message:"Select a file to preview its contents."});const c=dt(r),p=e.endsWith(".md")&&c!==null,f=p&&c?st(c):null,x=ut(e,r)?je(e,r):null,l=p?b=>It({src:b,selectedFile:e,allFiles:a,orgChartPreviewUrl:n}):void 0;return(0,t.jsxs)("div",{className:"min-w-0",children:[(0,t.jsx)("div",{className:"border-b border-border px-5 py-3",children:(0,t.jsx)("div",{className:"truncate font-mono text-sm",children:e})}),(0,t.jsx)("div",{className:"min-h-(--sz-560px) px-5 py-5",children:f?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ot,{data:f.data,onSkillClick:o}),f.body.trim()&&(0,t.jsx)(fe,{resolveImageSrc:l,softBreaks:!1,linkIssueReferences:!1,children:f.body})]}):p?(0,t.jsx)(fe,{resolveImageSrc:l,softBreaks:!1,linkIssueReferences:!1,children:c??""}):x?(0,t.jsx)("div",{className:"flex min-h-(--sz-520px) items-center justify-center rounded-lg border border-border bg-accent/10 p-6",children:(0,t.jsx)("img",{src:x,alt:e,className:"max-h-(--sz-480px) max-w-full object-contain"})}):c!==null?(0,t.jsx)("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground",children:(0,t.jsx)("code",{children:c})}):(0,t.jsx)("div",{className:"rounded-lg border border-border bg-accent/10 px-4 py-3 text-sm text-muted-foreground",children:"Binary asset preview is not available for this file type."})})]})}d($t,"ExportPreviewPane");function ge(e){const r="/company/export/files/",a=Ge(e),n=a.indexOf(r);return n===-1?null:decodeURIComponent(a.slice(n+22))||null}d(ge,"filePathFromLocation");function be(e){const r=e.split("/").slice(0,-1),a=[];let n="";for(const o of r)n=n?`${n}/${o}`:o,a.push(n);return a}d(be,"expandAncestors");function Bt(e){return(e instanceof DOMException||e instanceof Error)&&e.name==="AbortError"}d(Bt,"isAbortError");function se(e){return e instanceof Error?e.message:"Failed to load export data."}d(se,"previewErrorMessage");function es(){const{selectedCompanyId:e,selectedCompany:r}=We(),{setBreadcrumbs:a}=Ve(),{pushToast:n}=it(),o=Ze(),c=Ye(),p=(0,h.useRef)(ge(c.pathname)),{data:f}=X({queryKey:G.auth.session,queryFn:d(()=>qe.getSession(),"queryFn")}),{data:x=[]}=X({queryKey:G.agents.list(e),queryFn:d(()=>Je.list(e),"queryFn"),enabled:!!e}),{data:l=[]}=X({queryKey:G.projects.list(e),queryFn:d(()=>Qe.list(e),"queryFn"),enabled:!!e}),{data:b}=X({queryKey:G.companies.exportFidelity(e),queryFn:d(()=>te.exportFidelity(e),"queryFn"),enabled:!!e}),[i,g]=(0,h.useState)(null),[j,y]=(0,h.useState)(null),[T,N]=(0,h.useState)(new Set),[C,_]=(0,h.useState)(()=>({...bt(),tasks:!1,routines:!1,attachments:!1})),[w,U]=(0,h.useState)(""),[E,L]=(0,h.useState)(xe),[A,W]=(0,h.useState)(!1),q=(0,h.useRef)(null),I=(0,h.useRef)(null),M=(0,h.useRef)(0),re=(0,h.useRef)(null),oe=f?.user?.id??f?.session?.userId??null,J=(0,h.useMemo)(()=>x.filter(s=>s.status!=="terminated"),[x]),Q=(0,h.useMemo)(()=>l,[l]),{orderedAgents:ae}=lt({agents:J,companyId:e,userId:oe}),{orderedProjects:ie}=pt({projects:Q,companyId:e,userId:oe}),ce=(0,h.useMemo)(()=>At({agents:J,orderedAgents:ae,projects:Q,orderedProjects:ie}),[ae,ie,J,Q]),V=C.tasks||C.routines,ee=(0,h.useCallback)((s,u=!1)=>{y(s),s?o(`/company/export/files/${encodeURI(s)}`,{replace:u}):o("/company/export",{replace:u})},[o]);(0,h.useEffect)(()=>{if(!i)return;const s=ge(c.pathname);s&&s in i.files&&s!==j?(y(s),N(u=>{const m=new Set(u);for(const v of be(s))m.add(v);return m})):!s&&j&&y(null)},[c.pathname,i]),(0,h.useEffect)(()=>{a([{label:r?.name??"Organization",href:"/dashboard"},{label:"Settings",href:"/company/settings"},{label:"Export"}])},[r?.name,a]);const P=pe({mutationFn:d(({includeIssues:s,includeSkills:u,signal:m})=>te.exportPreview(e,{include:{company:!0,agents:!0,projects:!0,issues:s,skills:u},sidebarOrder:ce},{signal:m}),"mutationFn"),onSuccess:d((s,u)=>{if(u.requestId!==M.current)return;g(s);const m=he(s.files),v=new Set;for(const k of m)k.kind==="dir"&&k.name!=="tasks"&&v.add(k.path);const S=p.current;if(S&&S in s.files){y(S);const k=be(S);N(new Set([...v,...k]))}else{const k="README.md"in s.files?"README.md":Object.keys(s.files)[0];k&&ee(k,!0),N(v)}},"onSuccess"),onError:d((s,u)=>{u.requestId!==M.current||Bt(s)||n({tone:"error",title:"Export failed",body:se(s)})},"onError")});function F(){if(!e)return;I.current?.abort();const s=new AbortController,u=M.current+1;M.current=u,I.current=s,W(!1),P.mutate({includeIssues:V,includeSkills:C.skills,requestId:u,signal:s.signal})}d(F,"startPreviewRequest");const K=pe({mutationFn:d(()=>te.exportBundle(e,{include:{company:!0,agents:!0,projects:!0,issues:V,skills:C.skills},selectedFiles:Array.from(R).sort(),sidebarOrder:ce}),"mutationFn"),onSuccess:d(s=>{const u=new Set(Object.keys(s.files));Lt(s,u,s.files),n({tone:"success",title:"Export downloaded",body:`${u.size} file${u.size===1?"":"s"} exported as ${s.rootPath}.zip`})},"onSuccess"),onError:d(s=>{n({tone:"error",title:"Export failed",body:s instanceof Error?s.message:"Failed to build export package."})},"onError")});(0,h.useEffect)(()=>{e&&(re.current!==e&&(re.current=e,g(null),y(null)),F())},[e,V,C.skills]),(0,h.useEffect)(()=>()=>{M.current+=1,I.current?.abort()},[]);const O=(0,h.useMemo)(()=>i?he(i.files):[],[i]),R=(0,h.useMemo)(()=>i?Ct({filePaths:Object.keys(i.files),issues:i.manifest.issues,categories:C,embeddedAssets:i.manifest.embeddedAssets??[]}):new Set,[i,C]),Ae=(0,h.useMemo)(()=>i?St(Object.keys(i.files),i.manifest.issues):null,[i]),{displayTree:Pe,totalTaskChildren:le,visibleTaskChildren:de}=(0,h.useMemo)(()=>{let s=O;w&&(s=Ee(s,w));const u=Tt(s,E,w,j);return{displayTree:u.nodes,totalTaskChildren:u.totalTaskChildren,visibleTaskChildren:u.visibleTaskChildren}},[O,w,E,j]),Re=(0,h.useMemo)(()=>{const s={};function u(m){if(m.kind==="file"){const S=R.has(m.path);return S||(s[m.path]="muted"),S}let v=!1;for(const S of m.children)u(S)&&(v=!0);return v||(s[m.path]="muted"),v}d(u,"walk");for(const m of O)u(m);return s},[O,R]),Y=(0,h.useMemo)(()=>{if(!i)return{};const s={...i.files},u=i.paperclipExtensionPath;if(u&&typeof i.files[u]=="string"&&(s[u]=Pt(i.files[u],R)),typeof i.files["README.md"]=="string"){const m=i.manifest.company?.name??r?.name??"Company",v=i.manifest.company?.description??null;s["README.md"]=Ft(i.manifest,R,m,v)}return s},[i,R,r?.name]),Te=(0,h.useMemo)(()=>i?at(Ne(i.files,R,Y),i.rootPath):0,[i,R,Y]),ue=(0,h.useMemo)(()=>rt(O),[O]),$=R.size,B=(0,h.useMemo)(()=>i?i.warnings.filter(s=>!/terminated agent/i.test(s)):[],[i]);function Le(s){N(u=>{const m=new Set(u);return m.has(s)?m.delete(s):m.add(s),m})}d(Le,"handleToggleDir");function Oe(s){_(u=>({...u,[s]:!u[s]}))}d(Oe,"handleToggleCategory");function Me(s){const u=w.length>0,m=s.length>0;if(m&&!u&&(q.current=new Set(T)),U(s),m){const v=Rt(O,s);N(S=>{const k=new Set(S);for(const Z of v)k.add(Z);return k})}else u&&q.current&&(N(q.current),q.current=null)}d(Me,"handleSearchChange");function Fe(s){if(!i)return;const u=i.manifest.skills.find(m=>m.key===s||m.slug===s)?.path??`skills/${s}/SKILL.md`;u in i.files&&(ee(u),N(m=>{const v=new Set(m);v.add("skills");const S=u.split("/").slice(0,-1);let k="";for(const Z of S)k=k?`${k}/${Z}`:Z,v.add(k);return v}))}d(Fe,"handleSkillClick");function Ie(){!i||R.size===0||K.isPending||K.mutate()}d(Ie,"handleDownload");function $e(){M.current+=1,I.current?.abort(),I.current=null,P.reset(),W(!0)}if(d($e,"handleCancelPreview"),!e)return(0,t.jsx)(D,{icon:z,message:"Select an organization to export."});if(P.isPending&&!i)return(0,t.jsx)(tt,{variant:"detail"});if(A&&!i)return(0,t.jsx)(D,{icon:z,title:"Export preview cancelled",message:"The preview request was cancelled. Your export settings are unchanged.",action:"Retry preview",onAction:F,hideActionIcon:!0});if(P.isError&&!i)return(0,t.jsx)(D,{icon:z,title:"Export preview failed",message:se(P.error),description:"Retry the preview. You do not need to reload this page.",action:"Retry preview",onAction:F,hideActionIcon:!0});if(!i)return(0,t.jsx)(D,{icon:z,title:"Export preview unavailable",message:"No export preview is loaded.",action:"Load preview",onAction:F,hideActionIcon:!0});const Be=j?Y[j]??null:null;return(0,t.jsxs)("div",{className:"max-w-6xl",children:[(0,t.jsx)("div",{className:"sticky top-0 z-10 border-b border-border bg-background px-5 py-3",children:(0,t.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[(0,t.jsxs)("span",{className:"font-medium",children:[r?.name??"Organization"," export"]}),(0,t.jsxs)("span",{className:"text-muted-foreground",children:["Exporting ",$.toLocaleString()," of ",ue.toLocaleString()," file",ue===1?"":"s",$>0&&` (~${ot(Te)})`]}),B.length>0&&(0,t.jsxs)("span",{className:"text-amber-500",children:[B.length," warning",B.length===1?"":"s"]})]}),(0,t.jsxs)(H,{size:"sm",onClick:Ie,disabled:$===0||K.isPending||P.isPending||P.isError||A,children:[(0,t.jsx)(nt,{className:"mr-1.5 h-3.5 w-3.5"}),K.isPending?"Building export...":`Export ${$.toLocaleString()} file${$===1?"":"s"}`]})]})}),B.length>0&&(0,t.jsx)("div",{className:"mx-5 mt-3 rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:B.map(s=>(0,t.jsx)("div",{className:"text-xs text-amber-500",children:s},s))}),b&&b.warnings.length>0&&(0,t.jsxs)("div",{className:"mx-5 mt-3 rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:[(0,t.jsx)("h3",{className:"mb-1.5 text-xs font-medium",children:"Not included in this export"}),b.warnings.map(s=>(0,t.jsx)("div",{className:ne("text-xs",s.severity==="blocker"?"font-medium text-destructive":"text-amber-500"),children:s.message},s.code))]}),(0,t.jsxs)("div",{className:"grid gap-4 xl:h-(--sz-calc-30) xl:grid-cols-(--gtc-25) xl:gap-0",children:[(0,t.jsxs)("aside",{className:"flex max-h-(--sz-24rem) flex-col overflow-hidden border-b border-border xl:max-h-none xl:border-b-0 xl:border-r",children:[(0,t.jsx)("div",{className:"border-b border-border px-4 py-3 shrink-0",children:(0,t.jsx)("h2",{className:"text-base font-semibold",children:"Package files"})}),(0,t.jsxs)("div",{className:"border-b border-border px-4 py-3 shrink-0",children:[(0,t.jsx)("h3",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"What to include"}),(0,t.jsx)("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5",role:"group","aria-label":"What to include",children:xt.map(s=>{const u=s==="attachments"&&!ye(C),m=C[s]&&!u,v=Ae?.[s]??0,S=i.manifest.includes.issues||s!=="tasks"&&s!=="routines"&&s!=="attachments";return(0,t.jsxs)("label",{className:ne("flex items-center gap-2 text-sm",u?"cursor-not-allowed opacity-50":"cursor-pointer"),title:u?"Attachments travel with tasks and routines; re-enable one of them to include attachments.":void 0,children:[(0,t.jsx)("input",{type:"checkbox",checked:m,disabled:u,onChange:d(()=>Oe(s),"onChange"),className:"accent-foreground","data-export-category":s}),(0,t.jsx)("span",{className:"min-w-0 truncate",children:gt[s]}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:S?v.toLocaleString():"—"})]},s)})}),(0,t.jsx)("p",{className:"mt-2 text-xs text-muted-foreground",children:"Task and routine history is opt-in because it can be large."})]}),(0,t.jsx)("div",{className:"border-b border-border px-3 py-2 shrink-0",children:(0,t.jsxs)("div",{className:"flex items-center gap-2 rounded-md border border-border px-2 py-1",children:[(0,t.jsx)(He,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,t.jsx)("input",{type:"text",value:w,onChange:d(s=>Me(s.target.value),"onChange"),placeholder:"Search files...",className:"w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground","data-page-search-target":"true"})]})}),(0,t.jsxs)("div",{className:"flex-1 overflow-y-auto",children:[(0,t.jsx)(ht,{nodes:Pe,selectedFile:j,expandedDirs:T,onToggleDir:Le,onSelectFile:ee,fileTones:Re,showCheckboxes:!1,wrapLabels:!1}),le>de&&!w&&(0,t.jsx)("div",{className:"px-4 py-2",children:(0,t.jsxs)("button",{type:"button",onClick:d(()=>L(s=>s+xe),"onClick"),className:"w-full rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-accent/30 hover:text-foreground transition-colors",children:["Show more tasks (",de," of ",le,")"]})})]})]}),(0,t.jsxs)("div",{className:"relative min-w-0 overflow-y-auto xl:pl-6",children:[(0,t.jsx)($t,{selectedFile:j,content:Be,allFiles:Y,orgChartPreviewUrl:`/api/companies/${encodeURIComponent(e)}/org.svg`,onSkillClick:Fe}),P.isPending?(0,t.jsx)("div",{className:"absolute inset-0 z-10 flex min-h-(--sz-520px) items-center justify-center bg-background/90 px-6 text-center",role:"status","aria-live":"polite","aria-busy":"true","data-export-preview-state":"loading",children:(0,t.jsxs)("div",{className:"flex max-w-md flex-col items-center gap-3",children:[(0,t.jsx)(et,{className:"h-6 w-6 animate-spin text-muted-foreground"}),(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:"Updating export preview…"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"Large task histories can take a minute. You can untick Tasks or cancel this update."})]}),(0,t.jsxs)(H,{type:"button",variant:"outline",size:"sm",onClick:$e,children:[(0,t.jsx)(Xe,{}),"Cancel update"]})]})}):A?(0,t.jsx)("div",{className:"absolute inset-0 z-10 flex min-h-(--sz-520px) items-center justify-center bg-background/90 px-6 text-center","data-export-preview-state":"cancelled",children:(0,t.jsxs)("div",{className:"flex max-w-md flex-col items-center gap-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"text-sm font-medium",children:"Preview update cancelled"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:"The previous preview remains available. Retry when you are ready."})]}),(0,t.jsxs)(H,{type:"button",variant:"outline",size:"sm",onClick:F,children:[(0,t.jsx)(me,{}),"Retry preview"]})]})}):P.isError?(0,t.jsx)("div",{className:"absolute inset-0 z-10 flex min-h-(--sz-520px) items-center justify-center bg-background/90 px-6 text-center",role:"alert","data-export-preview-state":"error",children:(0,t.jsxs)("div",{className:"flex max-w-md flex-col items-center gap-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("p",{className:"text-sm font-medium text-destructive",children:"Export preview failed"}),(0,t.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:se(P.error)})]}),(0,t.jsxs)(H,{type:"button",variant:"outline",size:"sm",onClick:F,children:[(0,t.jsx)(me,{}),"Retry preview"]})]})}):null]})]})]})}d(es,"CompanyExport");export{es as CompanyExport};
@@ -1,4 +1,4 @@
1
- var gr=Object.defineProperty;var n=(t,l)=>gr(t,"name",{value:l,configurable:!0});import{i as vn}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as fr,Lr as br,Pr as jr,S as M,U as vr,Y as f,nr as xe,tr as Y,z as yr}from"./createLucideIcon-r3v6fbGz.js";import{ct as kr,o as Nr,st as wr,t as Je}from"./router-Bb8nJWyv.js";import{Q as Sr,tt as Cr}from"./mention-chips-DXumPrOR.js";import{N as pe,g as Fr,l as Ir,o as yn,x as Dr}from"./zap-P-cXfK28.js";import{c as _,f as Lr,t as Br}from"./MarkdownEditor-DfrwLv1M.js";import{b as Pr,v as Ws,y as kn}from"./sheet-CQJe5sfn.js";import{t as nn}from"./AgentAvatar-PT82VwmU.js";import{A as Er,C as Ar,O as Ls,S as Ds,a as fs,c as bs,f as qe,g as Bs,h as Re,k as Tr,n as jt,o as Ts,p as $e,r as js,s as vt,t as Kr,u as vs,v as Ps,x as xt,y as Es}from"./checkbox-757DLJRS.js";import{i as As,r as Nn,t as wn}from"./tabs-DWRZjksg.js";import{n as Ft,t as Hs}from"./agents-BlSzFh-1.js";import{m as Sn}from"./StatusIcon-BuUYMqqU.js";import{t as Mr}from"./use-adapter-capabilities-BiWYK4zJ.js";import{r as qr,t as Ze}from"./EmptyState-DPcc0zYh.js";import{t as Cn}from"./check-DDiXDm2i.js";import{t as ps}from"./chevron-down-F9aZv-V7.js";import{t as Fn}from"./chevron-right-B9JUOr38.js";import{n as Rr,t as ht}from"./save-DUnPDT6R.js";import{k as yt,t as k}from"./button-CAPbz11u.js";import{i as In,r as It}from"./clipboard-CYJ5Q78m.js";import{t as gs}from"./external-link-0lrOvZWO.js";import{t as kt,y as $r}from"./MarkdownBody-DJQ35hak.js";import{t as Dt}from"./file-text-C9vgFckt.js";import{t as Dn}from"./triangle-alert-CgJcxSQX.js";import{t as le}from"./badge-Cf7ihb3q.js";import{t as Me}from"./input-DpsS9it-.js";import"./AgentIdentity-MCshmbhZ.js";import{t as Le}from"./PageSkeleton-DHjTwRT3.js";import{An as zr,At as _r,Bn as rn,Bt as Ur,Dt as Lt,En as Or,Et as Vr,Ft as Ln,J as Qr,Kt as Hr,Ln as Gr,Mn as Bn,Mt as pt,Nn as Pn,Nt as Wr,Ot as Yr,Pn as Nt,Pt as En,Q as Xr,Sn as Zr,Tn as Jr,X as ea,Y as sa,Z as ta,Zt as An,_ as na,bn as Tn,c as ra,ct as aa,d as la,dt as an,et as ia,f as Ks,fn as oa,ft as Xe,g as da,gn as ca,h as ua,ht as he,it as ma,jn as ys,jt as Gs,kn as xa,kt as gt,l as ha,lt as pa,m as Kn,mn as ga,nt as fa,o as ba,ot as ja,p as ft,rt as va,s as ya,st as ka,tt as Na,u as wa,ut as Mn,vn as Sa,wn as wt,zn as St}from"./index-BCClSQew.js";var c=vn(br(),1),e=vn(fr(),1),ln=16,on=24,dn="min-h-9";function cn(t){return(0,e.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...t,children:(0,e.jsx)("path",{d:"M12 4 21 19H3z"})})}n(cn,"VercelMark");function qn(t){const l=t.replace(/\r\n/g,`
1
+ var gr=Object.defineProperty;var n=(t,l)=>gr(t,"name",{value:l,configurable:!0});import{i as vn}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as fr,Lr as br,Pr as jr,S as M,U as vr,Y as f,nr as xe,tr as Y,z as yr}from"./createLucideIcon-r3v6fbGz.js";import{ct as kr,o as Nr,st as wr,t as Je}from"./router-Bb8nJWyv.js";import{Q as Sr,tt as Cr}from"./mention-chips-DXumPrOR.js";import{N as pe,g as Fr,l as Ir,o as yn,x as Dr}from"./zap-P-cXfK28.js";import{c as _,f as Lr,t as Br}from"./MarkdownEditor-DfrwLv1M.js";import{b as Pr,v as Ws,y as kn}from"./sheet-CQJe5sfn.js";import{t as nn}from"./AgentAvatar-PT82VwmU.js";import{A as Er,C as Ar,O as Ls,S as Ds,a as fs,c as bs,f as qe,g as Bs,h as Re,k as Tr,n as jt,o as Ts,p as $e,r as js,s as vt,t as Kr,u as vs,v as Ps,x as xt,y as Es}from"./checkbox-757DLJRS.js";import{i as As,r as Nn,t as wn}from"./tabs-DWRZjksg.js";import{n as Ft,t as Hs}from"./agents-BlSzFh-1.js";import{m as Sn}from"./StatusIcon-DgMlA1TU.js";import{t as Mr}from"./use-adapter-capabilities-BiWYK4zJ.js";import{r as qr,t as Ze}from"./EmptyState-DPcc0zYh.js";import{t as Cn}from"./check-DDiXDm2i.js";import{t as ps}from"./chevron-down-F9aZv-V7.js";import{t as Fn}from"./chevron-right-B9JUOr38.js";import{n as Rr,t as ht}from"./save-DUnPDT6R.js";import{k as yt,t as k}from"./button-CAPbz11u.js";import{i as In,r as It}from"./clipboard-CYJ5Q78m.js";import{t as gs}from"./external-link-0lrOvZWO.js";import{b as $r,t as kt}from"./MarkdownBody-NJwkQWmo.js";import{t as Dt}from"./file-text-C9vgFckt.js";import{t as Dn}from"./triangle-alert-CgJcxSQX.js";import{t as le}from"./badge-Cf7ihb3q.js";import{t as Me}from"./input-DpsS9it-.js";import"./AgentIdentity-MCshmbhZ.js";import{t as Le}from"./PageSkeleton-DHjTwRT3.js";import{An as zr,At as _r,Bn as rn,Bt as Ur,Dt as Lt,En as Or,Et as Vr,Ft as Ln,J as Qr,Kt as Hr,Ln as Gr,Mn as Bn,Mt as pt,Nn as Pn,Nt as Wr,Ot as Yr,Pn as Nt,Pt as En,Q as Xr,Sn as Zr,Tn as Jr,X as ea,Y as sa,Z as ta,Zt as An,_ as na,bn as Tn,c as ra,ct as aa,d as la,dt as an,et as ia,f as Ks,fn as oa,ft as Xe,g as da,gn as ca,h as ua,ht as he,it as ma,jn as ys,jt as Gs,kn as xa,kt as gt,l as ha,lt as pa,m as Kn,mn as ga,nt as fa,o as ba,ot as ja,p as ft,rt as va,s as ya,st as ka,tt as Na,u as wa,ut as Mn,vn as Sa,wn as wt,zn as St}from"./index-DMN58MRe.js";var c=vn(br(),1),e=vn(fr(),1),ln=16,on=24,dn="min-h-9";function cn(t){return(0,e.jsx)("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...t,children:(0,e.jsx)("path",{d:"M12 4 21 19H3z"})})}n(cn,"VercelMark");function qn(t){const l=t.replace(/\r\n/g,`
2
2
  `);if(!l.startsWith(`---
3
3
  `))return l.trim();const a=l.indexOf(`
4
4
  ---
@@ -1 +1 @@
1
- var ot=Object.defineProperty;var o=(i,h)=>ot(i,"name",{value:h,configurable:!0});import{i as Re}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as dt,L as J,Lr as lt,M,Pr as ct,S as Ie,T as m,U as ut,Y as v,nr as S,tr as qe,x as mt}from"./createLucideIcon-r3v6fbGz.js";import{i as O,n as B,r as pt,t as te}from"./tabs-DWRZjksg.js";import{r as gt,t as xt}from"./EmptyState-DPcc0zYh.js";import{t as ht}from"./chevron-down-F9aZv-V7.js";import{t as bt}from"./chevron-right-B9JUOr38.js";import{t as vt}from"./button-CAPbz11u.js";import{t as yt}from"./AgentIdentity-MCshmbhZ.js";import{i as R,o as $,r as F,s as L,t as q}from"./card-dmVcp3AX.js";import{t as se}from"./PageSkeleton-DHjTwRT3.js";import{$t as De,C as jt,D as N,E as Ae,Fn as ne,Gt as ft,Hn as re,In as ie,S as Fe,T as Ee,Wn as Nt,_t as ae,b as Ct,gt as wt,v as Tt,w as kt,x as Ke,xn as oe,y as St}from"./index-BCClSQew.js";var l=Re(lt(),1),e=Re(dt(),1),Bt="__none__";function Mt(){const i=new Date,h=i.getDay(),y=h===0?-6:1-h,u=new Date(i.getFullYear(),i.getMonth(),i.getDate()+y,0,0,0,0),j=new Date(u.getFullYear(),u.getMonth(),u.getDate()+6,23,59,59,999);return{from:u.toISOString(),to:j.toISOString()}}o(Mt,"currentWeekRange");function Pt({provider:i,rows:h}){const y=h.reduce((j,b)=>j+b.inputTokens+b.cachedInputTokens+b.outputTokens,0),u=h.reduce((j,b)=>j+b.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:J(i)}),(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(y)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(u)})]})}o(Pt,"ProviderTabLabel");function It({biller:i,rows:h}){const y=h.reduce((j,b)=>j+b.inputTokens+b.cachedInputTokens+b.outputTokens,0),u=h.reduce((j,b)=>j+b.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:J(i)}),(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(y)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(u)})]})}o(It,"BillerTabLabel");function C({label:i,value:h,subtitle:y,icon:u}){return(0,e.jsx)(q,{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-muted-foreground",children:i}),(0,e.jsx)("div",{className:"mt-2 text-2xl font-semibold tabular-nums",children:h}),(0,e.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:y})]}),(0,e.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-border",children:(0,e.jsx)(u,{className:"h-4 w-4 text-muted-foreground"})})]})})}o(C,"MetricTile");function _e({debitCents:i,creditCents:h,netCents:y,estimatedDebitCents:u,eventCount:j}){return(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"Finance ledger"}),(0,e.jsx)(R,{children:"Account-level charges that do not map to a single inference request."})]}),(0,e.jsxs)(F,{className:"grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4",children:[(0,e.jsx)(C,{label:"Debits",value:m(i),subtitle:`${j} total event${j===1?"":"s"} in range`,icon:re}),(0,e.jsx)(C,{label:"Credits",value:m(h),subtitle:"Refunds, offsets, and credit returns",icon:Nt}),(0,e.jsx)(C,{label:"Net",value:m(y),subtitle:"Debit minus credit for the selected period",icon:oe}),(0,e.jsx)(C,{label:"Estimated",value:m(u),subtitle:"Estimated debits that are not yet invoice-authoritative",icon:ie})]})]})}o(_e,"FinanceSummaryCard");function Ot(){const{selectedCompanyId:i}=ut(),{setBreadcrumbs:h}=gt(),y=ct(),[u,j]=(0,l.useState)("overview"),[b,de]=(0,l.useState)("all"),[W,le]=(0,l.useState)("all"),{preset:E,setPreset:$e,customFrom:Le,setCustomFrom:We,customTo:ze,setCustomTo:Oe,from:g,to:x,customReady:D}=Ct();(0,l.useEffect)(()=>{h([{label:"Costs"}])},[h]);const[Qe,Ye]=(0,l.useState)(()=>new Date().toDateString()),X=(0,l.useRef)(null);(0,l.useEffect)(()=>{const t=o(()=>{const s=new Date,n=new Date(s.getFullYear(),s.getMonth(),s.getDate()+1).getTime()-s.getTime();X.current=setTimeout(()=>{Ye(new Date().toDateString()),t()},n)},"schedule");return t(),()=>{X.current!=null&&clearTimeout(X.current)}},[]);const P=(0,l.useMemo)(()=>Mt(),[Qe]),d=i??Bt,{data:A,isLoading:Ue,error:ce}=S({queryKey:v.budgets.overview(d),queryFn:o(()=>ae.overview(d),"queryFn"),enabled:!!i&&D,refetchInterval:3e4,staleTime:5e3}),ue=o(()=>{i&&(y.invalidateQueries({queryKey:v.budgets.overview(i)}),y.invalidateQueries({queryKey:v.dashboard(i)}),y.invalidateQueries({queryKey:v.agents.list(i)}),y.invalidateQueries({queryKey:v.projects.all(i)}))},"invalidateBudgetViews"),me=qe({mutationFn:o(t=>ae.upsertPolicy(d,{scopeType:t.scopeType,scopeId:t.scopeId,amount:t.amount,windowKind:t.windowKind}),"mutationFn"),onSuccess:ue}),K=qe({mutationFn:o(t=>ae.resolveIncident(d,t.incidentId,t),"mutationFn"),onSuccess:ue}),{data:a,isLoading:Ve,error:He}=S({queryKey:v.costs(d,g||void 0,x||void 0),queryFn:o(async()=>{const[t,s,n,r]=await Promise.all([N.summary(d,g||void 0,x||void 0),N.byAgent(d,g||void 0,x||void 0),N.byProject(d,g||void 0,x||void 0),N.byAgentModel(d,g||void 0,x||void 0)]);return{summary:t,byAgent:s,byProject:n,byAgentModel:r}},"queryFn"),enabled:!!i&&D}),{data:p,isLoading:pe,error:Z}=S({queryKey:[v.financeSummary(d,g||void 0,x||void 0),v.financeByBiller(d,g||void 0,x||void 0),v.financeByKind(d,g||void 0,x||void 0),v.financeEvents(d,g||void 0,x||void 0,18)],queryFn:o(async()=>{const[t,s,n,r]=await Promise.all([N.financeSummary(d,g||void 0,x||void 0),N.financeByBiller(d,g||void 0,x||void 0),N.financeByKind(d,g||void 0,x||void 0),N.financeEvents(d,g||void 0,x||void 0,18)]);return{summary:t,byBiller:s,byKind:n,events:r}},"queryFn"),enabled:!!i&&D}),[Ge,ge]=(0,l.useState)(new Set);(0,l.useEffect)(()=>{ge(new Set)},[d,g,x]);function Je(t){ge(s=>{const n=new Set(s);return n.has(t)?n.delete(t):n.add(t),n})}o(Je,"toggleAgent");const Xe=(0,l.useMemo)(()=>{const t=new Map;for(const s of a?.byAgentModel??[]){const n=t.get(s.agentId)??[];n.push(s),t.set(s.agentId,n)}for(const[s,n]of t)t.set(s,n.slice().sort((r,c)=>c.costCents-r.costCents));return t},[a?.byAgentModel]),{data:Q}=S({queryKey:v.usageByProvider(d,g||void 0,x||void 0),queryFn:o(()=>N.byProvider(d,g||void 0,x||void 0),"queryFn"),enabled:!!i&&D&&(u==="providers"||u==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:xe}=S({queryKey:v.usageByBiller(d,g||void 0,x||void 0),queryFn:o(()=>N.byBiller(d,g||void 0,x||void 0),"queryFn"),enabled:!!i&&D&&u==="billers",refetchInterval:3e4,staleTime:1e4}),{data:he}=S({queryKey:v.usageByProvider(d,P.from,P.to),queryFn:o(()=>N.byProvider(d,P.from,P.to),"queryFn"),enabled:!!i&&(u==="providers"||u==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:be}=S({queryKey:v.usageByBiller(d,P.from,P.to),queryFn:o(()=>N.byBiller(d,P.from,P.to),"queryFn"),enabled:!!i&&u==="billers",refetchInterval:3e4,staleTime:1e4}),{data:ve}=S({queryKey:v.usageWindowSpend(d),queryFn:o(()=>N.windowSpend(d),"queryFn"),enabled:!!i&&u==="providers",refetchInterval:3e4,staleTime:1e4}),{data:_,isLoading:ye}=S({queryKey:v.usageQuotaWindows(d),queryFn:o(()=>N.quotaWindows(d),"queryFn"),enabled:!!i&&u==="providers",refetchInterval:3e5,staleTime:6e4}),w=(0,l.useMemo)(()=>{const t=new Map;for(const s of Q??[]){const n=t.get(s.provider)??[];n.push(s),t.set(s.provider,n)}return t},[Q]),k=(0,l.useMemo)(()=>{const t=new Map;for(const s of xe??[]){const n=t.get(s.biller)??[];n.push(s),t.set(s.biller,n)}return t},[xe]),je=(0,l.useMemo)(()=>{const t=new Map;for(const s of he??[])t.set(s.provider,(t.get(s.provider)??0)+s.costCents);return t},[he]),fe=(0,l.useMemo)(()=>{const t=new Map;for(const s of be??[])t.set(s.biller,(t.get(s.biller)??0)+s.costCents);return t},[be]),Ne=(0,l.useMemo)(()=>{const t=new Map;for(const s of ve??[]){const n=t.get(s.provider)??[];n.push(s),t.set(s.provider,n)}return t},[ve]),Ce=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])s.ok&&s.windows.length>0&&t.set(s.provider,s.windows);return t},[_]),we=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])!s.ok&&s.error&&t.set(s.provider,s.error);return t},[_]),Te=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])typeof s.source=="string"&&s.source.length>0&&t.set(s.provider,s.source);return t},[_]),ke=(0,l.useMemo)(()=>{const t=new Map;if(E!=="mtd")return t;const s=a?.summary.budgetCents??0;if(s<=0)return t;const n=a?.summary.spendCents??0,r=new Date,c=r.getDate(),T=new Date(r.getFullYear(),r.getMonth()+1,0).getDate();for(const[f,nt]of w){const ee=nt.reduce((rt,it)=>rt+it.costCents,0),Pe=s*(n>0?ee/n:0);if(Pe<=0){t.set(f,!1);continue}const at=ee/Math.max(c,1);t.set(f,ee+at*(T-c)>Pe)}return t},[E,a,w]),Y=(0,l.useMemo)(()=>Array.from(w.keys()),[w]),U=(0,l.useMemo)(()=>Array.from(k.keys()),[k]),V=b==="all"||Y.includes(b)?b:"all";(0,l.useEffect)(()=>{V!==b&&de("all")},[V,b]);const H=W==="all"||U.includes(W)?W:"all";(0,l.useEffect)(()=>{H!==W&&le("all")},[H,W]);const Ze=(0,l.useMemo)(()=>{const t=Array.from(w.keys()),s=t.reduce((r,c)=>r+(w.get(c)?.reduce((T,f)=>T+f.inputTokens+f.cachedInputTokens+f.outputTokens,0)??0),0),n=t.reduce((r,c)=>r+(w.get(c)?.reduce((T,f)=>T+f.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"}),t.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(s)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(n)})]}):null]})},...t.map(r=>({value:r,label:(0,e.jsx)(Pt,{provider:r,rows:w.get(r)??[]})}))]},[w]),et=(0,l.useMemo)(()=>{const t=Array.from(k.keys()),s=t.reduce((r,c)=>r+(k.get(c)?.reduce((T,f)=>T+f.inputTokens+f.cachedInputTokens+f.outputTokens,0)??0),0),n=t.reduce((r,c)=>r+(k.get(c)?.reduce((T,f)=>T+f.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"}),t.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(s)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(n)})]}):null]})},...t.map(r=>({value:r,label:(0,e.jsx)(It,{biller:r,rows:k.get(r)??[]})}))]},[k]),Se=(a?.byAgent??[]).reduce((t,s)=>t+s.inputTokens+s.cachedInputTokens+s.outputTokens,0),Be=p?.events??[],z=A?.policies??[],I=A?.activeIncidents??[],tt=(0,l.useMemo)(()=>({company:z.filter(t=>t.scopeType==="company"),agent:z.filter(t=>t.scopeType==="agent"),project:z.filter(t=>t.scopeType==="project")}),[z]);if(!i)return(0,e.jsx)(xt,{icon:ne,message:"Select a company to view costs."});const G=E==="custom"&&!D,st=(Ve||pe)&&D,Me=He??Z;return(0,e.jsxs)("div",{className:"space-y-6",children:[(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.jsxs)("div",{children:[(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:"Costs"}),(0,e.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted-foreground",children:"Inference spend, platform fees, credits, and live quota windows."})]}),(0,e.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:Tt.map(t=>(0,e.jsx)(vt,{variant:E===t?"secondary":"ghost",size:"sm",onClick:o(()=>$e(t),"onClick"),"aria-pressed":E===t,children:St[t]},t))})]}),E==="custom"?(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 border border-border p-3",children:[(0,e.jsx)("input",{type:"date",value:Le,onChange:o(t=>We(t.target.value),"onChange"),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"}),(0,e.jsx)("span",{className:"text-sm text-muted-foreground",children:"to"}),(0,e.jsx)("input",{type:"date",value:ze,onChange:o(t=>Oe(t.target.value),"onChange"),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"})]}):null,(0,e.jsxs)("div",{className:"grid gap-3 lg:grid-cols-4",children:[(0,e.jsx)(C,{label:"Inference spend",value:m(a?.summary.spendCents??0),subtitle:`${M(Se)} tokens across request-scoped events`,icon:ne}),(0,e.jsx)(C,{label:"Budget",value:I.length>0?String(I.length):a?.summary.budgetCents&&a.summary.budgetCents>0?`${a.summary.utilizationPercent}%`:"Open",subtitle:I.length>0?`${A?.pausedAgentCount??0} agents paused · ${A?.pausedProjectCount??0} projects paused`:a?.summary.budgetCents&&a.summary.budgetCents>0?`${m(a.summary.spendCents)} of ${m(a.summary.budgetCents)}`:"No monthly cap configured",icon:ie}),(0,e.jsx)(C,{label:"Finance net",value:m(p?.summary.netCents??0),subtitle:`${m(p?.summary.debitCents??0)} debits · ${m(p?.summary.creditCents??0)} credits`,icon:oe}),(0,e.jsx)(C,{label:"Finance events",value:String(p?.summary.eventCount??0),subtitle:`${m(p?.summary.estimatedDebitCents??0)} estimated in range`,icon:re})]})]}),(0,e.jsxs)(te,{value:u,onValueChange:o(t=>j(t),"onValueChange"),children:[(0,e.jsxs)(pt,{variant:"line",className:"justify-start",children:[(0,e.jsx)(O,{value:"overview",children:"Overview"}),(0,e.jsx)(O,{value:"budgets",children:"Budgets"}),(0,e.jsx)(O,{value:"providers",children:"Providers"}),(0,e.jsx)(O,{value:"billers",children:"Billers"}),(0,e.jsx)(O,{value:"finance",children:"Finance"})]}),(0,e.jsx)(B,{value:"overview",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):st?(0,e.jsx)(se,{variant:"costs"}):Me?(0,e.jsx)("p",{className:"text-sm text-destructive",children:Me.message}):(0,e.jsxs)(e.Fragment,{children:[I.length>0?(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:I.slice(0,2).map(t=>(0,e.jsx)(Ee,{incident:t,isMutating:K.isPending,onKeepPaused:o(()=>K.mutate({incidentId:t.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:o(s=>K.mutate({incidentId:t.id,action:"raise_budget_and_resume",amount:s}),"onRaiseAndResume")},t.id))}):null,(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-31)",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"Inference ledger"}),(0,e.jsx)(R,{children:"Request-scoped inference spend for the selected period."})]}),(0,e.jsxs)(F,{className:"space-y-4 px-5 pb-5 pt-2",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"text-3xl font-semibold tabular-nums",children:m(a?.summary.spendCents??0)}),(0,e.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:a?.summary.budgetCents&&a.summary.budgetCents>0?`Budget ${m(a.summary.budgetCents)}`:"Unlimited budget"})]}),(0,e.jsxs)("div",{className:"border border-border px-4 py-3 text-right",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:"usage"}),(0,e.jsx)("div",{className:"mt-1 text-lg font-medium tabular-nums",children:M(Se)})]})]}),a?.summary.budgetCents&&a.summary.budgetCents>0?(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("div",{className:"h-2 overflow-hidden bg-muted",children:(0,e.jsx)("div",{className:Ie("h-full transition-(--tp-width-background-color) duration-150",a.summary.utilizationPercent>90?"bg-(--status-task-blocked)":a.summary.utilizationPercent>70?"bg-(--status-task-todo)":"bg-(--status-task-done)"),style:{width:`${Math.min(100,a.summary.utilizationPercent)}%`}})}),(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:[a.summary.utilizationPercent,"% of monthly budget consumed in this range."]})]}):null]})]}),(0,e.jsx)(_e,{debitCents:p?.summary.debitCents??0,creditCents:p?.summary.creditCents??0,netCents:p?.summary.netCents??0,estimatedDebitCents:p?.summary.estimatedDebitCents??0,eventCount:p?.summary.eventCount??0})]}),(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-32)",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By agent"}),(0,e.jsx)(R,{children:"What each agent consumed in the selected period."})]}),(0,e.jsx)(F,{className:"space-y-2 px-5 pb-5 pt-2",children:(a?.byAgent.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No cost events yet."}):a?.byAgent.map(t=>{const s=Xe.get(t.agentId)??[],n=Ge.has(t.agentId),r=s.length>0;return(0,e.jsxs)("div",{className:"border border-border px-4 py-3",children:[(0,e.jsxs)("div",{className:Ie("flex items-start justify-between gap-3",r?"cursor-pointer select-none":""),onClick:o(()=>r&&Je(t.agentId),"onClick"),children:[(0,e.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[r?n?(0,e.jsx)(ht,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):(0,e.jsx)(bt,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):(0,e.jsx)("span",{className:"h-3 w-3 shrink-0"}),(0,e.jsx)(yt,{agent:{id:t.agentId,name:t.agentName??t.agentId,appearance:t.agentAppearance},size:"sm"}),t.agentStatus==="terminated"?(0,e.jsx)(ft,{status:"terminated"}):null]}),(0,e.jsxs)("div",{className:"text-right text-sm tabular-nums",children:[(0,e.jsx)("div",{className:"font-medium",children:m(t.costCents)}),(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:["in ",M(t.inputTokens+t.cachedInputTokens)," · out ",M(t.outputTokens)]}),t.apiRunCount>0||t.subscriptionRunCount>0?(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:[t.apiRunCount>0?`${t.apiRunCount} api`:"0 api"," · ",t.subscriptionRunCount>0?`${t.subscriptionRunCount} subscription`:"0 subscription"]}):null]})]}),n&&s.length>0?(0,e.jsx)("div",{className:"mt-3 space-y-2 border-l border-border pl-4",children:s.map(c=>{const T=t.costCents>0?Math.round(c.costCents/t.costCents*100):0;return(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 text-xs",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"truncate font-medium text-foreground",children:[J(c.provider),(0,e.jsx)("span",{className:"mx-1 text-border",children:"/"}),(0,e.jsx)("span",{className:"font-mono",children:c.model})]}),(0,e.jsxs)("div",{className:"truncate text-muted-foreground",children:[J(c.biller)," · ",mt(c.billingType)]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsxs)("div",{className:"font-medium",children:[m(c.costCents),(0,e.jsxs)("span",{className:"ml-1 font-normal text-muted-foreground",children:["(",T,"%)"]})]}),(0,e.jsxs)("div",{className:"text-muted-foreground",children:[M(c.inputTokens+c.cachedInputTokens+c.outputTokens)," tok"]})]})]},`${c.provider}:${c.model}:${c.billingType}`)})}):null]},t.agentId)})})]}),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By project"}),(0,e.jsx)(R,{children:"Run costs attributed through project-linked tasks."})]}),(0,e.jsx)(F,{className:"space-y-2 px-5 pb-5 pt-2",children:(a?.byProject.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No project-attributed run costs yet."}):a?.byProject.map((t,s)=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm",children:[(0,e.jsx)("span",{className:"truncate",children:t.projectName??t.projectId??"Unattributed"}),(0,e.jsx)("span",{className:"font-medium tabular-nums",children:m(t.costCents)})]},t.projectId??`unattributed-${s}`))})]}),(0,e.jsx)(Fe,{rows:Be.slice(0,6),emptyMessage:"No finance events yet. Add account-level charges once biller invoices or credits land."})]})]})]})}),(0,e.jsx)(B,{value:"budgets",className:"mt-4 space-y-4",children:Ue?(0,e.jsx)(se,{variant:"costs"}):ce?(0,e.jsx)("p",{className:"text-sm text-destructive",children:ce.message}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(q,{className:"border-border/70 bg-(image:--gradient-extract-2)",children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-3",children:[(0,e.jsx)(L,{className:"text-base",children:"Budget control plane"}),(0,e.jsx)(R,{children:"Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers."})]}),(0,e.jsxs)(F,{className:"grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4",children:[(0,e.jsx)(C,{label:"Active incidents",value:String(I.length),subtitle:"Open soft or hard threshold crossings",icon:oe}),(0,e.jsx)(C,{label:"Pending approvals",value:String(A?.pendingApprovalCount??0),subtitle:"Budget override approvals awaiting board action",icon:re}),(0,e.jsx)(C,{label:"Paused agents",value:String(A?.pausedAgentCount??0),subtitle:"Agent heartbeats blocked by budget",icon:ie}),(0,e.jsx)(C,{label:"Paused projects",value:String(A?.pausedProjectCount??0),subtitle:"Project execution blocked by budget",icon:ne})]})]}),I.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-muted-foreground",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:I.map(t=>(0,e.jsx)(Ee,{incident:t,isMutating:K.isPending,onKeepPaused:o(()=>K.mutate({incidentId:t.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:o(s=>K.mutate({incidentId:t.id,action:"raise_budget_and_resume",amount:s}),"onRaiseAndResume")},t.id))})]}):null,(0,e.jsxs)("div",{className:"space-y-5",children:[["company","agent","project"].map(t=>{const s=tt[t];return s.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:[t," budgets"]}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:t==="company"?"Company-wide monthly policy.":t==="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:s.map(n=>(0,e.jsx)(wt,{summary:n,isSaving:me.isPending,onSave:o(r=>me.mutate({scopeType:n.scopeType,scopeId:n.scopeId,amount:r,windowKind:n.windowKind}),"onSave")},n.policyId))})]},t)}),z.length===0?(0,e.jsx)(q,{children:(0,e.jsx)(F,{className:"px-5 py-8 text-sm text-muted-foreground",children:"No budget policies yet. Set agent and project budgets from their detail pages, or use the existing company monthly budget control."})}):null]})]})}),(0,e.jsx)(B,{value:"providers",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(te,{value:V,onValueChange:de,children:[(0,e.jsx)(De,{items:Ze,value:V}),(0,e.jsx)(B,{value:"all",className:"mt-4",children:Y.length===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No cost events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:Y.map(t=>(0,e.jsx)(Ke,{provider:t,rows:w.get(t)??[],budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,weekSpendCents:je.get(t)??0,windowRows:Ne.get(t)??[],showDeficitNotch:ke.get(t)??!1,quotaWindows:Ce.get(t)??[],quotaError:we.get(t)??null,quotaSource:Te.get(t)??null,quotaLoading:ye},t))})}),Y.map(t=>(0,e.jsx)(B,{value:t,className:"mt-4",children:(0,e.jsx)(Ke,{provider:t,rows:w.get(t)??[],budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,weekSpendCents:je.get(t)??0,windowRows:Ne.get(t)??[],showDeficitNotch:ke.get(t)??!1,quotaWindows:Ce.get(t)??[],quotaError:we.get(t)??null,quotaSource:Te.get(t)??null,quotaLoading:ye})},t))]})})}),(0,e.jsx)(B,{value:"billers",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(te,{value:H,onValueChange:le,children:[(0,e.jsx)(De,{items:et,value:H}),(0,e.jsx)(B,{value:"all",className:"mt-4",children:U.length===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No billable events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:U.map(t=>{const s=(k.get(t)??[])[0];if(!s)return null;const n=(Q??[]).filter(r=>r.biller===t);return(0,e.jsx)(Ae,{row:s,weekSpendCents:fe.get(t)??0,budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,providerRows:n},t)})})}),U.map(t=>{const s=(k.get(t)??[])[0];if(!s)return null;const n=(Q??[]).filter(r=>r.biller===t);return(0,e.jsx)(B,{value:t,className:"mt-4",children:(0,e.jsx)(Ae,{row:s,weekSpendCents:fe.get(t)??0,budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,providerRows:n})},t)})]})})}),(0,e.jsx)(B,{value:"finance",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):pe?(0,e.jsx)(se,{variant:"costs"}):Z?(0,e.jsx)("p",{className:"text-sm text-destructive",children:Z.message}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(_e,{debitCents:p?.summary.debitCents??0,creditCents:p?.summary.creditCents??0,netCents:p?.summary.netCents??0,estimatedDebitCents:p?.summary.estimatedDebitCents??0,eventCount:p?.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)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By biller"}),(0,e.jsx)(R,{children:"Account-level financial events grouped by who charged or credited them."})]}),(0,e.jsx)(F,{className:"grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2",children:(p?.byBiller.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No finance events yet."}):p?.byBiller.map(t=>(0,e.jsx)(kt,{row:t},t.biller))})]}),(0,e.jsx)(Fe,{rows:Be})]}),(0,e.jsx)(jt,{rows:p?.byKind??[]})]})]})})]})]})}o(Ot,"Costs");export{Ot as Costs};
1
+ var ot=Object.defineProperty;var o=(i,h)=>ot(i,"name",{value:h,configurable:!0});import{i as Re}from"./rolldown-runtime-ZpX3ckPj.js";import{Fr as dt,L as J,Lr as lt,M,Pr as ct,S as Ie,T as m,U as ut,Y as v,nr as S,tr as qe,x as mt}from"./createLucideIcon-r3v6fbGz.js";import{i as O,n as B,r as pt,t as te}from"./tabs-DWRZjksg.js";import{r as gt,t as xt}from"./EmptyState-DPcc0zYh.js";import{t as ht}from"./chevron-down-F9aZv-V7.js";import{t as bt}from"./chevron-right-B9JUOr38.js";import{t as vt}from"./button-CAPbz11u.js";import{t as yt}from"./AgentIdentity-MCshmbhZ.js";import{i as R,o as $,r as F,s as L,t as q}from"./card-dmVcp3AX.js";import{t as se}from"./PageSkeleton-DHjTwRT3.js";import{$t as De,C as jt,D as N,E as Ae,Fn as ne,Gt as ft,Hn as re,In as ie,S as Fe,T as Ee,Wn as Nt,_t as ae,b as Ct,gt as wt,v as Tt,w as kt,x as Ke,xn as oe,y as St}from"./index-DMN58MRe.js";var l=Re(lt(),1),e=Re(dt(),1),Bt="__none__";function Mt(){const i=new Date,h=i.getDay(),y=h===0?-6:1-h,u=new Date(i.getFullYear(),i.getMonth(),i.getDate()+y,0,0,0,0),j=new Date(u.getFullYear(),u.getMonth(),u.getDate()+6,23,59,59,999);return{from:u.toISOString(),to:j.toISOString()}}o(Mt,"currentWeekRange");function Pt({provider:i,rows:h}){const y=h.reduce((j,b)=>j+b.inputTokens+b.cachedInputTokens+b.outputTokens,0),u=h.reduce((j,b)=>j+b.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:J(i)}),(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(y)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(u)})]})}o(Pt,"ProviderTabLabel");function It({biller:i,rows:h}){const y=h.reduce((j,b)=>j+b.inputTokens+b.cachedInputTokens+b.outputTokens,0),u=h.reduce((j,b)=>j+b.costCents,0);return(0,e.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,e.jsx)("span",{children:J(i)}),(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(y)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(u)})]})}o(It,"BillerTabLabel");function C({label:i,value:h,subtitle:y,icon:u}){return(0,e.jsx)(q,{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-muted-foreground",children:i}),(0,e.jsx)("div",{className:"mt-2 text-2xl font-semibold tabular-nums",children:h}),(0,e.jsx)("div",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:y})]}),(0,e.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-border",children:(0,e.jsx)(u,{className:"h-4 w-4 text-muted-foreground"})})]})})}o(C,"MetricTile");function _e({debitCents:i,creditCents:h,netCents:y,estimatedDebitCents:u,eventCount:j}){return(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"Finance ledger"}),(0,e.jsx)(R,{children:"Account-level charges that do not map to a single inference request."})]}),(0,e.jsxs)(F,{className:"grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4",children:[(0,e.jsx)(C,{label:"Debits",value:m(i),subtitle:`${j} total event${j===1?"":"s"} in range`,icon:re}),(0,e.jsx)(C,{label:"Credits",value:m(h),subtitle:"Refunds, offsets, and credit returns",icon:Nt}),(0,e.jsx)(C,{label:"Net",value:m(y),subtitle:"Debit minus credit for the selected period",icon:oe}),(0,e.jsx)(C,{label:"Estimated",value:m(u),subtitle:"Estimated debits that are not yet invoice-authoritative",icon:ie})]})]})}o(_e,"FinanceSummaryCard");function Ot(){const{selectedCompanyId:i}=ut(),{setBreadcrumbs:h}=gt(),y=ct(),[u,j]=(0,l.useState)("overview"),[b,de]=(0,l.useState)("all"),[W,le]=(0,l.useState)("all"),{preset:E,setPreset:$e,customFrom:Le,setCustomFrom:We,customTo:ze,setCustomTo:Oe,from:g,to:x,customReady:D}=Ct();(0,l.useEffect)(()=>{h([{label:"Costs"}])},[h]);const[Qe,Ye]=(0,l.useState)(()=>new Date().toDateString()),X=(0,l.useRef)(null);(0,l.useEffect)(()=>{const t=o(()=>{const s=new Date,n=new Date(s.getFullYear(),s.getMonth(),s.getDate()+1).getTime()-s.getTime();X.current=setTimeout(()=>{Ye(new Date().toDateString()),t()},n)},"schedule");return t(),()=>{X.current!=null&&clearTimeout(X.current)}},[]);const P=(0,l.useMemo)(()=>Mt(),[Qe]),d=i??Bt,{data:A,isLoading:Ue,error:ce}=S({queryKey:v.budgets.overview(d),queryFn:o(()=>ae.overview(d),"queryFn"),enabled:!!i&&D,refetchInterval:3e4,staleTime:5e3}),ue=o(()=>{i&&(y.invalidateQueries({queryKey:v.budgets.overview(i)}),y.invalidateQueries({queryKey:v.dashboard(i)}),y.invalidateQueries({queryKey:v.agents.list(i)}),y.invalidateQueries({queryKey:v.projects.all(i)}))},"invalidateBudgetViews"),me=qe({mutationFn:o(t=>ae.upsertPolicy(d,{scopeType:t.scopeType,scopeId:t.scopeId,amount:t.amount,windowKind:t.windowKind}),"mutationFn"),onSuccess:ue}),K=qe({mutationFn:o(t=>ae.resolveIncident(d,t.incidentId,t),"mutationFn"),onSuccess:ue}),{data:a,isLoading:Ve,error:He}=S({queryKey:v.costs(d,g||void 0,x||void 0),queryFn:o(async()=>{const[t,s,n,r]=await Promise.all([N.summary(d,g||void 0,x||void 0),N.byAgent(d,g||void 0,x||void 0),N.byProject(d,g||void 0,x||void 0),N.byAgentModel(d,g||void 0,x||void 0)]);return{summary:t,byAgent:s,byProject:n,byAgentModel:r}},"queryFn"),enabled:!!i&&D}),{data:p,isLoading:pe,error:Z}=S({queryKey:[v.financeSummary(d,g||void 0,x||void 0),v.financeByBiller(d,g||void 0,x||void 0),v.financeByKind(d,g||void 0,x||void 0),v.financeEvents(d,g||void 0,x||void 0,18)],queryFn:o(async()=>{const[t,s,n,r]=await Promise.all([N.financeSummary(d,g||void 0,x||void 0),N.financeByBiller(d,g||void 0,x||void 0),N.financeByKind(d,g||void 0,x||void 0),N.financeEvents(d,g||void 0,x||void 0,18)]);return{summary:t,byBiller:s,byKind:n,events:r}},"queryFn"),enabled:!!i&&D}),[Ge,ge]=(0,l.useState)(new Set);(0,l.useEffect)(()=>{ge(new Set)},[d,g,x]);function Je(t){ge(s=>{const n=new Set(s);return n.has(t)?n.delete(t):n.add(t),n})}o(Je,"toggleAgent");const Xe=(0,l.useMemo)(()=>{const t=new Map;for(const s of a?.byAgentModel??[]){const n=t.get(s.agentId)??[];n.push(s),t.set(s.agentId,n)}for(const[s,n]of t)t.set(s,n.slice().sort((r,c)=>c.costCents-r.costCents));return t},[a?.byAgentModel]),{data:Q}=S({queryKey:v.usageByProvider(d,g||void 0,x||void 0),queryFn:o(()=>N.byProvider(d,g||void 0,x||void 0),"queryFn"),enabled:!!i&&D&&(u==="providers"||u==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:xe}=S({queryKey:v.usageByBiller(d,g||void 0,x||void 0),queryFn:o(()=>N.byBiller(d,g||void 0,x||void 0),"queryFn"),enabled:!!i&&D&&u==="billers",refetchInterval:3e4,staleTime:1e4}),{data:he}=S({queryKey:v.usageByProvider(d,P.from,P.to),queryFn:o(()=>N.byProvider(d,P.from,P.to),"queryFn"),enabled:!!i&&(u==="providers"||u==="billers"),refetchInterval:3e4,staleTime:1e4}),{data:be}=S({queryKey:v.usageByBiller(d,P.from,P.to),queryFn:o(()=>N.byBiller(d,P.from,P.to),"queryFn"),enabled:!!i&&u==="billers",refetchInterval:3e4,staleTime:1e4}),{data:ve}=S({queryKey:v.usageWindowSpend(d),queryFn:o(()=>N.windowSpend(d),"queryFn"),enabled:!!i&&u==="providers",refetchInterval:3e4,staleTime:1e4}),{data:_,isLoading:ye}=S({queryKey:v.usageQuotaWindows(d),queryFn:o(()=>N.quotaWindows(d),"queryFn"),enabled:!!i&&u==="providers",refetchInterval:3e5,staleTime:6e4}),w=(0,l.useMemo)(()=>{const t=new Map;for(const s of Q??[]){const n=t.get(s.provider)??[];n.push(s),t.set(s.provider,n)}return t},[Q]),k=(0,l.useMemo)(()=>{const t=new Map;for(const s of xe??[]){const n=t.get(s.biller)??[];n.push(s),t.set(s.biller,n)}return t},[xe]),je=(0,l.useMemo)(()=>{const t=new Map;for(const s of he??[])t.set(s.provider,(t.get(s.provider)??0)+s.costCents);return t},[he]),fe=(0,l.useMemo)(()=>{const t=new Map;for(const s of be??[])t.set(s.biller,(t.get(s.biller)??0)+s.costCents);return t},[be]),Ne=(0,l.useMemo)(()=>{const t=new Map;for(const s of ve??[]){const n=t.get(s.provider)??[];n.push(s),t.set(s.provider,n)}return t},[ve]),Ce=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])s.ok&&s.windows.length>0&&t.set(s.provider,s.windows);return t},[_]),we=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])!s.ok&&s.error&&t.set(s.provider,s.error);return t},[_]),Te=(0,l.useMemo)(()=>{const t=new Map;for(const s of _??[])typeof s.source=="string"&&s.source.length>0&&t.set(s.provider,s.source);return t},[_]),ke=(0,l.useMemo)(()=>{const t=new Map;if(E!=="mtd")return t;const s=a?.summary.budgetCents??0;if(s<=0)return t;const n=a?.summary.spendCents??0,r=new Date,c=r.getDate(),T=new Date(r.getFullYear(),r.getMonth()+1,0).getDate();for(const[f,nt]of w){const ee=nt.reduce((rt,it)=>rt+it.costCents,0),Pe=s*(n>0?ee/n:0);if(Pe<=0){t.set(f,!1);continue}const at=ee/Math.max(c,1);t.set(f,ee+at*(T-c)>Pe)}return t},[E,a,w]),Y=(0,l.useMemo)(()=>Array.from(w.keys()),[w]),U=(0,l.useMemo)(()=>Array.from(k.keys()),[k]),V=b==="all"||Y.includes(b)?b:"all";(0,l.useEffect)(()=>{V!==b&&de("all")},[V,b]);const H=W==="all"||U.includes(W)?W:"all";(0,l.useEffect)(()=>{H!==W&&le("all")},[H,W]);const Ze=(0,l.useMemo)(()=>{const t=Array.from(w.keys()),s=t.reduce((r,c)=>r+(w.get(c)?.reduce((T,f)=>T+f.inputTokens+f.cachedInputTokens+f.outputTokens,0)??0),0),n=t.reduce((r,c)=>r+(w.get(c)?.reduce((T,f)=>T+f.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"}),t.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(s)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(n)})]}):null]})},...t.map(r=>({value:r,label:(0,e.jsx)(Pt,{provider:r,rows:w.get(r)??[]})}))]},[w]),et=(0,l.useMemo)(()=>{const t=Array.from(k.keys()),s=t.reduce((r,c)=>r+(k.get(c)?.reduce((T,f)=>T+f.inputTokens+f.cachedInputTokens+f.outputTokens,0)??0),0),n=t.reduce((r,c)=>r+(k.get(c)?.reduce((T,f)=>T+f.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"}),t.length>0?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:M(s)}),(0,e.jsx)("span",{className:"text-xs text-muted-foreground",children:m(n)})]}):null]})},...t.map(r=>({value:r,label:(0,e.jsx)(It,{biller:r,rows:k.get(r)??[]})}))]},[k]),Se=(a?.byAgent??[]).reduce((t,s)=>t+s.inputTokens+s.cachedInputTokens+s.outputTokens,0),Be=p?.events??[],z=A?.policies??[],I=A?.activeIncidents??[],tt=(0,l.useMemo)(()=>({company:z.filter(t=>t.scopeType==="company"),agent:z.filter(t=>t.scopeType==="agent"),project:z.filter(t=>t.scopeType==="project")}),[z]);if(!i)return(0,e.jsx)(xt,{icon:ne,message:"Select a company to view costs."});const G=E==="custom"&&!D,st=(Ve||pe)&&D,Me=He??Z;return(0,e.jsxs)("div",{className:"space-y-6",children:[(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.jsxs)("div",{children:[(0,e.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:"Costs"}),(0,e.jsx)("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted-foreground",children:"Inference spend, platform fees, credits, and live quota windows."})]}),(0,e.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:Tt.map(t=>(0,e.jsx)(vt,{variant:E===t?"secondary":"ghost",size:"sm",onClick:o(()=>$e(t),"onClick"),"aria-pressed":E===t,children:St[t]},t))})]}),E==="custom"?(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2 border border-border p-3",children:[(0,e.jsx)("input",{type:"date",value:Le,onChange:o(t=>We(t.target.value),"onChange"),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"}),(0,e.jsx)("span",{className:"text-sm text-muted-foreground",children:"to"}),(0,e.jsx)("input",{type:"date",value:ze,onChange:o(t=>Oe(t.target.value),"onChange"),className:"h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"})]}):null,(0,e.jsxs)("div",{className:"grid gap-3 lg:grid-cols-4",children:[(0,e.jsx)(C,{label:"Inference spend",value:m(a?.summary.spendCents??0),subtitle:`${M(Se)} tokens across request-scoped events`,icon:ne}),(0,e.jsx)(C,{label:"Budget",value:I.length>0?String(I.length):a?.summary.budgetCents&&a.summary.budgetCents>0?`${a.summary.utilizationPercent}%`:"Open",subtitle:I.length>0?`${A?.pausedAgentCount??0} agents paused · ${A?.pausedProjectCount??0} projects paused`:a?.summary.budgetCents&&a.summary.budgetCents>0?`${m(a.summary.spendCents)} of ${m(a.summary.budgetCents)}`:"No monthly cap configured",icon:ie}),(0,e.jsx)(C,{label:"Finance net",value:m(p?.summary.netCents??0),subtitle:`${m(p?.summary.debitCents??0)} debits · ${m(p?.summary.creditCents??0)} credits`,icon:oe}),(0,e.jsx)(C,{label:"Finance events",value:String(p?.summary.eventCount??0),subtitle:`${m(p?.summary.estimatedDebitCents??0)} estimated in range`,icon:re})]})]}),(0,e.jsxs)(te,{value:u,onValueChange:o(t=>j(t),"onValueChange"),children:[(0,e.jsxs)(pt,{variant:"line",className:"justify-start",children:[(0,e.jsx)(O,{value:"overview",children:"Overview"}),(0,e.jsx)(O,{value:"budgets",children:"Budgets"}),(0,e.jsx)(O,{value:"providers",children:"Providers"}),(0,e.jsx)(O,{value:"billers",children:"Billers"}),(0,e.jsx)(O,{value:"finance",children:"Finance"})]}),(0,e.jsx)(B,{value:"overview",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):st?(0,e.jsx)(se,{variant:"costs"}):Me?(0,e.jsx)("p",{className:"text-sm text-destructive",children:Me.message}):(0,e.jsxs)(e.Fragment,{children:[I.length>0?(0,e.jsx)("div",{className:"grid gap-4 xl:grid-cols-2",children:I.slice(0,2).map(t=>(0,e.jsx)(Ee,{incident:t,isMutating:K.isPending,onKeepPaused:o(()=>K.mutate({incidentId:t.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:o(s=>K.mutate({incidentId:t.id,action:"raise_budget_and_resume",amount:s}),"onRaiseAndResume")},t.id))}):null,(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-31)",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"Inference ledger"}),(0,e.jsx)(R,{children:"Request-scoped inference spend for the selected period."})]}),(0,e.jsxs)(F,{className:"space-y-4 px-5 pb-5 pt-2",children:[(0,e.jsxs)("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("div",{className:"text-3xl font-semibold tabular-nums",children:m(a?.summary.spendCents??0)}),(0,e.jsx)("div",{className:"mt-1 text-sm text-muted-foreground",children:a?.summary.budgetCents&&a.summary.budgetCents>0?`Budget ${m(a.summary.budgetCents)}`:"Unlimited budget"})]}),(0,e.jsxs)("div",{className:"border border-border px-4 py-3 text-right",children:[(0,e.jsx)("div",{className:"text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground",children:"usage"}),(0,e.jsx)("div",{className:"mt-1 text-lg font-medium tabular-nums",children:M(Se)})]})]}),a?.summary.budgetCents&&a.summary.budgetCents>0?(0,e.jsxs)("div",{className:"space-y-2",children:[(0,e.jsx)("div",{className:"h-2 overflow-hidden bg-muted",children:(0,e.jsx)("div",{className:Ie("h-full transition-(--tp-width-background-color) duration-150",a.summary.utilizationPercent>90?"bg-(--status-task-blocked)":a.summary.utilizationPercent>70?"bg-(--status-task-todo)":"bg-(--status-task-done)"),style:{width:`${Math.min(100,a.summary.utilizationPercent)}%`}})}),(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:[a.summary.utilizationPercent,"% of monthly budget consumed in this range."]})]}):null]})]}),(0,e.jsx)(_e,{debitCents:p?.summary.debitCents??0,creditCents:p?.summary.creditCents??0,netCents:p?.summary.netCents??0,estimatedDebitCents:p?.summary.estimatedDebitCents??0,eventCount:p?.summary.eventCount??0})]}),(0,e.jsxs)("div",{className:"grid gap-4 xl:grid-cols-(--gtc-32)",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By agent"}),(0,e.jsx)(R,{children:"What each agent consumed in the selected period."})]}),(0,e.jsx)(F,{className:"space-y-2 px-5 pb-5 pt-2",children:(a?.byAgent.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No cost events yet."}):a?.byAgent.map(t=>{const s=Xe.get(t.agentId)??[],n=Ge.has(t.agentId),r=s.length>0;return(0,e.jsxs)("div",{className:"border border-border px-4 py-3",children:[(0,e.jsxs)("div",{className:Ie("flex items-start justify-between gap-3",r?"cursor-pointer select-none":""),onClick:o(()=>r&&Je(t.agentId),"onClick"),children:[(0,e.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[r?n?(0,e.jsx)(ht,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):(0,e.jsx)(bt,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):(0,e.jsx)("span",{className:"h-3 w-3 shrink-0"}),(0,e.jsx)(yt,{agent:{id:t.agentId,name:t.agentName??t.agentId,appearance:t.agentAppearance},size:"sm"}),t.agentStatus==="terminated"?(0,e.jsx)(ft,{status:"terminated"}):null]}),(0,e.jsxs)("div",{className:"text-right text-sm tabular-nums",children:[(0,e.jsx)("div",{className:"font-medium",children:m(t.costCents)}),(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:["in ",M(t.inputTokens+t.cachedInputTokens)," · out ",M(t.outputTokens)]}),t.apiRunCount>0||t.subscriptionRunCount>0?(0,e.jsxs)("div",{className:"text-xs text-muted-foreground",children:[t.apiRunCount>0?`${t.apiRunCount} api`:"0 api"," · ",t.subscriptionRunCount>0?`${t.subscriptionRunCount} subscription`:"0 subscription"]}):null]})]}),n&&s.length>0?(0,e.jsx)("div",{className:"mt-3 space-y-2 border-l border-border pl-4",children:s.map(c=>{const T=t.costCents>0?Math.round(c.costCents/t.costCents*100):0;return(0,e.jsxs)("div",{className:"flex items-start justify-between gap-3 text-xs",children:[(0,e.jsxs)("div",{className:"min-w-0",children:[(0,e.jsxs)("div",{className:"truncate font-medium text-foreground",children:[J(c.provider),(0,e.jsx)("span",{className:"mx-1 text-border",children:"/"}),(0,e.jsx)("span",{className:"font-mono",children:c.model})]}),(0,e.jsxs)("div",{className:"truncate text-muted-foreground",children:[J(c.biller)," · ",mt(c.billingType)]})]}),(0,e.jsxs)("div",{className:"text-right tabular-nums",children:[(0,e.jsxs)("div",{className:"font-medium",children:[m(c.costCents),(0,e.jsxs)("span",{className:"ml-1 font-normal text-muted-foreground",children:["(",T,"%)"]})]}),(0,e.jsxs)("div",{className:"text-muted-foreground",children:[M(c.inputTokens+c.cachedInputTokens+c.outputTokens)," tok"]})]})]},`${c.provider}:${c.model}:${c.billingType}`)})}):null]},t.agentId)})})]}),(0,e.jsxs)("div",{className:"space-y-4",children:[(0,e.jsxs)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By project"}),(0,e.jsx)(R,{children:"Run costs attributed through project-linked tasks."})]}),(0,e.jsx)(F,{className:"space-y-2 px-5 pb-5 pt-2",children:(a?.byProject.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No project-attributed run costs yet."}):a?.byProject.map((t,s)=>(0,e.jsxs)("div",{className:"flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm",children:[(0,e.jsx)("span",{className:"truncate",children:t.projectName??t.projectId??"Unattributed"}),(0,e.jsx)("span",{className:"font-medium tabular-nums",children:m(t.costCents)})]},t.projectId??`unattributed-${s}`))})]}),(0,e.jsx)(Fe,{rows:Be.slice(0,6),emptyMessage:"No finance events yet. Add account-level charges once biller invoices or credits land."})]})]})]})}),(0,e.jsx)(B,{value:"budgets",className:"mt-4 space-y-4",children:Ue?(0,e.jsx)(se,{variant:"costs"}):ce?(0,e.jsx)("p",{className:"text-sm text-destructive",children:ce.message}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(q,{className:"border-border/70 bg-(image:--gradient-extract-2)",children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-3",children:[(0,e.jsx)(L,{className:"text-base",children:"Budget control plane"}),(0,e.jsx)(R,{children:"Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers."})]}),(0,e.jsxs)(F,{className:"grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4",children:[(0,e.jsx)(C,{label:"Active incidents",value:String(I.length),subtitle:"Open soft or hard threshold crossings",icon:oe}),(0,e.jsx)(C,{label:"Pending approvals",value:String(A?.pendingApprovalCount??0),subtitle:"Budget override approvals awaiting board action",icon:re}),(0,e.jsx)(C,{label:"Paused agents",value:String(A?.pausedAgentCount??0),subtitle:"Agent heartbeats blocked by budget",icon:ie}),(0,e.jsx)(C,{label:"Paused projects",value:String(A?.pausedProjectCount??0),subtitle:"Project execution blocked by budget",icon:ne})]})]}),I.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-muted-foreground",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:I.map(t=>(0,e.jsx)(Ee,{incident:t,isMutating:K.isPending,onKeepPaused:o(()=>K.mutate({incidentId:t.id,action:"keep_paused"}),"onKeepPaused"),onRaiseAndResume:o(s=>K.mutate({incidentId:t.id,action:"raise_budget_and_resume",amount:s}),"onRaiseAndResume")},t.id))})]}):null,(0,e.jsxs)("div",{className:"space-y-5",children:[["company","agent","project"].map(t=>{const s=tt[t];return s.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:[t," budgets"]}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:t==="company"?"Company-wide monthly policy.":t==="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:s.map(n=>(0,e.jsx)(wt,{summary:n,isSaving:me.isPending,onSave:o(r=>me.mutate({scopeType:n.scopeType,scopeId:n.scopeId,amount:r,windowKind:n.windowKind}),"onSave")},n.policyId))})]},t)}),z.length===0?(0,e.jsx)(q,{children:(0,e.jsx)(F,{className:"px-5 py-8 text-sm text-muted-foreground",children:"No budget policies yet. Set agent and project budgets from their detail pages, or use the existing company monthly budget control."})}):null]})]})}),(0,e.jsx)(B,{value:"providers",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(te,{value:V,onValueChange:de,children:[(0,e.jsx)(De,{items:Ze,value:V}),(0,e.jsx)(B,{value:"all",className:"mt-4",children:Y.length===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No cost events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:Y.map(t=>(0,e.jsx)(Ke,{provider:t,rows:w.get(t)??[],budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,weekSpendCents:je.get(t)??0,windowRows:Ne.get(t)??[],showDeficitNotch:ke.get(t)??!1,quotaWindows:Ce.get(t)??[],quotaError:we.get(t)??null,quotaSource:Te.get(t)??null,quotaLoading:ye},t))})}),Y.map(t=>(0,e.jsx)(B,{value:t,className:"mt-4",children:(0,e.jsx)(Ke,{provider:t,rows:w.get(t)??[],budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,weekSpendCents:je.get(t)??0,windowRows:Ne.get(t)??[],showDeficitNotch:ke.get(t)??!1,quotaWindows:Ce.get(t)??[],quotaError:we.get(t)??null,quotaSource:Te.get(t)??null,quotaLoading:ye})},t))]})})}),(0,e.jsx)(B,{value:"billers",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):(0,e.jsx)(e.Fragment,{children:(0,e.jsxs)(te,{value:H,onValueChange:le,children:[(0,e.jsx)(De,{items:et,value:H}),(0,e.jsx)(B,{value:"all",className:"mt-4",children:U.length===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No billable events in this period."}):(0,e.jsx)("div",{className:"grid gap-4 md:grid-cols-2",children:U.map(t=>{const s=(k.get(t)??[])[0];if(!s)return null;const n=(Q??[]).filter(r=>r.biller===t);return(0,e.jsx)(Ae,{row:s,weekSpendCents:fe.get(t)??0,budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,providerRows:n},t)})})}),U.map(t=>{const s=(k.get(t)??[])[0];if(!s)return null;const n=(Q??[]).filter(r=>r.biller===t);return(0,e.jsx)(B,{value:t,className:"mt-4",children:(0,e.jsx)(Ae,{row:s,weekSpendCents:fe.get(t)??0,budgetMonthlyCents:a?.summary.budgetCents??0,totalCompanySpendCents:a?.summary.spendCents??0,providerRows:n})},t)})]})})}),(0,e.jsx)(B,{value:"finance",className:"mt-4 space-y-4",children:G?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"Select a start and end date to load data."}):pe?(0,e.jsx)(se,{variant:"costs"}):Z?(0,e.jsx)("p",{className:"text-sm text-destructive",children:Z.message}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(_e,{debitCents:p?.summary.debitCents??0,creditCents:p?.summary.creditCents??0,netCents:p?.summary.netCents??0,estimatedDebitCents:p?.summary.estimatedDebitCents??0,eventCount:p?.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)(q,{children:[(0,e.jsxs)($,{className:"px-5 pt-5 pb-2",children:[(0,e.jsx)(L,{className:"text-base",children:"By biller"}),(0,e.jsx)(R,{children:"Account-level financial events grouped by who charged or credited them."})]}),(0,e.jsx)(F,{className:"grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2",children:(p?.byBiller.length??0)===0?(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:"No finance events yet."}):p?.byBiller.map(t=>(0,e.jsx)(kt,{row:t},t.biller))})]}),(0,e.jsx)(Fe,{rows:Be})]}),(0,e.jsx)(jt,{rows:p?.byKind??[]})]})]})})]})]})}o(Ot,"Costs");export{Ot as Costs};