@useorgx/openclaw-plugin 0.7.17 → 0.7.20

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 (111) hide show
  1. package/dashboard/dist/assets/{Crj3jKHE.js → B014hrCe.js} +1 -1
  2. package/dashboard/dist/assets/B014hrCe.js.br +0 -0
  3. package/dashboard/dist/assets/B014hrCe.js.gz +0 -0
  4. package/dashboard/dist/assets/{DBRLnKWw.js → BGY6oI8h.js} +1 -1
  5. package/dashboard/dist/assets/BGY6oI8h.js.br +0 -0
  6. package/dashboard/dist/assets/BGY6oI8h.js.gz +0 -0
  7. package/dashboard/dist/assets/BJI1Iy5v.css +1 -0
  8. package/dashboard/dist/assets/BJI1Iy5v.css.br +0 -0
  9. package/dashboard/dist/assets/BJI1Iy5v.css.gz +0 -0
  10. package/dashboard/dist/assets/BUvcp_7V.js +1 -0
  11. package/dashboard/dist/assets/BUvcp_7V.js.br +0 -0
  12. package/dashboard/dist/assets/BUvcp_7V.js.gz +0 -0
  13. package/dashboard/dist/assets/BV2Tf8S2.js +212 -0
  14. package/dashboard/dist/assets/BV2Tf8S2.js.br +0 -0
  15. package/dashboard/dist/assets/BV2Tf8S2.js.gz +0 -0
  16. package/dashboard/dist/assets/{CoDun8X6.js → BYb6DARX.js} +1 -1
  17. package/dashboard/dist/assets/BYb6DARX.js.br +0 -0
  18. package/dashboard/dist/assets/BYb6DARX.js.gz +0 -0
  19. package/dashboard/dist/assets/{DLNTxNX-.js → BoDhb8_y.js} +1 -1
  20. package/dashboard/dist/assets/BoDhb8_y.js.br +0 -0
  21. package/dashboard/dist/assets/BoDhb8_y.js.gz +0 -0
  22. package/dashboard/dist/assets/Bqk_l0k6.js +1 -0
  23. package/dashboard/dist/assets/Bqk_l0k6.js.br +0 -0
  24. package/dashboard/dist/assets/Bqk_l0k6.js.gz +0 -0
  25. package/dashboard/dist/assets/{BDlKSbsp.js → CV0sWMbv.js} +1 -1
  26. package/dashboard/dist/assets/CV0sWMbv.js.br +0 -0
  27. package/dashboard/dist/assets/CV0sWMbv.js.gz +0 -0
  28. package/dashboard/dist/assets/CaAkScfa.js +1 -0
  29. package/dashboard/dist/assets/CaAkScfa.js.br +0 -0
  30. package/dashboard/dist/assets/CaAkScfa.js.gz +0 -0
  31. package/dashboard/dist/assets/{CyUpNSKv.js → Ck5KlsPN.js} +1 -1
  32. package/dashboard/dist/assets/Ck5KlsPN.js.br +0 -0
  33. package/dashboard/dist/assets/Ck5KlsPN.js.gz +0 -0
  34. package/dashboard/dist/assets/{CMir7ekf.js → D2G51wQm.js} +1 -1
  35. package/dashboard/dist/assets/D2G51wQm.js.br +0 -0
  36. package/dashboard/dist/assets/D2G51wQm.js.gz +0 -0
  37. package/dashboard/dist/assets/{D8mvKY2h.js → DAr4MfFk.js} +1 -1
  38. package/dashboard/dist/assets/DAr4MfFk.js.br +0 -0
  39. package/dashboard/dist/assets/DAr4MfFk.js.gz +0 -0
  40. package/dashboard/dist/assets/{DvFumX8R.js → DXVs61e1.js} +1 -1
  41. package/dashboard/dist/assets/DXVs61e1.js.br +0 -0
  42. package/dashboard/dist/assets/DXVs61e1.js.gz +0 -0
  43. package/dashboard/dist/assets/{CWXk6UZl.js → DibzNd0I.js} +1 -1
  44. package/dashboard/dist/assets/DibzNd0I.js.br +0 -0
  45. package/dashboard/dist/assets/DibzNd0I.js.gz +0 -0
  46. package/dashboard/dist/assets/{DdYkuATV.js → Dm0CfDGr.js} +1 -1
  47. package/dashboard/dist/assets/Dm0CfDGr.js.br +0 -0
  48. package/dashboard/dist/assets/Dm0CfDGr.js.gz +0 -0
  49. package/dashboard/dist/assets/_zpQCpjm.js +1 -0
  50. package/dashboard/dist/assets/_zpQCpjm.js.br +0 -0
  51. package/dashboard/dist/assets/_zpQCpjm.js.gz +0 -0
  52. package/dashboard/dist/assets/{B8NuBCcY.js → uNGpYMSH.js} +1 -1
  53. package/dashboard/dist/assets/uNGpYMSH.js.br +0 -0
  54. package/dashboard/dist/assets/uNGpYMSH.js.gz +0 -0
  55. package/dashboard/dist/assets/{B7kFLPiD.js → wa4jJQK9.js} +1 -1
  56. package/dashboard/dist/assets/wa4jJQK9.js.br +0 -0
  57. package/dashboard/dist/assets/wa4jJQK9.js.gz +0 -0
  58. package/dashboard/dist/index.html +2 -2
  59. package/dashboard/dist/index.html.br +0 -0
  60. package/dashboard/dist/index.html.gz +0 -0
  61. package/dist/http/helpers/auto-continue-engine.d.ts +39 -0
  62. package/dist/http/helpers/auto-continue-engine.js +96 -0
  63. package/dist/http/index.js +2 -1
  64. package/dist/http/routes/mission-control-read.d.ts +14 -0
  65. package/dist/http/routes/mission-control-read.js +69 -5
  66. package/dist/outbox.js +9 -2
  67. package/package.json +2 -1
  68. package/dashboard/dist/assets/05zHA1Am.js +0 -1
  69. package/dashboard/dist/assets/05zHA1Am.js.br +0 -0
  70. package/dashboard/dist/assets/05zHA1Am.js.gz +0 -0
  71. package/dashboard/dist/assets/0uYJrBLl.js +0 -1
  72. package/dashboard/dist/assets/0uYJrBLl.js.br +0 -0
  73. package/dashboard/dist/assets/0uYJrBLl.js.gz +0 -0
  74. package/dashboard/dist/assets/8nr6IqT4.js +0 -1
  75. package/dashboard/dist/assets/8nr6IqT4.js.br +0 -0
  76. package/dashboard/dist/assets/8nr6IqT4.js.gz +0 -0
  77. package/dashboard/dist/assets/B7kFLPiD.js.br +0 -0
  78. package/dashboard/dist/assets/B7kFLPiD.js.gz +0 -0
  79. package/dashboard/dist/assets/B8NuBCcY.js.br +0 -0
  80. package/dashboard/dist/assets/B8NuBCcY.js.gz +0 -0
  81. package/dashboard/dist/assets/BDlKSbsp.js.br +0 -0
  82. package/dashboard/dist/assets/BDlKSbsp.js.gz +0 -0
  83. package/dashboard/dist/assets/C8AYbjlq.js +0 -212
  84. package/dashboard/dist/assets/C8AYbjlq.js.br +0 -0
  85. package/dashboard/dist/assets/C8AYbjlq.js.gz +0 -0
  86. package/dashboard/dist/assets/CMir7ekf.js.br +0 -0
  87. package/dashboard/dist/assets/CMir7ekf.js.gz +0 -0
  88. package/dashboard/dist/assets/CWXk6UZl.js.br +0 -0
  89. package/dashboard/dist/assets/CWXk6UZl.js.gz +0 -0
  90. package/dashboard/dist/assets/CoDun8X6.js.br +0 -0
  91. package/dashboard/dist/assets/CoDun8X6.js.gz +0 -0
  92. package/dashboard/dist/assets/Crj3jKHE.js.br +0 -0
  93. package/dashboard/dist/assets/Crj3jKHE.js.gz +0 -0
  94. package/dashboard/dist/assets/CyUpNSKv.js.br +0 -0
  95. package/dashboard/dist/assets/CyUpNSKv.js.gz +0 -0
  96. package/dashboard/dist/assets/D8mvKY2h.js.br +0 -0
  97. package/dashboard/dist/assets/D8mvKY2h.js.gz +0 -0
  98. package/dashboard/dist/assets/DBRLnKWw.js.br +0 -0
  99. package/dashboard/dist/assets/DBRLnKWw.js.gz +0 -0
  100. package/dashboard/dist/assets/DBct8HLW.js +0 -1
  101. package/dashboard/dist/assets/DBct8HLW.js.br +0 -0
  102. package/dashboard/dist/assets/DBct8HLW.js.gz +0 -0
  103. package/dashboard/dist/assets/DLNTxNX-.js.br +0 -0
  104. package/dashboard/dist/assets/DLNTxNX-.js.gz +0 -0
  105. package/dashboard/dist/assets/DdYkuATV.js.br +0 -0
  106. package/dashboard/dist/assets/DdYkuATV.js.gz +0 -0
  107. package/dashboard/dist/assets/DvFumX8R.js.br +0 -0
  108. package/dashboard/dist/assets/DvFumX8R.js.gz +0 -0
  109. package/dashboard/dist/assets/RZkbqlJk.css +0 -1
  110. package/dashboard/dist/assets/RZkbqlJk.css.br +0 -0
  111. package/dashboard/dist/assets/RZkbqlJk.css.gz +0 -0
@@ -0,0 +1,212 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CaAkScfa.js","assets/Dj2k1r16.js","assets/DMKyYAtD.js","assets/BUvcp_7V.js","assets/DXVs61e1.js","assets/eeHXe_OQ.js","assets/wa4jJQK9.js","assets/BCudUvwg.js","assets/BGY6oI8h.js","assets/DibzNd0I.js","assets/cX2e-TLi.js","assets/BjK42gtU.js","assets/qm8xLgv-.css","assets/BV0BcV1u.js","assets/uNGpYMSH.js","assets/DAr4MfFk.js","assets/D2G51wQm.js","assets/CSlBSRyv.js","assets/C-MOJWHs.js","assets/Ck5KlsPN.js","assets/BoDhb8_y.js","assets/_zpQCpjm.js","assets/CV0sWMbv.js","assets/B014hrCe.js","assets/Dm0CfDGr.js","assets/Bqk_l0k6.js","assets/BYb6DARX.js"])))=>i.map(i=>d[i]);
2
+ var Qc=Object.defineProperty;var Yc=(e,t,s)=>t in e?Qc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Yn=(e,t,s)=>Yc(e,typeof t!="symbol"?t+"":t,s);import{r as o,j as n,a as Jc,d as Zc}from"./Dj2k1r16.js";import{u as Wa,a as ed,b as Dn,c as Gs,Q as td,d as nd}from"./DMKyYAtD.js";import{m as he,A as It,u as ps}from"./eeHXe_OQ.js";import{a7 as sd}from"./cX2e-TLi.js";import{D as mo}from"./BjK42gtU.js";import{T as id,u as rd}from"./BV0BcV1u.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const a of r)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const a={};return r.integrity&&(a.integrity=r.integrity),r.referrerPolicy&&(a.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?a.credentials="include":r.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(r){if(r.ep)return;r.ep=!0;const a=s(r);fetch(r.href,a)}})();const ad="modulepreload",od=function(e){return"/orgx/live/"+e},po={},un=function(t,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(p=>Promise.resolve(p).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));r=l(s.map(u=>{if(u=od(u),u in po)return;po[u]=!0;const p=u.endsWith(".css"),x=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${x}`))return;const b=document.createElement("link");if(b.rel=p?"stylesheet":ad,p||(b.as="script"),b.crossOrigin="",b.href=u,d&&b.setAttribute("nonce",d),document.head.appendChild(b),p)return new Promise((h,I)=>{b.addEventListener("load",h),b.addEventListener("error",()=>I(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})},fo=()=>{const e=new Date,t=r=>new Date(e.getTime()-r*60*1e3).toISOString(),s=r=>new Date(e.getTime()-r*60*60*1e3).toISOString(),i=r=>new Date(e.getTime()-r*24*60*60*1e3).toISOString();return{connection:"connected",lastActivity:"1m ago",lastSnapshotAt:e.toISOString(),snapshotVersion:3,sessions:{groups:[{id:"init-1",label:"Content Engine: Dogfood the Larry Playbook",status:"active"},{id:"init-2",label:"Live View UX Redesign — The Conductor's Display",status:"active"},{id:"init-3",label:"Directory Submissions & External References",status:"active"},{id:"init-4",label:"Revenue Expansion Q2",status:"completed"},{id:"init-5",label:"Incident Replay & Reliability",status:"blocked"}],edges:[{parentId:"run-100",childId:"run-101"},{parentId:"run-100",childId:"run-102"},{parentId:"run-100",childId:"run-103"},{parentId:"run-200",childId:"run-201"},{parentId:"run-200",childId:"run-202"},{parentId:"run-200",childId:"run-203"},{parentId:"run-300",childId:"run-301"},{parentId:"run-300",childId:"run-302"},{parentId:"run-300",childId:"run-303"}],nodes:[{id:"run-100",parentId:null,runId:"run-100",title:"Content Engine: Program orchestrator",agentId:"holt",agentName:"Holt",status:"running",progress:52,initiativeId:"init-1",workstreamId:null,groupId:"init-1",groupLabel:"Content Engine: Dogfood the Larry Playbook",startedAt:s(4),updatedAt:t(1),lastEventAt:t(1),lastEventSummary:"Stall scan complete; queue advanced to blog QA and distribution prep.",blockers:[],phase:"execution",state:"running",eta:"26m",checkpointCount:18,runtimeClient:"codex",runtimeLabel:"Codex Dispatch",runtimeProvider:"codex",instanceId:"instance-codex-01",lastHeartbeatAt:t(1)},{id:"run-101",parentId:"run-100",runId:"run-101",title:"Long-form article generation",agentId:"kimi",agentName:"Kimi",status:"in_progress",progress:61,initiativeId:"init-1",workstreamId:"ws-content-1",groupId:"init-1",groupLabel:"Content Engine: Dogfood the Larry Playbook",startedAt:s(2),updatedAt:t(4),lastEventAt:t(4),lastEventSummary:"Two draft sections passed quality checks; awaiting review handoff.",blockers:[],phase:"review",state:"running",eta:"14m",checkpointCount:6,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Runner",runtimeProvider:"openclaw",instanceId:"instance-openclaw-03",lastHeartbeatAt:t(2)},{id:"run-102",parentId:"run-100",runId:"run-102",title:"Persona QA and legal sweep",agentId:"holt",agentName:"Holt",status:"blocked",progress:34,initiativeId:"init-1",workstreamId:"ws-content-legal",groupId:"init-1",groupLabel:"Content Engine: Dogfood the Larry Playbook",startedAt:s(3),updatedAt:t(7),lastEventAt:t(7),lastEventSummary:"Blocked: legal sign-off timeout on compliance language.",blockers:["Legal sign-off overdue for compliance language","Persona claim needs policy exception approval"],phase:"blocked",state:"error",blockerReason:"Legal reviewer did not respond before SLA timeout.",eta:"Waiting on decision",checkpointCount:4,runtimeClient:"codex",runtimeLabel:"Codex Review Worker",runtimeProvider:"codex",instanceId:"instance-codex-07",lastHeartbeatAt:t(7),blockerDiagnostics:{reason:"Legal review is pending and blocked downstream publication.",source:"orgx",errorCode:"LEGAL_REVIEW_TIMEOUT",errorCategory:"dependency",retryable:!1,suggestedActions:["Escalate to legal duty reviewer","Approve fallback compliant copy variant"],eventId:"evt-legal-401",eventType:"question_timeout_started",eventTimestamp:t(9),context:{initiativeId:"init-1",workstreamId:"ws-content-legal",workstreamTitle:"Persona QA and legal sweep",taskIds:["task-legal-2"],milestoneIds:["mile-content-2"],sliceRunId:"slice-run-104",parallelMode:"serial",logPath:"/tmp/orgx/legal-review.log",outputPath:"/tmp/orgx/legal-review-summary.md"}}},{id:"run-103",parentId:"run-100",runId:"run-103",title:"Distribution schedule and channel mapping",agentId:"pace",agentName:"Pace",status:"review",progress:82,initiativeId:"init-1",workstreamId:"ws-content-ops",groupId:"init-1",groupLabel:"Content Engine: Dogfood the Larry Playbook",startedAt:s(2),updatedAt:t(20),lastEventAt:t(20),lastEventSummary:"Schedule proposal complete; waiting for owner confirmation.",blockers:["Owner confirmation pending"],phase:"review",state:"idle",eta:"11m after approval",checkpointCount:7,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Planner",runtimeProvider:"openclaw",instanceId:"instance-openclaw-04",lastHeartbeatAt:t(18)},{id:"run-200",parentId:null,runId:"run-200",title:"Live View UX Redesign — Orchestrator",agentId:"orgx",agentName:"OrgX",status:"running",progress:39,initiativeId:"init-2",workstreamId:null,groupId:"init-2",groupLabel:"Live View UX Redesign — The Conductor's Display",startedAt:s(5),updatedAt:t(2),lastEventAt:t(2),lastEventSummary:"Dispatching layout and timeline polish slices.",blockers:[],phase:"execution",state:"running",eta:"48m",checkpointCount:12,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Orchestrator",runtimeProvider:"openclaw",instanceId:"instance-openclaw-01",lastHeartbeatAt:t(1)},{id:"run-201",parentId:"run-200",runId:"run-201",title:"Activity feed readability pass",agentId:"dana",agentName:"Dana",status:"in_progress",progress:48,initiativeId:"init-2",workstreamId:"ws-ux-activity",groupId:"init-2",groupLabel:"Live View UX Redesign — The Conductor's Display",startedAt:s(2),updatedAt:t(6),lastEventAt:t(6),lastEventSummary:"Adjusted semantic grouping and status labels in timeline rows.",blockers:[],phase:"execution",state:"running",eta:"22m",checkpointCount:5,runtimeClient:"codex",runtimeLabel:"Codex UI Worker",runtimeProvider:"codex",instanceId:"instance-codex-02",lastHeartbeatAt:t(2)},{id:"run-202",parentId:"run-200",runId:"run-202",title:"Developer-mode feature gating",agentId:"holt",agentName:"Holt",status:"running",progress:73,initiativeId:"init-2",workstreamId:"ws-ux-devmode",groupId:"init-2",groupLabel:"Live View UX Redesign — The Conductor's Display",startedAt:s(3),updatedAt:t(3),lastEventAt:t(3),lastEventSummary:"Gated chat affordances and context cards behind developer mode.",blockers:[],phase:"execution",state:"running",eta:"9m",checkpointCount:9,runtimeClient:"codex",runtimeLabel:"Codex UI Worker",runtimeProvider:"codex",instanceId:"instance-codex-03",lastHeartbeatAt:t(1)},{id:"run-203",parentId:"run-200",runId:"run-203",title:"Grouped section collapse spacing regression",agentId:"kimi",agentName:"Kimi",status:"blocked",progress:46,initiativeId:"init-2",workstreamId:"ws-ux-collapse",groupId:"init-2",groupLabel:"Live View UX Redesign — The Conductor's Display",startedAt:s(2),updatedAt:t(2),lastEventAt:t(2),lastEventSummary:"Needs design decision on collapsed spacing token in grouped sections.",blockers:["Spacing token decision required for collapsed groups","Visual QA needs final approved baseline screenshot"],phase:"blocked",state:"error",blockerReason:"Design token ambiguity for collapsed section gap.",eta:"Waiting on decision",checkpointCount:5,runtimeClient:"codex",runtimeLabel:"Codex UI Worker",runtimeProvider:"codex",instanceId:"instance-codex-05",lastHeartbeatAt:t(2),blockerDiagnostics:{reason:"Layout engine requires explicit collapsed gap token before patching.",source:"agent",errorCode:"COLLAPSE_GAP_TOKEN_MISSING",errorCategory:"configuration",retryable:!0,suggestedActions:["Approve 8px collapsed gap token","Approve 0px gap for fully collapsed sections"],eventId:"evt-ux-778",eventType:"decision_needed",eventTimestamp:t(2),context:{initiativeId:"init-2",workstreamId:"ws-ux-collapse",workstreamTitle:"Grouped section collapse spacing regression",taskIds:["task-ux-41"],milestoneIds:["mile-ux-12"],sliceRunId:"slice-run-101",parallelMode:"parallel",logPath:"/tmp/orgx/collapse-gap.log",outputPath:"/tmp/orgx/collapse-gap-plan.md"}}},{id:"run-300",parentId:null,runId:"run-300",title:"Directory Submissions & External References",agentId:"ops",agentName:"Ops",status:"running",progress:36,initiativeId:"init-3",workstreamId:null,groupId:"init-3",groupLabel:"Directory Submissions & External References",startedAt:s(3),updatedAt:t(5),lastEventAt:t(5),lastEventSummary:"Multi-lane pipeline active: import retries, QA verification, and outreach copy drafting.",blockers:["One vendor lane still rate-limited; recovery in progress"],phase:"execution",state:"running",blockerReason:"Partial dependency degradation on one vendor lane.",eta:"42m",checkpointCount:8,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Intake",runtimeProvider:"openclaw",instanceId:"instance-openclaw-08",lastHeartbeatAt:t(2)},{id:"run-301",parentId:"run-300",runId:"run-301",title:"Enrichment import pipeline",agentId:"pace",agentName:"Pace",status:"running",progress:27,initiativeId:"init-3",workstreamId:"ws-directory-import",groupId:"init-3",groupLabel:"Directory Submissions & External References",startedAt:s(1),updatedAt:t(3),lastEventAt:t(3),lastEventSummary:"Import retries active after vendor sandbox rate limits.",blockers:["Clearbit sandbox rate-limited; retry window opens in 6 minutes"],phase:"execution",state:"running",eta:"31m",checkpointCount:4,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Pipeline Worker",runtimeProvider:"openclaw",instanceId:"instance-openclaw-09",lastHeartbeatAt:t(1)},{id:"run-302",parentId:"run-300",runId:"run-302",title:"Reference verification QA lane",agentId:"kimi",agentName:"Kimi",status:"running",progress:58,initiativeId:"init-3",workstreamId:"ws-directory-qa",groupId:"init-3",groupLabel:"Directory Submissions & External References",startedAt:s(2),updatedAt:t(5),lastEventAt:t(5),lastEventSummary:"Citation verification batch completed; QA memo and mismatch ledger attached.",blockers:[],phase:"execution",state:"running",eta:"18m",checkpointCount:5,runtimeClient:"codex",runtimeLabel:"Codex QA Worker",runtimeProvider:"codex",instanceId:"instance-codex-09",lastHeartbeatAt:t(1)},{id:"run-303",parentId:"run-300",runId:"run-303",title:"External partner outreach copy",agentId:"mark",agentName:"Mark",status:"running",progress:41,initiativeId:"init-3",workstreamId:"ws-directory-outreach",groupId:"init-3",groupLabel:"Directory Submissions & External References",startedAt:s(2),updatedAt:t(8),lastEventAt:t(8),lastEventSummary:"Outreach sequence draft in progress with two channel variants.",blockers:[],phase:"execution",state:"running",eta:"24m",checkpointCount:4,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Content Worker",runtimeProvider:"openclaw",instanceId:"instance-openclaw-13",lastHeartbeatAt:t(2)},{id:"run-400",parentId:null,runId:"run-400",title:"Incident Replay & Reliability",agentId:"ops",agentName:"Ops",status:"blocked",progress:22,initiativeId:"init-5",workstreamId:null,groupId:"init-5",groupLabel:"Incident Replay & Reliability",startedAt:s(6),updatedAt:t(25),lastEventAt:t(25),lastEventSummary:"Replay reconstruction failed due to missing archived logs.",blockers:["Archive bucket retention policy removed required replay logs","Manual restore approval from platform owner required"],phase:"blocked",state:"error",blockerReason:"Missing archived logs prevent deterministic replay.",eta:"Waiting on restore decision",checkpointCount:11,runtimeClient:"api",runtimeLabel:"OrgX Replay Service",runtimeProvider:"orgx",instanceId:"instance-orgx-01",lastHeartbeatAt:t(25)},{id:"run-500",parentId:null,runId:"run-500",title:"Revenue Expansion Q2 closeout",agentId:"mark",agentName:"Mark",status:"completed",progress:100,initiativeId:"init-4",workstreamId:"ws-revenue-closeout",groupId:"init-4",groupLabel:"Revenue Expansion Q2",startedAt:s(8),updatedAt:t(40),lastEventAt:t(40),lastEventSummary:"Closeout report approved and milestone marked complete.",blockers:[],phase:"completed",state:"idle",checkpointCount:9,runtimeClient:"openclaw",runtimeLabel:"OpenClaw Revenue Worker",runtimeProvider:"openclaw",instanceId:"instance-openclaw-12",lastHeartbeatAt:t(40)}]},activity:[{id:"activity-200",type:"decision_requested",title:"Decision requested: collapsed section spacing",description:"Choose collapsed group spacing behavior to ship the gap regression fix.",agentId:"kimi",agentName:"Kimi",requesterAgentId:"kimi",requesterAgentName:"Kimi",executorAgentId:"kimi",executorAgentName:"Kimi",runId:"run-203",initiativeId:"init-2",timestamp:t(2),decisionRequired:!0,metadata:{event:"decision_needed",event_name:"question_asked",source:"agent",parsed_status:"blocked",decision_title:"Collapse spacing token",decisions_needed:[{title:"Use 8px collapsed gap",id:"decision-100"},{title:"Use 0px collapsed gap",id:"decision-100b"}],blocker:{description:"Layout cannot merge without explicit spacing token.",waiting_on:"you"}}},{id:"activity-201",type:"blocker_created",title:"Blocker created: grouped section gap",description:"Spacing token conflict detected while collapsing grouped sections.",agentId:"kimi",agentName:"Kimi",requesterAgentId:"kimi",requesterAgentName:"Kimi",executorAgentId:"kimi",executorAgentName:"Kimi",runId:"run-203",initiativeId:"init-2",timestamp:t(3),metadata:{event:"autopilot_slice_result",event_name:"autopilot_slice_result",source:"agent",parsed_status:"blocked",blocked_reason:"Collapsed section gap token unresolved.",blocker:{description:"Collapsed group spacing token is undefined across variants.",waiting_on:"design_owner"},decisions_needed:[{title:"Approve spacing token",id:"decision-100"}]}},{id:"activity-202",type:"artifact_created",title:"Artifact created: developer-mode gating patch",description:"Prepared patch and screenshot evidence for developer-mode-only controls.",agentId:"holt",agentName:"Holt",requesterAgentId:"holt",requesterAgentName:"Holt",executorAgentId:"holt",executorAgentName:"Holt",runId:"run-202",initiativeId:"init-2",timestamp:t(4),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"agent",parsed_status:"completed",outcomes:{pr_url:"https://github.com/useorgx/orgx-openclaw-plugin/pull/312",pr_number:312,commit_sha:"1f4b2c9",commit_url:"https://github.com/useorgx/orgx-openclaw-plugin/commit/1f4b2c9",tests:{passed:31,failed:0,skipped:4}},task_updates:[{title:"Gate chat icon under developer mode",status:"completed"},{title:"Gate mic icon under developer mode",status:"completed"},{title:"Gate context card under developer mode",status:"completed"}]}},{id:"activity-203",type:"delegation",title:"Dispatch: readability pass",description:"Orchestrator dispatched readability polish while feature gating continues.",agentId:"orgx",agentName:"OrgX",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-200",initiativeId:"init-2",timestamp:t(6),metadata:{event:"autopilot_slice_dispatched",event_name:"autopilot_slice_dispatched",source:"orchestrator",parsed_status:"running",run_id:"slice-run-106",dispatch_selection_reason:"Queue selected highest confidence unblocked UI slice"}},{id:"activity-204",type:"run_started",title:"Slice started: enrichment import retry",description:"Started retry batch after rate limit window reopened.",agentId:"pace",agentName:"Pace",requesterAgentId:"ops",requesterAgentName:"Ops",executorAgentId:"pace",executorAgentName:"Pace",runId:"run-301",initiativeId:"init-3",timestamp:t(8),metadata:{event:"autopilot_slice_started",event_name:"autopilot_slice_started",source:"agent",parsed_status:"running",run_id:"slice-run-102"}},{id:"activity-225",type:"artifact_created",title:"Artifact created: reference QA packet",description:"Published mismatch ledger and verification memo for the latest reference batch.",agentId:"kimi",agentName:"Kimi",requesterAgentId:"ops",requesterAgentName:"Ops",executorAgentId:"kimi",executorAgentName:"Kimi",runId:"run-302",initiativeId:"init-3",timestamp:t(5),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"agent",parsed_status:"completed",outcomes:{artifact_count:2,tests:{passed:14,failed:0,skipped:1},task_updates:2},task_updates:[{title:"Run citation verification across 120 references",status:"completed"},{title:"Publish mismatch ledger for reviewer approval",status:"completed"}],artifacts:[{id:"artifact-dir-qa-1",type:"report",title:"Reference verification memo",url:null},{id:"artifact-dir-qa-2",type:"spreadsheet",title:"Citation mismatch ledger",url:null}]}},{id:"activity-226",type:"delegation",title:"Dispatch: partner outreach copy lane",description:"Orchestrator launched a copy lane to draft partner outreach and handoff templates.",agentId:"orgx",agentName:"OrgX",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-300",initiativeId:"init-3",timestamp:t(9),metadata:{event:"autopilot_slice_dispatched",event_name:"autopilot_slice_dispatched",source:"orchestrator",parsed_status:"running",run_id:"slice-run-112",dispatch_selection_reason:"Reference verification can proceed in parallel with outreach preparation."}},{id:"activity-227",type:"run_started",title:"Slice started: outreach sequence draft",description:"Mark began drafting outreach sequence copy for external partners.",agentId:"mark",agentName:"Mark",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-303",initiativeId:"init-3",timestamp:t(8),metadata:{event:"autopilot_slice_started",event_name:"autopilot_slice_started",source:"agent",parsed_status:"running",run_id:"slice-run-112"}},{id:"activity-228",type:"artifact_created",title:"Artifact created: outreach copy sequence",description:"Drafted email + LinkedIn outreach variants and handoff checklist.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-303",initiativeId:"init-3",timestamp:t(6),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"agent",parsed_status:"completed",outcomes:{artifact_count:1,tests:{passed:8,failed:0,skipped:0}},task_updates:[{title:"Produce 2 outreach channel variants",status:"completed"},{title:"Attach partner-ready handoff checklist",status:"completed"}],artifacts:[{id:"artifact-dir-outreach-1",type:"brief",title:"Partner outreach sequence v1",url:null}]}},{id:"activity-205",type:"decision_requested",title:"Decision requested: legal-safe copy variant",description:"Select fallback copy variant to unblock compliance gate.",agentId:"holt",agentName:"Holt",requesterAgentId:"holt",requesterAgentName:"Holt",executorAgentId:"holt",executorAgentName:"Holt",runId:"run-102",initiativeId:"init-1",timestamp:t(10),decisionRequired:!0,metadata:{event:"question_asked",event_name:"question_asked",source:"agent",parsed_status:"blocked",decision_title:"Legal-safe phrasing for claim section",decisions_needed:[{title:"Choose fallback compliant claim",id:"decision-101"}],blocker:{description:"Cannot publish until legal-safe variant is selected.",waiting_on:"you"}}},{id:"activity-206",type:"blocker_created",title:"Blocker created: vendor rate limit",description:"Clearbit sandbox returned 429 and paused enrichment imports.",agentId:"pace",agentName:"Pace",requesterAgentId:"pace",requesterAgentName:"Pace",executorAgentId:"pace",executorAgentName:"Pace",runId:"run-301",initiativeId:"init-3",timestamp:t(12),metadata:{event:"autopilot_slice_timeout",event_name:"autopilot_slice_timeout",source:"agent",parsed_status:"blocked",blocked_reason:"Rate limit hit during vendor enrichment fetch.",blocker:{description:"Vendor sandbox has 60 req/hour cap.",waiting_on:"vendor_api"}}},{id:"activity-207",type:"handoff_requested",title:"Handoff requested: editorial review",description:"Content draft is ready for editor review before publish scheduling.",agentId:"kimi",agentName:"Kimi",requesterAgentId:"kimi",requesterAgentName:"Kimi",executorAgentId:"main",executorAgentName:"You",runId:"run-101",initiativeId:"init-1",timestamp:t(14),metadata:{event:"autopilot_slice_handoff",event_name:"autopilot_slice_handoff",source:"agent",parsed_status:"review"}},{id:"activity-208",type:"decision_resolved",title:"Decision resolved: hide non-dev controls",description:"Approved developer-mode gating for non-production controls.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-202",initiativeId:"init-2",timestamp:t(18),metadata:{event:"decision_resolved",event_name:"decision_resolved",source:"user",parsed_status:"completed",decision_id:"decision-108",selected_option_id:"decision-108-approve"}},{id:"activity-209",type:"run_completed",title:"Run completed: distribution schedule draft",description:"Channel mapping draft completed and attached for final owner sign-off.",agentId:"pace",agentName:"Pace",requesterAgentId:"holt",requesterAgentName:"Holt",executorAgentId:"pace",executorAgentName:"Pace",runId:"run-103",initiativeId:"init-1",timestamp:t(21),metadata:{event:"autopilot_slice_result",event_name:"autopilot_slice_result",source:"agent",parsed_status:"completed",run_id:"slice-run-105",outcomes:{tests:{passed:11,failed:0,skipped:1},artifact_count:1},task_updates:[{title:"Distribution schedule build",status:"completed"}]}},{id:"activity-210",type:"run_failed",title:"Run failed: incident replay reconstruction",description:"Replay service failed due to missing archived log segment.",agentId:"ops",agentName:"Ops",requesterAgentId:"ops",requesterAgentName:"Ops",executorAgentId:"ops",executorAgentName:"Ops",runId:"run-400",initiativeId:"init-5",timestamp:t(25),metadata:{event:"workflow_error",event_name:"workflow_error",source:"system",parsed_status:"failed",blocked_reason:"Replay logs missing from archive.",decisions_needed:[{title:"Approve restore from backup snapshot",id:"decision-103"}]}},{id:"activity-211",type:"delegation",title:"Dispatch: legal review branch",description:"Orchestrator dispatched compliance fallback drafting branch.",agentId:"holt",agentName:"Holt",requesterAgentId:"holt",requesterAgentName:"Holt",executorAgentId:"kimi",executorAgentName:"Kimi",runId:"run-100",initiativeId:"init-1",timestamp:t(29),metadata:{event:"orchestrator_dispatch",event_name:"orchestrator_dispatch",source:"orchestrator",parsed_status:"running"}},{id:"activity-212",type:"milestone_completed",title:"Milestone completed: developer-mode controls",description:"Mission Control and Activity controls are now hidden for non-developer mode.",agentId:"dana",agentName:"Dana",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-202",initiativeId:"init-2",timestamp:t(34),metadata:{event:"milestone_completed",event_name:"milestone_completed",source:"agent",parsed_status:"completed"}},{id:"activity-213",type:"run_started",title:"Run started: content orchestrator",description:"Autopilot started for Larry playbook initiative.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-100",initiativeId:"init-1",timestamp:t(72),metadata:{event:"auto_continue_started",event_name:"auto_continue_started",source:"user",parsed_status:"running"}},{id:"activity-214",type:"blocker_created",title:"Blocker created: vendor credential handshake",description:"Directory submission pipeline is waiting for external vendor credentials.",agentId:"ops",agentName:"Ops",requesterAgentId:"ops",requesterAgentName:"Ops",executorAgentId:"ops",executorAgentName:"Ops",runId:"run-300",initiativeId:"init-3",timestamp:t(54),metadata:{event:"spawn_guard_blocked",event_name:"spawn_guard_blocked",source:"system",parsed_status:"blocked",blocked_reason:"Credentials not provisioned in secret manager."}},{id:"activity-230",type:"milestone_completed",title:"Milestone completed: readability foundation",description:"Baseline readability hierarchy shipped and adopted in activity and mission panels.",agentId:"dana",agentName:"Dana",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-201",initiativeId:"init-2",timestamp:i(2),metadata:{event:"milestone_completed",event_name:"milestone_completed",source:"agent",parsed_status:"completed",outcomes:{artifact_count:1,tests:{passed:22,failed:0,skipped:3}},artifacts:[{id:"artifact-ux-activity-legacy",type:"design",title:"Readability hierarchy baseline",url:null}]}},{id:"activity-231",type:"artifact_created",title:"Artifact created: executive notes and next-up alignment",description:"You captured final guidance so completed work maps cleanly to what starts next.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-500",initiativeId:"init-4",timestamp:i(1),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"user",parsed_status:"completed",outcomes:{artifact_count:1,task_updates:1},task_updates:[{title:"Connect closeout outputs to next-up backlog",status:"completed"}],artifacts:[{id:"artifact-revenue-7",type:"brief",title:"Executive closeout notes",url:null}]}},{id:"activity-219",type:"run_started",title:"Run started: revenue closeout",description:"Revenue closeout automation launched for Q2 finalize workflow.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-500",initiativeId:"init-4",timestamp:s(8),metadata:{event:"session_start",event_name:"session_start",source:"user",parsed_status:"running"}},{id:"activity-220",type:"delegation",title:"Dispatch: finance reconciliation slice",description:"Orchestrator delegated reconciliation and closeout reporting to Mark.",agentId:"orgx",agentName:"OrgX",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-500",initiativeId:"init-4",timestamp:s(7),metadata:{event:"orchestrator_dispatch",event_name:"orchestrator_dispatch",source:"orchestrator",parsed_status:"running",run_id:"slice-run-110"}},{id:"activity-221",type:"artifact_created",title:"Artifact created: closeout package",description:"Published closeout report, variance sheet, and stakeholder brief.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-500",initiativeId:"init-4",timestamp:s(5),metadata:{event:"artifact_registered",event_name:"artifact_registered",source:"agent",parsed_status:"completed",outcomes:{artifact_count:3,tests:{passed:6,failed:0,skipped:0}}}},{id:"activity-222",type:"decision_resolved",title:"Decision resolved: approve final variance handling",description:"Approved finance variance interpretation and finalized closeout notes.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-500",initiativeId:"init-4",timestamp:s(4),metadata:{event:"decision_resolved",event_name:"decision_resolved",source:"user",parsed_status:"completed",decision_id:"decision-revenue-4",selected_option_id:"decision-revenue-4-approve"}},{id:"activity-223",type:"handoff_fulfilled",title:"Handoff fulfilled: executive sign-off",description:"Executive review completed and closeout approved for publication.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"main",executorAgentName:"You",runId:"run-500",initiativeId:"init-4",timestamp:t(95),metadata:{event:"autopilot_slice_handoff",event_name:"autopilot_slice_handoff",source:"agent",parsed_status:"review"}},{id:"activity-224",type:"milestone_completed",title:"Milestone completed: Q2 closeout pack",description:"All closeout deliverables finalized and attached to the initiative.",agentId:"mark",agentName:"Mark",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-500",initiativeId:"init-4",timestamp:t(42),metadata:{event:"milestone_completed",event_name:"milestone_completed",source:"agent",parsed_status:"completed"}},{id:"activity-218",type:"run_completed",title:"Run completed: revenue closeout",description:"Final Q2 closeout report submitted and approved.",agentId:"mark",agentName:"Mark",requesterAgentId:"orgx",requesterAgentName:"OrgX",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-500",initiativeId:"init-4",timestamp:t(40),metadata:{event:"run_completed",event_name:"run_completed",source:"agent",parsed_status:"completed"}},{id:"activity-215",type:"run_started",title:"Run started: UX redesign orchestrator",description:"Autopilot started for live view redesign initiative.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-200",initiativeId:"init-2",timestamp:t(89),metadata:{event:"auto_continue_started",event_name:"auto_continue_started",source:"user",parsed_status:"running"}},{id:"activity-216",type:"run_started",title:"Run started: directory intake",description:"Directory submissions initiative entered queued intake phase.",agentId:"main",agentName:"You",requesterAgentId:"main",requesterAgentName:"You",executorAgentId:"main",executorAgentName:"You",runId:"run-300",initiativeId:"init-3",timestamp:t(110),metadata:{event:"session_start",event_name:"session_start",source:"user",parsed_status:"queued"}},{id:"activity-217",type:"run_started",title:"Heartbeat",description:"System health check across active runtime instances.",agentId:"system",agentName:"System",requesterAgentId:"system",requesterAgentName:"System",executorAgentId:"system",executorAgentName:"System",runId:"run-200",initiativeId:"init-2",timestamp:t(1),metadata:{event:"heartbeat",event_name:"heartbeat",source:"system"}}],handoffs:[{id:"handoff-200",title:"Editorial approval for long-form section",status:"created",priority:"high",summary:"Need human editorial approval before publishing section 3 and section 4.",currentActorType:"user",currentActorId:"you",createdAt:t(14),updatedAt:t(6),events:[{id:"handoff-event-200-1",handoffId:"handoff-200",eventType:"created",actorType:"agent",actorId:"kimi",payload:{summary:"Draft content is ready for editorial pass."},createdAt:t(14)},{id:"handoff-event-200-2",handoffId:"handoff-200",eventType:"claimed",actorType:"user",actorId:"you",payload:{summary:"Reviewing section drafts now."},createdAt:t(6)}]},{id:"handoff-201",title:"UX patch verification run",status:"claimed",priority:"medium",summary:"Patch is implemented and needs targeted visual verification before merge.",currentActorType:"agent",currentActorId:"dana",createdAt:t(37),updatedAt:t(18),events:[{id:"handoff-event-201-1",handoffId:"handoff-201",eventType:"created",actorType:"agent",actorId:"dana",payload:{summary:"Patch created for developer-mode visibility controls."},createdAt:t(37)},{id:"handoff-event-201-2",handoffId:"handoff-201",eventType:"claimed",actorType:"agent",actorId:"holt",payload:{summary:"Taking ownership of QA capture and merge readiness checks."},createdAt:t(18)}]},{id:"handoff-202",title:"Incident replay restore request",status:"created",priority:"high",summary:"Platform owner approval is required to restore archived logs from backup snapshot.",currentActorType:"user",currentActorId:"you",createdAt:t(29),updatedAt:t(25),events:[{id:"handoff-event-202-1",handoffId:"handoff-202",eventType:"created",actorType:"system",actorId:"orgx",payload:{summary:"Replay pipeline blocked by retention policy loss."},createdAt:t(29)}]},{id:"handoff-203",title:"Revenue closeout executive review",status:"fulfilled",priority:"medium",summary:"Executive sign-off complete and closeout artifacts accepted.",currentActorType:"agent",currentActorId:"mark",createdAt:s(5),updatedAt:t(95),events:[{id:"handoff-event-203-1",handoffId:"handoff-203",eventType:"created",actorType:"agent",actorId:"mark",payload:{summary:"Requested executive review of closeout package."},createdAt:s(5)},{id:"handoff-event-203-2",handoffId:"handoff-203",eventType:"claimed",actorType:"user",actorId:"you",payload:{summary:"Executive review in progress."},createdAt:s(4)},{id:"handoff-event-203-3",handoffId:"handoff-203",eventType:"fulfilled",actorType:"agent",actorId:"mark",payload:{summary:"Sign-off captured and initiative unblocked."},createdAt:t(95)}]}],decisions:[{id:"decision-100",title:"Choose collapsed section spacing behavior",context:"Grouped section collapse bug fix needs an explicit spacing token before merge.",status:"pending",priority:"high",decisionType:"ui_behavior",agentName:"Kimi",agentId:"kimi",initiativeId:"init-2",workstreamId:"ws-ux-collapse",dueAt:t(-30),requestedAt:t(2),updatedAt:t(2),waitingMinutes:2,sourceSystem:"orgx_live",recommendedAction:"Approve 8px spacing token for collapsed grouped sections.",occurrenceCount:1,sourceRunId:"run-203",metadata:{severity:"high",blockedWorkstreams:1,impactedScreens:["Activity","Mission Control"]},options:[{id:"decision-100-approve-8",label:"Use 8px collapsed spacing",description:"Keeps visual grouping while removing layout hole.",impliedStatus:"approved",actionType:"approve",requiresNote:!1},{id:"decision-100-approve-0",label:"Use 0px collapsed spacing",description:"Removes all gaps in collapsed state.",impliedStatus:"approved",actionType:"confirm_scope",requiresNote:!0},{id:"decision-100-defer",label:"Defer and park fix",description:"Move this slice to queue and continue with others.",impliedStatus:"cancelled",actionType:"defer",requiresNote:!0}]},{id:"decision-101",title:"Select legal-safe copy variant",context:"Legal review timeout blocked publication of Larry playbook draft.",status:"pending",priority:"critical",decisionType:"compliance",agentName:"Holt",agentId:"holt",initiativeId:"init-1",workstreamId:"ws-content-legal",dueAt:t(-20),requestedAt:t(10),updatedAt:t(7),waitingMinutes:10,sourceSystem:"orgx_live",recommendedAction:"Approve fallback variant B that removes unsupported claims.",occurrenceCount:2,sourceRunId:"run-102",metadata:{severity:"critical",blockedWorkstreams:2,downstreamBlockedCount:5},options:[{id:"decision-101-variant-b",label:"Approve variant B",description:"Compliant copy with conservative claims.",impliedStatus:"approved",actionType:"approve",requiresNote:!1},{id:"decision-101-request-legal",label:"Request legal context",description:"Ask legal reviewer for targeted edits.",impliedStatus:null,actionType:"request_info",requiresNote:!0},{id:"decision-101-reject",label:"Reject current options",description:"Restart copy drafting with stricter constraints.",impliedStatus:"declined",actionType:"reject",requiresNote:!0}]},{id:"decision-102",title:"Unblock vendor sandbox rate limits",context:"Directory enrichment pipeline is repeatedly throttled by vendor sandbox limits.",status:"pending",priority:"medium",decisionType:"ops_routing",agentName:"Pace",agentId:"pace",initiativeId:"init-3",workstreamId:"ws-directory-import",dueAt:t(-45),requestedAt:t(12),updatedAt:t(3),waitingMinutes:12,sourceSystem:"orgx_live",recommendedAction:"Promote queue priority for paid-tier vendor credentials.",occurrenceCount:3,sourceRunId:"run-301",metadata:{severity:"medium",blockedWorkstreams:1},options:[{id:"decision-102-queue-top",label:"Queue paid-tier credential setup",description:"Move credential provisioning to top of ops queue.",impliedStatus:"approved",actionType:"queue_top",requiresNote:!1},{id:"decision-102-retry",label:"Retry in 10 minutes",description:"Continue on sandbox and retry later.",impliedStatus:null,actionType:"retry",requiresNote:!1}]},{id:"decision-103",title:"Approve replay log restoration",context:"Incident replay is blocked because archive retention removed required logs.",status:"pending",priority:"critical",decisionType:"incident_recovery",agentName:"Ops",agentId:"ops",initiativeId:"init-5",workstreamId:"ws-reliability-replay",dueAt:t(-15),requestedAt:t(25),updatedAt:t(25),waitingMinutes:25,sourceSystem:"orgx_live",recommendedAction:"Approve restore from backup snapshot 2026-03-04T20:00Z.",occurrenceCount:1,sourceRunId:"run-400",metadata:{severity:"critical",blockedWorkstreams:3,downstreamBlockedCount:7},options:[{id:"decision-103-restore",label:"Restore snapshot",description:"Restore archived logs and resume replay.",impliedStatus:"approved",actionType:"approve",requiresNote:!1},{id:"decision-103-escalate",label:"Escalate to platform owner",description:"Escalate if restore permissions are unavailable.",impliedStatus:null,actionType:"escalate",requiresNote:!0}]},{id:"decision-104",title:"Confirm external reference verification policy",context:"Need policy confirmation for linking third-party directory references in generated content.",status:"pending",priority:"low",decisionType:"policy",agentName:"Ops",agentId:"ops",initiativeId:"init-3",workstreamId:"ws-directory-policy",dueAt:s(-6),requestedAt:t(41),updatedAt:t(19),waitingMinutes:41,sourceSystem:"orgx_live",recommendedAction:"Use strict verification and citation for all imported references.",occurrenceCount:1,sourceRunId:"run-300",metadata:{severity:"low",blockedWorkstreams:0},options:[{id:"decision-104-confirm",label:"Require strict verification",description:"Only include references with successful source validation.",impliedStatus:"approved",actionType:"confirm_scope",requiresNote:!1},{id:"decision-104-defer",label:"Defer to later milestone",description:"Proceed with placeholders and finalize references later.",impliedStatus:"cancelled",actionType:"defer",requiresNote:!0}]}],sliceRuns:[{id:"slice-run-100",sliceRunId:"slice-run-100",runId:"run-202",initiativeId:"init-2",workstreamId:"ws-ux-devmode",workstreamTitle:"Developer-mode feature gating",taskIds:["task-ux-31","task-ux-32","task-ux-33"],milestoneIds:[],status:"running",statusExplainer:"Patch implementation is running and waiting for final QA capture.",primaryAction:"review_output",hasArtifact:!0,artifactCount:2,artifacts:[{id:"artifact-ux-devmode-1",type:"diff_pack",title:"Developer mode gating patch",url:null,createdAt:t(4)},{id:"artifact-ux-devmode-2",type:"screenshot_set",title:"Visibility verification screenshots",url:null,createdAt:t(3)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"active",startedAt:s(3),updatedAt:t(1),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(1),lastEventSummary:"Final QA pending before merge request.",correlationId:"run-202",confidence:"high",scope:"workstream",scopeProgress:{totalTasks:5,completedTasks:4}},{id:"slice-run-101",sliceRunId:"slice-run-101",runId:"run-203",initiativeId:"init-2",workstreamId:"ws-ux-collapse",workstreamTitle:"Grouped section collapse spacing regression",taskIds:["task-ux-41"],milestoneIds:[],status:"awaiting_input",statusExplainer:"Blocked pending spacing-token decision.",primaryAction:"resolve_decision",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"slice-run-101-opt-approve-8",label:"Approve 8px spacing",description:"Proceed with 8px collapsed group spacing.",impliedStatus:"approved",requiresNote:!1},{id:"slice-run-101-opt-approve-0",label:"Approve 0px spacing",description:"Proceed with 0px collapsed group spacing.",impliedStatus:"approved",requiresNote:!0}],sourceClient:"codex",runtimeState:"idle",startedAt:s(2),updatedAt:t(2),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(2),lastEventSummary:"Waiting for a decision before patch can finalize.",correlationId:"run-203",confidence:"high",scope:"task",scopeProgress:{totalTasks:2,completedTasks:1}},{id:"slice-run-102",sliceRunId:"slice-run-102",runId:"run-301",initiativeId:"init-3",workstreamId:"ws-directory-import",workstreamTitle:"Enrichment import pipeline",taskIds:["task-dir-12"],milestoneIds:[],status:"failed",statusExplainer:"Failed due to vendor rate limiting; retry action available.",primaryAction:"retry_slice",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:0,decisionOptions:[{id:"slice-run-102-opt-retry",label:"Retry after cooldown",description:"Retry once vendor cooldown period ends.",impliedStatus:null,requiresNote:!1}],sourceClient:"openclaw",runtimeState:"error",startedAt:s(1),updatedAt:t(3),completedAt:null,failedAt:t(12),archivedAt:null,lastEventAt:t(3),lastEventSummary:"Retry cycle started; previous run failed from API 429.",correlationId:"run-301",confidence:"medium",scope:"task",scopeProgress:{totalTasks:3,completedTasks:1}},{id:"slice-run-103",sliceRunId:"slice-run-103",runId:"run-101",initiativeId:"init-1",workstreamId:"ws-content-1",workstreamTitle:"Long-form article generation",taskIds:["task-content-12","task-content-13"],milestoneIds:["mile-content-2"],status:"needs_review",statusExplainer:"Draft complete; waiting for editorial review.",primaryAction:"review_output",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-content-21",type:"document",title:"Larry playbook draft v3",url:null,createdAt:t(14)}],decisionCount:1,blockingDecisionCount:0,decisionOptions:[{id:"slice-run-103-opt-open",label:"Open draft",description:"Inspect draft and approve editorial handoff.",impliedStatus:null,requiresNote:!1}],sourceClient:"openclaw",runtimeState:"idle",startedAt:s(2),updatedAt:t(14),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(14),lastEventSummary:"Ready for editorial sign-off.",correlationId:"run-101",confidence:"high",scope:"task",scopeProgress:{totalTasks:4,completedTasks:3}},{id:"slice-run-104",sliceRunId:"slice-run-104",runId:"run-102",initiativeId:"init-1",workstreamId:"ws-content-legal",workstreamTitle:"Persona QA and legal sweep",taskIds:["task-legal-2"],milestoneIds:["mile-content-2"],status:"awaiting_input",statusExplainer:"Waiting for legal-safe variant decision.",primaryAction:"resolve_decision",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"slice-run-104-opt-variant-b",label:"Approve legal variant B",description:"Proceed using conservative compliant variant.",impliedStatus:"approved",requiresNote:!1},{id:"slice-run-104-opt-request-info",label:"Request legal context",description:"Request legal reviewer notes before proceeding.",impliedStatus:null,requiresNote:!0}],sourceClient:"codex",runtimeState:"idle",startedAt:s(3),updatedAt:t(7),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(7),lastEventSummary:"Awaiting legal-safe variant selection.",correlationId:"run-102",confidence:"high",scope:"task",scopeProgress:{totalTasks:2,completedTasks:1}},{id:"slice-run-105",sliceRunId:"slice-run-105",runId:"run-103",initiativeId:"init-1",workstreamId:"ws-content-ops",workstreamTitle:"Distribution schedule and channel mapping",taskIds:["task-content-ops-7"],milestoneIds:["mile-content-3"],status:"completed",statusExplainer:"Completed with deliverable attached.",primaryAction:"open_artifact",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-content-ops-3",type:"plan",title:"Distribution schedule matrix",url:null,createdAt:t(21)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"stopped",startedAt:s(2),updatedAt:t(21),completedAt:t(21),failedAt:null,archivedAt:null,lastEventAt:t(21),lastEventSummary:"Schedule matrix generated and shared for review.",correlationId:"run-103",confidence:"high",scope:"milestone",scopeProgress:{totalTasks:3,completedTasks:3}},{id:"slice-run-106",sliceRunId:"slice-run-106",runId:"run-201",initiativeId:"init-2",workstreamId:"ws-ux-activity",workstreamTitle:"Activity feed readability pass",taskIds:["task-ux-18","task-ux-19"],milestoneIds:[],status:"running",statusExplainer:"Active polish pass with live preview updates.",primaryAction:"review_output",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"active",startedAt:s(2),updatedAt:t(6),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(6),lastEventSummary:"Refining hierarchy labels and status chips.",correlationId:"run-201",confidence:"medium",scope:"workstream",scopeProgress:{totalTasks:4,completedTasks:2}},{id:"slice-run-107",sliceRunId:"slice-run-107",runId:"run-300",initiativeId:"init-3",workstreamId:"ws-directory-intake",workstreamTitle:"Directory intake coordination",taskIds:["task-dir-1"],milestoneIds:[],status:"queued",statusExplainer:"Queued behind credential provisioning dependency.",primaryAction:"none",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:0,decisionOptions:[{id:"slice-run-107-opt-queue-top",label:"Prioritize credentials",description:"Move credential provisioning to top of queue.",impliedStatus:"approved",requiresNote:!1}],sourceClient:"openclaw",runtimeState:"stale",startedAt:s(2),updatedAt:t(11),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(11),lastEventSummary:"Awaiting secret manager updates.",correlationId:"run-300",confidence:"medium",scope:"workstream",scopeProgress:{totalTasks:2,completedTasks:0}},{id:"slice-run-108",sliceRunId:"slice-run-108",runId:"run-400",initiativeId:"init-5",workstreamId:"ws-reliability-replay",workstreamTitle:"Incident replay reconstruction",taskIds:["task-rel-44"],milestoneIds:["mile-rel-9"],status:"failed",statusExplainer:"Failed due to missing archive logs and blocked restore.",primaryAction:"review_output",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-rel-2",type:"report",title:"Replay failure diagnostics",url:null,createdAt:t(25)}],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"slice-run-108-opt-restore",label:"Approve restore",description:"Restore backup snapshot and retry replay.",impliedStatus:"approved",requiresNote:!1}],sourceClient:"api",runtimeState:"error",startedAt:s(6),updatedAt:t(25),completedAt:null,failedAt:t(25),archivedAt:null,lastEventAt:t(25),lastEventSummary:"Replay failed: archive segment missing.",correlationId:"run-400",confidence:"high",scope:"milestone",scopeProgress:{totalTasks:5,completedTasks:1}},{id:"slice-run-109",sliceRunId:"slice-run-109",runId:"run-100",initiativeId:"init-1",workstreamId:"ws-content-orchestration",workstreamTitle:"Content engine orchestration",taskIds:["task-content-orch-1","task-content-orch-2"],milestoneIds:["mile-content-1"],status:"running",statusExplainer:"Coordinator slice is dispatching and reconciling downstream tasks.",primaryAction:"none",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"active",startedAt:s(4),updatedAt:t(1),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(1),lastEventSummary:"Orchestrator heartbeat healthy and dispatching.",correlationId:"run-100",confidence:"high",scope:"workstream",scopeProgress:{totalTasks:7,completedTasks:4}},{id:"slice-run-110",sliceRunId:"slice-run-110",runId:"run-500",initiativeId:"init-4",workstreamId:"ws-revenue-closeout",workstreamTitle:"Revenue Expansion Q2 closeout",taskIds:["task-revenue-19"],milestoneIds:["mile-revenue-4"],status:"completed",statusExplainer:"Completed and approved by stakeholders.",primaryAction:"open_artifact",hasArtifact:!0,artifactCount:3,artifacts:[{id:"artifact-revenue-4",type:"report",title:"Q2 revenue closeout summary",url:null,createdAt:s(5)},{id:"artifact-revenue-5",type:"spreadsheet",title:"Q2 variance reconciliation sheet",url:null,createdAt:s(5)},{id:"artifact-revenue-6",type:"brief",title:"Executive stakeholder brief",url:null,createdAt:t(40)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"stopped",startedAt:s(8),updatedAt:t(40),completedAt:t(40),failedAt:null,archivedAt:null,lastEventAt:t(40),lastEventSummary:"Closeout summary delivered and approved.",correlationId:"run-500",confidence:"high",scope:"milestone",scopeProgress:{totalTasks:1,completedTasks:1}},{id:"slice-run-111",sliceRunId:"slice-run-111",runId:"run-302",initiativeId:"init-3",workstreamId:"ws-directory-qa",workstreamTitle:"Reference verification QA lane",taskIds:["task-dir-qa-1","task-dir-qa-2"],milestoneIds:["mile-dir-2"],status:"running",statusExplainer:"Verification memo published; reconciling final citation mismatches.",primaryAction:"review_output",hasArtifact:!0,artifactCount:2,artifacts:[{id:"artifact-dir-qa-1",type:"report",title:"Reference verification memo",url:null,createdAt:t(5)},{id:"artifact-dir-qa-2",type:"spreadsheet",title:"Citation mismatch ledger",url:null,createdAt:t(5)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"codex",runtimeState:"active",startedAt:s(2),updatedAt:t(5),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(5),lastEventSummary:"QA packet shipped; final mismatch reconciliation in progress.",correlationId:"run-302",confidence:"high",scope:"task",scopeProgress:{totalTasks:4,completedTasks:2}},{id:"slice-run-112",sliceRunId:"slice-run-112",runId:"run-303",initiativeId:"init-3",workstreamId:"ws-directory-outreach",workstreamTitle:"External partner outreach copy",taskIds:["task-dir-outreach-1","task-dir-outreach-2"],milestoneIds:["mile-dir-3"],status:"running",statusExplainer:"Draft sequence underway with channel variants attached for quick review.",primaryAction:"review_output",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-dir-outreach-1",type:"brief",title:"Partner outreach sequence v1",url:null,createdAt:t(6)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"active",startedAt:s(2),updatedAt:t(6),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(6),lastEventSummary:"Email + LinkedIn variants drafted; QA polish remaining.",correlationId:"run-303",confidence:"medium",scope:"task",scopeProgress:{totalTasks:3,completedTasks:1}}],runtimeInstances:[{id:"instance-codex-01",sourceClient:"codex",displayName:"Codex Dispatch Primary",providerLogo:"codex",state:"active",runId:"run-100",correlationId:"run-100",initiativeId:"init-1",workstreamId:null,taskId:null,agentId:"holt",agentName:"Holt",phase:"execution",progressPct:52,currentTask:"Queue scoring + legal branch dispatch",lastHeartbeatAt:t(1),lastEventAt:t(1),lastMessage:"Stall scan clear; queue advancing.",metadata:{queueDepth:5,source:"dispatch_job"}},{id:"instance-codex-03",sourceClient:"codex",displayName:"Codex UI Worker",providerLogo:"codex",state:"active",runId:"run-202",correlationId:"run-202",initiativeId:"init-2",workstreamId:"ws-ux-devmode",taskId:"task-ux-31",agentId:"holt",agentName:"Holt",phase:"execution",progressPct:73,currentTask:"QA screenshot capture and merge checklist",lastHeartbeatAt:t(1),lastEventAt:t(1),lastMessage:"Awaiting final visual verify before merge.",metadata:{branch:"feat/live-devmode-gates"}},{id:"instance-codex-05",sourceClient:"codex",displayName:"Codex UI Worker",providerLogo:"codex",state:"stale",runId:"run-203",correlationId:"run-203",initiativeId:"init-2",workstreamId:"ws-ux-collapse",taskId:"task-ux-41",agentId:"kimi",agentName:"Kimi",phase:"blocked",progressPct:46,currentTask:"Waiting on spacing-token decision",lastHeartbeatAt:t(2),lastEventAt:t(2),lastMessage:"Decision required before continuing.",metadata:{blockerCode:"COLLAPSE_GAP_TOKEN_MISSING"}},{id:"instance-openclaw-09",sourceClient:"openclaw",displayName:"OpenClaw Pipeline Worker",providerLogo:"openclaw",state:"active",runId:"run-301",correlationId:"run-301",initiativeId:"init-3",workstreamId:"ws-directory-import",taskId:"task-dir-12",agentId:"pace",agentName:"Pace",phase:"execution",progressPct:27,currentTask:"Retrying enrichment pull after cooldown",lastHeartbeatAt:t(1),lastEventAt:t(1),lastMessage:"Vendor cooldown window reopened.",metadata:{retryAttempt:3,vendor:"clearbit-sandbox"}},{id:"instance-codex-09",sourceClient:"codex",displayName:"Codex QA Worker",providerLogo:"codex",state:"active",runId:"run-302",correlationId:"run-302",initiativeId:"init-3",workstreamId:"ws-directory-qa",taskId:"task-dir-qa-2",agentId:"kimi",agentName:"Kimi",phase:"execution",progressPct:58,currentTask:"Reconciling citation mismatches after verification pass",lastHeartbeatAt:t(1),lastEventAt:t(1),lastMessage:"QA memo published; validating final mismatch set.",metadata:{artifactIds:["artifact-dir-qa-1","artifact-dir-qa-2"]}},{id:"instance-openclaw-13",sourceClient:"openclaw",displayName:"OpenClaw Content Worker",providerLogo:"openclaw",state:"active",runId:"run-303",correlationId:"run-303",initiativeId:"init-3",workstreamId:"ws-directory-outreach",taskId:"task-dir-outreach-2",agentId:"mark",agentName:"Mark",phase:"execution",progressPct:41,currentTask:"Drafting partner outreach sequence",lastHeartbeatAt:t(2),lastEventAt:t(2),lastMessage:"Outreach variants drafted; preparing QA polish.",metadata:{artifactId:"artifact-dir-outreach-1"}},{id:"instance-orgx-01",sourceClient:"api",displayName:"OrgX Replay Service",providerLogo:"orgx",state:"error",runId:"run-400",correlationId:"run-400",initiativeId:"init-5",workstreamId:"ws-reliability-replay",taskId:"task-rel-44",agentId:"ops",agentName:"Ops",phase:"blocked",progressPct:22,currentTask:"Waiting for archive restore approval",lastHeartbeatAt:t(25),lastEventAt:t(25),lastMessage:"Replay failed: missing archive segment.",metadata:{incidentId:"inc-4471",severity:"sev2"}},{id:"instance-openclaw-04",sourceClient:"openclaw",displayName:"OpenClaw Planner",providerLogo:"openclaw",state:"stopped",runId:"run-103",correlationId:"run-103",initiativeId:"init-1",workstreamId:"ws-content-ops",taskId:"task-content-ops-7",agentId:"pace",agentName:"Pace",phase:"completed",progressPct:100,currentTask:"Awaiting owner sign-off",lastHeartbeatAt:t(21),lastEventAt:t(21),lastMessage:"Distribution schedule artifact attached.",metadata:{artifactId:"artifact-content-ops-3"}},{id:"instance-openclaw-12",sourceClient:"openclaw",displayName:"OpenClaw Revenue Worker",providerLogo:"openclaw",state:"stopped",runId:"run-500",correlationId:"run-500",initiativeId:"init-4",workstreamId:"ws-revenue-closeout",taskId:"task-revenue-19",agentId:"mark",agentName:"Mark",phase:"completed",progressPct:100,currentTask:"Closeout approved",lastHeartbeatAt:t(40),lastEventAt:t(40),lastMessage:"Q2 closeout summary approved.",metadata:{artifactIds:["artifact-revenue-4","artifact-revenue-5","artifact-revenue-6"],handoffId:"handoff-203"}}],timelineNarrative:[{projectionVersion:2,sliceRunId:"slice-run-100",title:"Developer-mode controls gated",occurredAt:t(1),actorProvenance:{actorType:"agent",actorId:"holt",displayName:"Holt",avatarKey:"holt"},intent:"Hide non-production controls unless developer mode is enabled.",dispatch:"Patch and QA capture were dispatched in parallel.",highlights:["Chat icon gated behind developer mode","Mic icon gated behind developer mode","Context card gated behind developer mode"],outcome:{state:"succeeded_with_artifacts",summary:"Patch complete with QA evidence; pending merge.",artifactCount:2},nextAction:{actionType:"open_pr",label:"Open PR and merge",payloadSchema:{prNumber:"number"},primary:!0},technicalTrace:{eventCount:12,eventIds:["activity-202","activity-208","activity-212"]}},{projectionVersion:2,sliceRunId:"slice-run-101",title:"Collapse-gap fix waiting on spacing decision",occurredAt:t(2),actorProvenance:{actorType:"agent",actorId:"kimi",displayName:"Kimi",avatarKey:"kimi"},intent:"Remove visual gap between grouped sections when collapsed.",dispatch:"Debugged layout tree and isolated spacing-token source.",highlights:["Collapsed layout path identified","Two viable spacing tokens proposed"],outcome:{state:"needs_input",summary:"Implementation blocked until spacing token is approved.",artifactCount:0},nextAction:{actionType:"review_decision",label:"Resolve spacing decision",payloadSchema:{decisionId:"string"},primary:!0},technicalTrace:{eventCount:7,eventIds:["activity-200","activity-201"]}},{projectionVersion:2,sliceRunId:"slice-run-104",title:"Legal sweep blocked by compliance response timeout",occurredAt:t(7),actorProvenance:{actorType:"agent",actorId:"holt",displayName:"Holt",avatarKey:"holt"},intent:"Finalize policy-safe copy before publication.",dispatch:"Escalated to legal and prepared fallback copy variants.",highlights:["Fallback variant B prepared","Compliance queue escalated"],outcome:{state:"needs_input",summary:"Awaiting legal-safe variant decision.",artifactCount:0},nextAction:{actionType:"review_decision",label:"Approve legal-safe variant",payloadSchema:{decisionId:"string"},primary:!0},technicalTrace:{eventCount:9,eventIds:["activity-205"]}},{projectionVersion:2,sliceRunId:"slice-run-102",title:"Enrichment import recovered from rate limiting",occurredAt:t(3),actorProvenance:{actorType:"agent",actorId:"pace",displayName:"Pace",avatarKey:"pace"},intent:"Ingest external references and keep queue moving.",dispatch:"Entered cooldown and resumed once rate window reopened.",highlights:["Vendor cooldown tracked","Retry workflow resumed automatically"],outcome:{state:"failed_actionable",summary:"Earlier failure remains actionable; retry is in progress.",artifactCount:0},nextAction:{actionType:"retry",label:"Retry enrichment slice",payloadSchema:{delayMinutes:"number"},primary:!0},technicalTrace:{eventCount:8,eventIds:["activity-204","activity-206"]}},{projectionVersion:2,sliceRunId:"slice-run-103",title:"Long-form draft prepared for editorial review",occurredAt:t(14),actorProvenance:{actorType:"agent",actorId:"kimi",displayName:"Kimi",avatarKey:"kimi"},intent:"Produce publication-ready long-form article draft.",dispatch:"Generated drafts and handed off for human editorial review.",highlights:["Three sections completed","Editorial handoff created"],outcome:{state:"succeeded_with_artifacts",summary:"Draft artifact created and waiting for review.",artifactCount:1},nextAction:{actionType:"open_artifact",label:"Open draft artifact",payloadSchema:{artifactId:"string"},primary:!0},technicalTrace:{eventCount:6,eventIds:["activity-207"]}},{projectionVersion:2,sliceRunId:"slice-run-105",title:"Distribution schedule finalized",occurredAt:t(21),actorProvenance:{actorType:"agent",actorId:"pace",displayName:"Pace",avatarKey:"pace"},intent:"Map finalized content to channels and publish windows.",dispatch:"Generated channel matrix and queued owner confirmation.",highlights:["Cross-channel schedule matrix generated","Owner sign-off request prepared"],outcome:{state:"succeeded_with_artifacts",summary:"Completed with one planning artifact.",artifactCount:1},nextAction:{actionType:"open_artifact",label:"Open schedule matrix",payloadSchema:{artifactId:"string"},primary:!1},technicalTrace:{eventCount:5,eventIds:["activity-209"]}},{projectionVersion:2,sliceRunId:"slice-run-108",title:"Incident replay blocked by missing archive logs",occurredAt:t(25),actorProvenance:{actorType:"system",actorId:"orgx",displayName:"OrgX",avatarKey:"orgx"},intent:"Reconstruct replay timeline for incident root-cause validation.",dispatch:"Replay attempted with available segments and failed on missing archive block.",highlights:["Archive block 2026-03-01 missing","Recovery decision raised for snapshot restore"],outcome:{state:"failed_actionable",summary:"Awaiting restore decision to continue replay.",artifactCount:1},nextAction:{actionType:"review_blocker",label:"Approve restore path",payloadSchema:{decisionId:"string"},primary:!0},technicalTrace:{eventCount:10,eventIds:["activity-210"]}},{projectionVersion:2,sliceRunId:"slice-run-109",title:"Orchestrator heartbeat and queue health",occurredAt:t(1),actorProvenance:{actorType:"system",actorId:"orgx",displayName:"OrgX",avatarKey:"orgx"},intent:"Keep active initiatives progressing through dispatch automation.",dispatch:"Heartbeat checked stalls, queue depth, and pending decisions.",highlights:["No task stalls detected in current window","Decision queue remains actionable for two initiatives"],outcome:{state:"succeeded_without_artifacts",summary:"Control-plane checks healthy; dispatch continues.",artifactCount:0},nextAction:null,technicalTrace:{eventCount:4,eventIds:["activity-217"]}},{projectionVersion:2,sliceRunId:"slice-run-110",title:"Revenue closeout completed",occurredAt:t(40),actorProvenance:{actorType:"agent",actorId:"mark",displayName:"Mark",avatarKey:"mark"},intent:"Finalize Q2 closeout and publish approved summary.",dispatch:"Closeout reporting and stakeholder review were executed sequentially.",highlights:["Run started and delegated by orchestrator","Closeout artifacts package published (3 artifacts)","Decision resolved for variance interpretation","Executive handoff fulfilled","Milestone and run marked complete"],outcome:{state:"succeeded_with_artifacts",summary:"Revenue closeout completed successfully.",artifactCount:3},nextAction:null,technicalTrace:{eventCount:7,eventIds:["activity-219","activity-220","activity-221","activity-222","activity-223","activity-224","activity-218"]}}],runningWorkSlices:5,needsInputTotal:3,failedActionableTotal:2,completedTodayTotal:7,consistencyFlags:[],outbox:{pendingTotal:4,pendingByQueue:{activity:2,artifacts:1,decisions:1},oldestEventAt:t(19),newestEventAt:t(2),replayStatus:"running",lastReplayAttemptAt:t(1),lastReplaySuccessAt:t(30),lastReplayFailureAt:t(3),lastReplayError:"Temporary timeout while replaying 1 decision event."},chat:{threads:[],total:0,updatedAt:e.toISOString()}}},ea="all";function us(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ld(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return us(e.get("workspace_id"))??us(e.get("workspaceId"))??us(e.get("command_center_id"))??us(e.get("commandCenterId"))??us(e.get("center"))??us(e.get("project_id"))??us(e.get("projectId"))}catch{return null}}function _s(e,t,s){const i=us(t);if(!i){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",ea),e.set("command_center_id",ea),e.set("center",ea));return}e.set("workspace_id",i),e.set("command_center_id",i),e.set("center",i)}function cd(e){const t=us(e);return t?{"x-orgx-workspace-id":t}:{}}function Ht(e){const t={};e.contentTypeJson&&(t["Content-Type"]="application/json"),e.embedMode&&(t["X-Orgx-Embed"]="true"),e.authToken&&(t.Authorization=`Bearer ${e.authToken}`);const s=e.workspaceId??ld();return Object.assign(t,cd(s)),t}const dd=[[/opus/i,"Opus"],[/sonnet/i,"Sonnet"],[/haiku/i,"Haiku"],[/kimi/i,"Kimi"],[/gemini/i,"Gemini"],[/gpt-4o/i,"GPT-4o"],[/gpt-4/i,"GPT-4"],[/qwen/i,"Qwen"],[/deepseek/i,"DeepSeek"],[/llama/i,"Llama"]];function Hi(e){if(!e)return"";for(const[s,i]of dd)if(s.test(e))return i;const t=e.split("/");return t[t.length-1]??e}const Kl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Vl=/^[0-9a-f]{20,}$/i;function Is(e){return Kl.test(e)?`#${e.slice(0,4)}`:Vl.test(e)?`#${e.slice(0,4)}`:e}function Wn(e){return Kl.test(e)||Vl.test(e)}function Un(e,t=4){let s=e.replace(/^\/Users\/[^/]+\//,"~/").replace(/^~\/Code\//,"").replace(/^~\//,"");const i=s.split("/");return i.length>t&&(s=i.slice(-t).join("/")),s}function st(e){let t=e;return t=t.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,s=>`#${s.slice(0,4)}`),t=t.replace(/(?:anthropic|openrouter|openai)\/[a-z0-9._/-]+/gi,s=>Hi(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>Un(s)),t}function Bt(e){let t=e;return t=t.replace(/\[?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\]?/gi,""),t=t.replace(/\[workstream\s*\]/gi,""),t=t.replace(/\[workstream\b[^\]]*\]/gi,""),t=t.replace(/\/var\/folders\/[^\s"']*/g,"(local file)"),t=t.replace(/\/tmp\/[^\s"']*/g,"(temp file)"),t=t.replace(/\/Users\/[^\s"']*/g,s=>Un(s)),t=t.replace(/telegram:\d+/g,"Telegram session"),t=t.replace(/discord:\d+/g,"Discord session"),t=t.replace(/\s{2,}/g," ").trim(),t||"Untitled session"}function ta(e){const t=e.toLowerCase().trim();return t==="main"?"You":t==="system"||t==="system / unknown"||t==="openclaw"||t==="local_openclaw"?"OrgX":t==="not assigned"||t==="unassigned"?"Pending":e}function ho(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function _i(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function ud(e,t){if(!e)return null;for(const s of t){const i=e[s];if(!(typeof i!="number"||!Number.isFinite(i)))return i}return null}function go(e){const t=ho(e);if(!t)return null;const s=ho(t.error),i=s??t,r=_i(i,["message","detail","error_description"])??(s?null:_i(t,["error"])),a=_i(i,["code","error_code","type"]),l=ud(i,["status","httpStatusCode"]),c=_i(i,["requestId","request_id"]),d=_i(i,["docsUrl","docs_url"]);return!r&&!a&&l==null&&!c&&!d?null:{code:a,message:r,status:l,requestId:c,docsUrl:d}}function md(e){var d,u;const t=e.trim();if(!t)return null;const s=(()=>{try{return JSON.parse(t)}catch{return null}})(),i=go(s);if(i)return i;const r=t.indexOf("{"),a=t.lastIndexOf("}");if(r>=0&&a>r){const p=t.slice(r,a+1);try{const x=JSON.parse(p),b=go(x);if(b)return b}catch{}}const l=t.match(/"message"\s*:\s*"([^"]+)"/i),c=t.match(/"code"\s*:\s*"([^"]+)"/i);return!l&&!c?null:{code:((d=c==null?void 0:c[1])==null?void 0:d.trim())||null,message:((u=l==null?void 0:l[1])==null?void 0:u.trim())||null,status:null,requestId:null,docsUrl:null}}function xo(e){return e.replace(/"requestId"\s*:\s*"[^"]*"/gi,"").replace(/"timestamp"\s*:\s*"[^"]*"/gi,"").replace(/"docsUrl"\s*:\s*"[^"]*"/gi,"").replace(/\brequest[_\s-]?id[:=]\s*[\w-]+/gi,"").replace(/\bdocsUrl[:=]\s*\S+/gi,"").replace(/\btimestamp[:=]\s*\S+/gi,"").replace(/[{}]/g," ").replace(/\s{2,}/g," ").trim()}function Xt(e){var c;const t=md(e),s=((c=t==null?void 0:t.code)==null?void 0:c.toLowerCase())??"",i=(t==null?void 0:t.message)??null,r=(i==null?void 0:i.toLowerCase())??"";if(s==="internal_error"||r.includes("internal server error"))return/list decision|load decision|decision/i.test(r)?"Decisions are temporarily unavailable. Try refreshing in a moment.":"OrgX hit a temporary server issue. We will retry automatically.";if(s==="unauthorized"||s==="forbidden"||r.includes("unauthorized")||r.includes("forbidden"))return"Authentication needs attention. Reconnect OrgX in Settings.";const a=xo(i||e),l=a.toLowerCase();return/agent catalog unavailable|listagents/i.test(e)?"Agent details are still loading.":/timed out|timeout|request cancelled|signal is aborted/i.test(l)?"Live sync is taking longer than expected. Data will refresh automatically.":/budget.*exhaust/i.test(l)?"Token budget reached":/unknown api endpoint|route is unavailable|missing required live routes/i.test(l)?"This plugin build is missing required routes. Update and restart the plugin.":/unauthorized|forbidden|authentication|api key/i.test(l)?"Authentication needs attention. Reconnect OrgX in Settings.":/worker exited without structured output|worker close|signal=null/i.test(l)?"An agent run ended before returning a structured result.":/mcp handshake failed/i.test(l)?"The agent connection handshake failed. Retry after reconnecting.":/run not found/i.test(l)?"This session is no longer available.":/500|internal_error|internal server error/i.test(l)?"Something went wrong on the server. Retrying automatically.":/econnrefused|network error|fetch failed/i.test(l)?"Connection issue. Retrying automatically.":/40[13]/.test(l)?"Access issue. You may need to reconnect your workspace.":/blocked without an explicit reason/i.test(l)?"This item was paused without a specific reason.":Bt(st(a))}function pd(e,t){if(e==null&&t==null||e===0&&t||e===0&&!t)return null;const s=e??0,i=t??0,r=a=>a>=1e6?`${(a/1e6).toFixed(1)}M`:a>=1e3?`${Math.round(a/1e3)}K`:`${a}`;return i>0?`${r(s)} / ${r(i)} (${Math.round(s/i*100)}%)`:r(s)}function fd(e){const t=(e==null?void 0:e.event_name)??(e==null?void 0:e.event)??"";if(t){const i=st(t);if(i&&i!=="Untitled session")return i}const s=(e==null?void 0:e.task_title)??(e==null?void 0:e.workstream_title)??(e==null?void 0:e.initiative_title)??"";return s.trim()?s.trim():"Activity event"}function hd(e){const t=e.metadata??{},s=ri(t,"task_title")??ri(t,"workstream_title"),i=s?Bt(String(s)):e.title?Bt(e.title):null,r=ri(t,"user_summary")??ri(t,"summary"),a=r?Bt(String(r)):e.summary?Bt(e.summary):e.description?Bt(e.description):null,l=ri(t,"next_step")??ri(t,"nextStep"),c=l?Bt(String(l)):null,d=(x,b)=>x===b||x.includes(b)||b.includes(x),u=a&&i&&d(a,i)?null:a,p=c&&(i&&d(c,i)||a&&d(c,a))?null:c;return{taskDescription:i,outcomeDescription:u,nextStep:p}}function ri(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const gd={auto_continue_stopped:"Autopilot paused",budget_exhausted:"Token budget reached",error:"Encountered an error",blocked:"Waiting for input",stopped:"Manually stopped",rate_limited:"Rate limited — retrying shortly",timeout:"Timed out",timed_out:"Timed out",cancelled:"Cancelled",completed:"Completed"};function Si(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return gd[t]??e.replace(/_/g," ")}const xd={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function cx(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return xd[t]??e.replace(/_/g," ")}function dx(e,t){return e.toLowerCase().includes("path")?Un(t):Wn(t)?Is(t):t.includes(",")?t.split(",").map(i=>{const r=i.trim();return Wn(r)?Is(r):r}).join(", "):Bt(t)}function yd(e){if(!Number.isFinite(e)||e<1)return"just now";if(e<60)return`${Math.round(e)} min`;const t=Math.floor(e/60),s=Math.round(e%60);if(t<24)return s>0?`${t} hr ${s} min`:`${t} hr`;const i=Math.floor(t/24);return i<7?`${i} day${i===1?"":"s"}`:i<14?"over a week":`${Math.floor(i/7)} weeks`}function ux(e){const t=yd(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function Fr(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function Pt(e){const s=(e instanceof Date?e:new Date(e)).getTime()-Date.now();if(Number.isNaN(s))return"unknown";const i=Math.floor(Math.abs(s)/1e3),r=s<0?"past":"future";if(i<10)return r==="past"?"just now":"soon";if(i<60)return r==="past"?`${i}s ago`:`in ${i}s`;const a=Math.floor(i/60);if(a<60)return r==="past"?`${a}m ago`:`in ${a}m`;const l=Math.floor(a/60);if(l<24)return r==="past"?`${l}h ago`:`in ${l}h`;const c=Math.floor(l/24);return r==="past"?`${c}d ago`:`in ${c}d`}const bd=8e3,vd=320,wd=300,kd=80,Id=80,Nd=120,yo=6e4,jd=1200,Ad=90,_d=3,Sd=24,bo=24,Ci=new WeakMap,Ha={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},rr={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Ks={threads:[],total:0,updatedAt:null},vo={running:0,active:0,queued:1,in_progress:1,working:1,planning:1,handoff:1,review:2,pending:2,blocked:3,failed:4,cancelled:5,paused:6,completed:6,archived:7},Gl=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),ar=10*6e4;function Cd(e){const t=e.trim().toLowerCase();return t?t.includes("aborterror")||t.includes("signal is aborted")||t.includes("aborted")||t.includes("request cancelled")||t.includes("request canceled"):!1}function Td(e){const t=e.map(a=>a.trim()).filter(Boolean);if(t.length===0)return"Live data is unavailable right now. OrgX Live will retry automatically.";const s=t.map(a=>a.toLowerCase());return s.every(a=>a.includes("timed out")||a.includes("timeout")||a.includes("signal is aborted")||a.includes("request cancelled")||a.includes("request canceled"))?"Live sync is taking longer than expected. OrgX Live is retrying in the background.":s.some(a=>a.includes("unknown api endpoint"))?"This plugin runtime is missing required live routes. Restart the plugin, then update if needed.":s.some(a=>a.includes("unauthorized")||a.includes("forbidden"))?"OrgX authorization needs attention. Reconnect your API key in Settings.":Array.from(new Set(t.map(a=>{const l=a.replace(/^[^:]+:\s*/,"").trim();return l.length>0?l:a}))).slice(0,2).map(a=>Xt(a)).filter(a=>a.length>0).join(" ")}function Md(e){const t=e.trim().toLowerCase();if(!t)return"";if(t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("request canceled")||t.includes("signal is aborted"))return"Live sync is slower than expected. Some panels may refresh a few seconds late.";if(t.includes("unauthorized")||t.includes("forbidden"))return"OrgX authorization needs attention. Reconnect your API key in Settings.";if(t.includes("unknown api endpoint")||t.includes("route is unavailable"))return"This plugin runtime is missing required live routes. Restart the plugin after updating.";const s=e.replace(/^[^:]+:\s*/,"").replace(/\s+/g," ").trim();return Xt(s.length>0?s:e.trim())}function Ed(e){const t=e.map(s=>Md(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function _t(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Or(e,t){const s=vo[e.status]??99,i=vo[t.status]??99;if(s!==i)return s-i;const r=_t(e.updatedAt??e.lastEventAt??e.startedAt),a=_t(t.updatedAt??t.lastEventAt??t.startedAt);return r!==a?a-r:e.id.localeCompare(t.id)}function Rd(e){return(e??"").trim().toLowerCase()}function wo(e){return Gl.has(Rd(e.status))}function na(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function ko(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const h=Date.now(),I=e.nodes.filter(w=>{const N=_t(w.updatedAt??w.lastEventAt??w.startedAt);if(wo(w))return!0;const T=["completed","archived","failed"].includes((w.status??"").toLowerCase())?ar/3:ar;return h-N<=T});if(!I.length)return t;const y=new Set(I.map(w=>w.id)),j=new Set(I.map(w=>w.groupId));return{nodes:I.sort(Or),edges:e.edges.filter(w=>y.has(w.parentId)&&y.has(w.childId)),groups:e.groups.filter(w=>j.has(w.id))}}const s=new Set,i=[...t.nodes];for(const h of t.nodes)for(const I of na(h))s.add(I);const r=Date.now(),a=[];for(const h of e.nodes){if(na(h).some(f=>s.has(f)))continue;const y=_t(h.updatedAt??h.lastEventAt??h.startedAt),w=["completed","archived","failed"].includes((h.status??"").toLowerCase())?ar/3:ar,N=r-y<=w;if(wo(h)||N){a.push(h),i.push(h);for(const f of na(h))s.add(f)}}if(!a.length)return t;const l=new Set(i.map(h=>h.id)),c=new Map(e.groups.map(h=>[h.id,h])),d=new Map(t.groups.map(h=>[h.id,h])),u=[...t.groups];for(const h of a){if(d.has(h.groupId))continue;const I=c.get(h.groupId)??{id:h.groupId,label:h.groupLabel||h.agentName||"Ungrouped",status:null};d.set(h.groupId,I),u.push(I)}const p=h=>`${h.parentId}->${h.childId}`,x=new Set,b=[];for(const h of t.edges){if(!l.has(h.parentId)||!l.has(h.childId))continue;const I=p(h);x.has(I)||(x.add(I),b.push(h))}for(const h of e.edges){if(!l.has(h.parentId)||!l.has(h.childId))continue;const I=p(h);x.has(I)||(x.add(I),b.push(h))}return{nodes:i.sort(Or),edges:b,groups:u}}function Ti(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(Or).slice(0,t),i=new Set(s.map(a=>a.id)),r=new Set(s.map(a=>a.groupId));return{nodes:s,edges:e.edges.filter(a=>i.has(a.parentId)&&i.has(a.childId)),groups:e.groups.filter(a=>r.has(a.id))}}function Io(e,t){return e.length<=t?e:[...e].sort((s,i)=>_t(i.updatedAt)-_t(s.updatedAt)).slice(0,t)}function Ld(e){const t=e.requestedAt??e.updatedAt??null,s=e.updatedAt??t,i=Number.isFinite(e.waitingMinutes)?Math.max(0,Math.floor(e.waitingMinutes)):t?Math.max(0,Math.floor((Date.now()-_t(t))/6e4)):0;return{id:e.id,title:e.title,context:e.context??null,status:e.status??"pending",agentName:e.agentName??null,requestedAt:t,updatedAt:s,waitingMinutes:i,metadata:e.metadata}}function Xl(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].timestamp!==t[s].timestamp||e[s].type!==t[s].type||e[s].title!==t[s].title||e[s].requesterAgentId!==t[s].requesterAgentId||e[s].requesterAgentName!==t[s].requesterAgentName||e[s].executorAgentId!==t[s].executorAgentId||e[s].executorAgentName!==t[s].executorAgentName)return!1;return!0}function No(e,t){if(e.nodes.length!==t.nodes.length||e.edges.length!==t.edges.length||e.groups.length!==t.groups.length)return!1;for(let s=0;s<e.nodes.length;s+=1){const i=e.nodes[s],r=t.nodes[s];if(i.id!==r.id||i.status!==r.status||i.title!==r.title||i.progress!==r.progress||i.updatedAt!==r.updatedAt||i.lastEventAt!==r.lastEventAt)return!1}for(let s=0;s<e.edges.length;s+=1){const i=e.edges[s],r=t.edges[s];if(i.parentId!==r.parentId||i.childId!==r.childId)return!1}for(let s=0;s<e.groups.length;s+=1){const i=e.groups[s],r=t.groups[s];if(i.id!==r.id||i.label!==r.label||i.status!==r.status)return!1}return!0}function jo(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].updatedAt!==t[s].updatedAt||e[s].status!==t[s].status||e[s].title!==t[s].title)return!1;return!0}function Ao(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].status!==t[s].status||e[s].updatedAt!==t[s].updatedAt||e[s].waitingMinutes!==t[s].waitingMinutes)return!1;return!0}function Ql(e){if(!e||typeof e!="object")return Ha;const t=e.pendingByQueue&&typeof e.pendingByQueue=="object"?Object.fromEntries(Object.entries(e.pendingByQueue).filter(([i])=>typeof i=="string"&&i.length>0).map(([i,r])=>[i,Number.isFinite(Number(r))?Math.max(0,Math.floor(Number(r))):0])):{},s=e.replayStatus==="running"||e.replayStatus==="success"||e.replayStatus==="error"?e.replayStatus:"idle";return{pendingTotal:Number.isFinite(e.pendingTotal)?Math.max(0,Math.floor(e.pendingTotal)):Object.values(t).reduce((i,r)=>i+r,0),pendingByQueue:t,oldestEventAt:e.oldestEventAt??null,newestEventAt:e.newestEventAt??null,replayStatus:s,lastReplayAttemptAt:e.lastReplayAttemptAt??null,lastReplaySuccessAt:e.lastReplaySuccessAt??null,lastReplayFailureAt:e.lastReplayFailureAt??null,lastReplayError:e.lastReplayError??null}}function Dd(e,t){if(e.pendingTotal!==t.pendingTotal||e.oldestEventAt!==t.oldestEventAt||e.newestEventAt!==t.newestEventAt||e.replayStatus!==t.replayStatus||e.lastReplayAttemptAt!==t.lastReplayAttemptAt||e.lastReplaySuccessAt!==t.lastReplaySuccessAt||e.lastReplayFailureAt!==t.lastReplayFailureAt||e.lastReplayError!==t.lastReplayError)return!1;const s=Object.keys(e.pendingByQueue),i=Object.keys(t.pendingByQueue);if(s.length!==i.length)return!1;for(const r of s)if(e.pendingByQueue[r]!==t.pendingByQueue[r])return!1;return!0}function qr(e,t=0){if(e==null)return"null";const s=typeof e;if(s==="string")return`s:${e}`;if(s==="number")return`n:${Number.isFinite(e)?String(e):"nan"}`;if(s==="boolean")return`b:${e?"1":"0"}`;if(s==="bigint")return`i:${String(e)}`;if(s!=="object")return`${s}:${String(e)}`;const i=e,r=Ci.get(i);if(r)return r;if(t>=_d){const x=Array.isArray(e)?"[…]":"{…}";return Ci.set(i,x),x}if(Ci.set(i,Array.isArray(e)?"[]":"{}"),Array.isArray(e)){const x=e.slice(0,bo).map(I=>qr(I,t+1)).join(","),b=e.length>bo?",…":"",h=`[${x}${b}]`;return Ci.set(i,h),h}const a=e,l=Object.keys(a).sort(),c=l.slice(0,Sd),d=c.map(x=>`${x}:${qr(a[x],t+1)}`).join("|"),u=l.length>c.length?"|…":"",p=`{${d}${u}}`;return Ci.set(i,p),p}function $d(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Os(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function Pd(e){const t=$d(e.metadata),s=t==null?void 0:t.event,i=typeof s=="string"?s.trim().toLowerCase():"",r=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??Os(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=Os(t,["correlation_id","correlationId"]),l=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??Os(t,["initiative_id","initiativeId"]),c=Os(t,["workstream_id","workstreamId"]),d=Os(t,["task_id","taskId"]),u=Os(t,["stop_reason","stopReason"]),p=Os(t,["parsed_status","parsedStatus"]),x=(e.title??"").trim().toLowerCase();return!i&&!r&&!a||!r&&!a&&!c&&!d?null:[i,l??"",c??"",d??"",r??"",a??"",u??"",p??"",x].join("|")}function or(e){let t=0;const s=e.metadata;return s&&(t+=Object.keys(s).length),e.summary&&(t+=2),e.description&&(t+=2),e.agentName&&(t+=1),e.runtimeLabel&&(t+=1),e.runtimeProvider&&(t+=1),e.phase&&(t+=1),e.state&&(t+=1),t}function Yl(e,t){const s=new Set,i=new Set,r=new Map,a=[];for(const l of e){if(s.has(l.id)){const d=a.findIndex(u=>u.id===l.id);d>=0&&or(l)>or(a[d])&&(a[d]=l);continue}s.add(l.id);const c=Pd(l);if(c&&i.has(c)){const d=r.get(c);or(l)>or(a[d])&&(a[d]=l);continue}if(c&&(i.add(c),r.set(c,a.length)),a.push(l),a.length>=t)break}return a}function Fd(e,t,s){if(t.length===0)return e;const i=new Map,r=new Map;for(const d of e)i.set(d.id,d),r.set(d.id,qr(d.metadata));let a=!1;for(const d of t){const u=i.get(d.id),p=qr(d.metadata);if(!u){i.set(d.id,d),r.set(d.id,p),a=!0;continue}(u.timestamp!==d.timestamp||u.type!==d.type||u.title!==d.title||u.description!==d.description||u.summary!==d.summary||u.kind!==d.kind||u.agentId!==d.agentId||u.agentName!==d.agentName||u.requesterAgentId!==d.requesterAgentId||u.requesterAgentName!==d.requesterAgentName||u.executorAgentId!==d.executorAgentId||u.executorAgentName!==d.executorAgentName||u.runId!==d.runId||u.initiativeId!==d.initiativeId||u.decisionRequired!==d.decisionRequired||r.get(d.id)!==p)&&(i.set(d.id,d),r.set(d.id,p),a=!0)}if(!a)return e;const l=Array.from(i.values()).sort((d,u)=>{const p=_t(u.timestamp)-_t(d.timestamp);return p!==0?p:u.id.localeCompare(d.id)}),c=Yl(l,s);return Xl(e,c)?e:c}function sa(e,t){const s=[...e].sort((i,r)=>{const a=_t(r.timestamp)-_t(i.timestamp);return a!==0?a:r.id.localeCompare(i.id)});return Yl(s,t)}function _o(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(Ld).sort((a,l)=>a.waitingMinutes!==l.waitingMinutes?l.waitingMinutes-a.waitingMinutes:_t(l.requestedAt??l.updatedAt)-_t(a.requestedAt??a.updatedAt)).slice(0,t),i=new Set,r=[];for(const a of s)i.has(a.id)||(i.add(a.id),r.push(a));return r}function So(e){return e==="run_failed"||e==="blocker_created"?"blocked":e==="run_completed"||e==="milestone_completed"?"completed":e==="decision_requested"||e==="handoff_requested"?"pending":e==="decision_resolved"||e==="handoff_fulfilled"?"completed":"running"}function Od(e){const t=e.toLowerCase();return t==="running"||t==="active"?"running":t==="queued"||t==="pending"?"queued":t==="blocked"?"blocked":t==="failed"?"failed":t==="completed"||t==="done"?"completed":"archived"}function qd(e,t){return!!(Gl.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function lr(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function ia(e){if(!Array.isArray(e))return[];const t=[];for(const s of e)typeof s=="string"&&s.trim().length>0&&t.push(s.trim());return t}function Bd(e,t,s){const i=new Map,r=[...e].sort((c,d)=>_t(d.timestamp)-_t(c.timestamp));for(const c of r){if(!c.runId)continue;const d=c.runId,u=i.get(d),p=c.timestamp;if(!u){const x=c.initiativeId??null;i.set(d,{id:d,parentId:null,runId:d,title:c.title,agentId:c.agentId??null,agentName:c.agentName??null,status:So(c.type),progress:null,initiativeId:x,workstreamId:null,groupId:x??"unscoped",groupLabel:lr(x),startedAt:p,updatedAt:p,lastEventAt:p,lastEventSummary:c.title,blockers:c.type==="blocker_created"&&c.description?[c.description]:[]});continue}(!u.startedAt||_t(p)<_t(u.startedAt))&&(u.startedAt=p),_t(p)>=_t(u.updatedAt??u.lastEventAt)&&(u.updatedAt=p,u.lastEventAt=p,u.lastEventSummary=c.title,u.status=So(c.type),c.agentName&&(u.agentName=c.agentName),c.agentId&&(u.agentId=c.agentId),c.initiativeId&&(u.initiativeId=c.initiativeId,u.groupId=c.initiativeId,u.groupLabel=lr(c.initiativeId)),(!u.title||u.title.length<4)&&(u.title=c.title)),c.type==="blocker_created"&&c.description&&(u.blockers.includes(c.description)||u.blockers.push(c.description))}for(const c of t??[]){const d=c.runId??`agent:${c.id}`,u=i.get(d),p=Od(c.status),x=new Date().toISOString(),b=qd(c,p),h=c.startedAt??(b?x:null),I=c.initiativeId??null,y=c.currentTask&&c.currentTask.trim().length>0?c.currentTask.trim():`${c.name??c.id} ${p==="archived"?"idle":p}`;if(!u){i.set(d,{id:d,parentId:null,runId:d,title:y,agentId:c.id,agentName:c.name??c.id,status:p,progress:null,initiativeId:I,workstreamId:null,groupId:I??"unscoped",groupLabel:lr(I),startedAt:h,updatedAt:h,lastEventAt:h,lastEventSummary:c.currentTask,blockers:ia(c.blockers)});continue}!u.agentName&&c.name&&(u.agentName=c.name),u.agentId||(u.agentId=c.id),(!u.title||u.title===u.runId)&&(u.title=y),b&&(u.updatedAt=h??u.updatedAt??x,u.lastEventAt=h??u.lastEventAt??x),u.status==="archived"&&p!=="archived"&&(u.status=p),ia(c.blockers).length>0&&(u.blockers=ia(c.blockers)),I&&!u.initiativeId&&(u.initiativeId=I,u.groupId=I,u.groupLabel=lr(I))}const a=Array.from(i.values()).sort(Or).slice(0,s),l=new Map;for(const c of a)l.has(c.groupId)||l.set(c.groupId,{id:c.groupId,label:c.groupLabel,status:c.status});return{nodes:a,edges:[],groups:Array.from(l.values())}}async function zd(e,t,s){var p;const i=Number.isFinite(s.timeoutMs)?Math.max(100,Math.floor(s.timeoutMs)):0,r=i>0?new AbortController:null,a=t==null?void 0:t.signal,l=(r==null?void 0:r.signal)??a,c=l?{...t??{},signal:l}:t??{};let d=null,u=null;if(r){if(a!=null&&a.aborted)r.abort();else if(a){const x=()=>r.abort();a.addEventListener("abort",x,{once:!0}),u=()=>a.removeEventListener("abort",x)}d=setTimeout(()=>r.abort(),i)}try{const x=await fetch(e,c),h=(((p=x.headers.get("content-type"))==null?void 0:p.toLowerCase())??"").includes("application/json");if(!x.ok){let I=`${x.status} ${x.statusText}`;if(h){const y=await x.json().catch(()=>null);y!=null&&y.error&&(I=`${x.status} ${y.error}`)}else{const y=(await x.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);y.length>0&&(I=`${x.status} ${y}`)}return{ok:!1,status:x.status,data:null,error:I}}if(!h){const I=(await x.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:x.status,data:null,error:`Unexpected content type for ${e}${I?`: ${I}`:""}`}}return{ok:!0,status:x.status,data:await x.json(),error:null}}catch(x){const b=x instanceof Error?x.message:"Network error",h=!!(r!=null&&r.signal.aborted)&&!(a!=null&&a.aborted);return x instanceof DOMException&&x.name==="AbortError"||Cd(b)?{ok:!1,status:0,data:null,error:h&&i>0?`request timed out after ${i}ms`:"request cancelled"}:{ok:!1,status:0,data:null,error:b}}finally{d&&clearTimeout(d),u&&u()}}function Ud(e,t,s,i,r=[],a=Ha,l=null,c=1,d=[],u=Ks,p){var I,y,j;const x=((I=t[0])==null?void 0:I.timestamp)??null,b=((y=i[0])==null?void 0:y.requestedAt)??((j=i[0])==null?void 0:j.updatedAt)??null,h=_t(x)>=_t(b)?x:b;return{connection:"connected",lastActivity:h?Pt(h):null,lastSnapshotAt:l,snapshotVersion:c,sessions:e,activity:t,handoffs:s,decisions:i,sliceRuns:r,outbox:Ql(a),chat:Cr(u),runtimeInstances:d,workSliceProjections:(p==null?void 0:p.workSliceProjections)??[],timelineNarrative:(p==null?void 0:p.timelineNarrative)??[],nextUpByInitiative:(p==null?void 0:p.nextUpByInitiative)??[],runningWorkSlices:(p==null?void 0:p.runningWorkSlices)??0,needsInputTotal:(p==null?void 0:p.needsInputTotal)??0,failedActionableTotal:(p==null?void 0:p.failedActionableTotal)??0,completedTodayTotal:(p==null?void 0:p.completedTodayTotal)??0,consistencyFlags:(p==null?void 0:p.consistencyFlags)??[],dataHealth:p==null?void 0:p.dataHealth}}function Co(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object"||typeof s.id!="string")continue;const i=s.id.trim();i&&t.set(i,s)}return Array.from(t.values()).sort((s,i)=>_t(i.lastEventAt??i.lastHeartbeatAt)-_t(s.lastEventAt??s.lastHeartbeatAt))}function To(e,t){const s=e??[],i=t??[];if(s.length!==i.length)return!1;for(let r=0;r<s.length;r+=1)if(s[r].id!==i[r].id||s[r].state!==i[r].state||s[r].lastEventAt!==i[r].lastEventAt||s[r].runId!==i[r].runId||s[r].progressPct!==i[r].progressPct)return!1;return!0}function Wd(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object"||typeof s.id!="string")continue;const i=s.id.trim();i&&t.set(i,{...s,id:i,watcherIds:Array.isArray(s.watcherIds)?s.watcherIds.filter(Boolean):[],watcherNames:Array.isArray(s.watcherNames)?s.watcherNames.filter(Boolean):[],latestLaunch:s.latestLaunch&&typeof s.latestLaunch=="object"?{...s.latestLaunch,watcherIds:Array.isArray(s.latestLaunch.watcherIds)?s.latestLaunch.watcherIds.filter(Boolean):[],watcherNames:Array.isArray(s.latestLaunch.watcherNames)?s.latestLaunch.watcherNames.filter(Boolean):[],warnings:Array.isArray(s.latestLaunch.warnings)?s.latestLaunch.warnings.filter(Boolean):[]}:null})}return Array.from(t.values()).sort((s,i)=>_t(i.lastActivityAt??i.updatedAt)-_t(s.lastActivityAt??s.updatedAt))}function Cr(e){if(!e||typeof e!="object")return Ks;const t=Wd(Array.isArray(e.threads)?e.threads:[]),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(t.length,Math.floor(e.total)):t.length;return{threads:t,total:s,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}function Hd(e,t){const s=e??Ks,i=t??Ks;if(s.total!==i.total||s.updatedAt!==i.updatedAt||s.threads.length!==i.threads.length)return!1;for(let r=0;r<s.threads.length;r+=1){const a=s.threads[r],l=i.threads[r];if(a.id!==l.id||a.status!==l.status||a.lastActivityAt!==l.lastActivityAt||a.lastSnippet!==l.lastSnippet||a.assigneeId!==l.assigneeId||a.launchCount!==l.launchCount||a.messageCount!==l.messageCount)return!1}return!0}function Tr(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map,s=(i,r)=>{const a=[],l=c=>{if(typeof c!="string")return;const d=c.trim();d&&(a.some(u=>u.toLowerCase()===d.toLowerCase())||a.push(d))};if(Array.isArray(i))for(const c of i)l(c);else if(typeof i=="string")for(const c of i.split(/[\n,;]+/g))l(c);return r&&l(r),a};for(const i of e){if(!i||typeof i!="object")continue;const r=typeof i.sliceKind=="string"?i.sliceKind:typeof i.slice_kind=="string"?i.slice_kind:null,a=(r==null?void 0:r.trim().toLowerCase())??null;if(a&&a!=="work_slice")continue;const l=typeof i.sliceRunId=="string"&&i.sliceRunId.trim().length>0?i.sliceRunId.trim():typeof i.id=="string"&&i.id.trim().length>0?i.id.trim():null;if(!l)continue;const c=s(i.initiativeIds,i.initiativeId??null),d=s(i.workstreamIds,i.workstreamId??null),u=s(i.iwmtIds,i.iwmtId??null),p=typeof i.initiativeId=="string"&&i.initiativeId.trim().length>0?i.initiativeId.trim():c[0]??null,x=typeof i.workstreamId=="string"&&i.workstreamId.trim().length>0?i.workstreamId.trim():d[0]??null,b=typeof i.iwmtId=="string"&&i.iwmtId.trim().length>0?i.iwmtId.trim():u[0]??null;t.set(l,{...i,id:l,sliceRunId:l,sliceKind:a==="work_slice"?"work_slice":void 0,initiativeId:p,initiativeIds:c,workstreamId:x,workstreamIds:d,iwmtId:b,iwmtIds:u,artifacts:Array.isArray(i.artifacts)?i.artifacts:[],decisionOptions:Array.isArray(i.decisionOptions)?i.decisionOptions:[],taskIds:Array.isArray(i.taskIds)?i.taskIds:[],milestoneIds:Array.isArray(i.milestoneIds)?i.milestoneIds:[]})}return Array.from(t.values()).sort((i,r)=>_t(r.updatedAt??r.lastEventAt)-_t(i.updatedAt??i.lastEventAt))}function cr(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const i=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;if(!i)continue;const r=s.lineage&&typeof s.lineage=="object"?s.lineage:null;t.set(i,{...s,sliceRunId:i,consistencyFlags:Array.isArray(s.consistencyFlags)?s.consistencyFlags:[],lineage:{initiativeIds:Array.isArray(r==null?void 0:r.initiativeIds)?r.initiativeIds:[],initiativeTitles:Array.isArray(r==null?void 0:r.initiativeTitles)?r.initiativeTitles:[],workstreamIds:Array.isArray(r==null?void 0:r.workstreamIds)?r.workstreamIds:[],workstreamTitles:Array.isArray(r==null?void 0:r.workstreamTitles)?r.workstreamTitles:[],taskIds:Array.isArray(r==null?void 0:r.taskIds)?r.taskIds:[],milestoneIds:Array.isArray(r==null?void 0:r.milestoneIds)?r.milestoneIds:[],iwmtIds:Array.isArray(r==null?void 0:r.iwmtIds)?r.iwmtIds:[],sliceRunId:i,sessionId:typeof(r==null?void 0:r.sessionId)=="string"?r.sessionId:null},artifacts:Array.isArray(s.artifacts)?s.artifacts:[]})}return Array.from(t.values()).sort((s,i)=>_t(i.updatedAt??i.completedAt??i.failedAt)-_t(s.updatedAt??s.completedAt??s.failedAt))}function ra(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const i=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;i&&t.set(i,{...s,sliceRunId:i,highlights:Array.isArray(s.highlights)?s.highlights:[],technicalTrace:s.technicalTrace??{eventCount:0,eventIds:[]}})}return Array.from(t.values()).sort((s,i)=>_t(i.occurredAt)-_t(s.occurredAt))}function aa(e){return!Array.isArray(e)||e.length===0?[]:e.filter(t=>t&&typeof t=="object").map(t=>({initiativeId:typeof t.initiativeId=="string"&&t.initiativeId.trim().length>0?t.initiativeId.trim():null,initiativeTitle:typeof t.initiativeTitle=="string"&&t.initiativeTitle.trim().length>0?t.initiativeTitle.trim():"Unscoped initiative",pendingCount:typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.floor(t.pendingCount)):0,queue:Array.isArray(t.queue)?t.queue:[]})).sort((t,s)=>s.pendingCount-t.pendingCount)}function Mo(e){var s;if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const i of e){if(i.sliceKind!=="work_slice")continue;const r=i.lineage.initiativeIds[0]??null,a=i.lineage.workstreamIds[0]??null,l=i.lineage.workstreamTitles[0]??i.lineage.workstreamIds[0]??null,c=i.lifecycleState==="completed"&&i.outcomeState==="succeeded_without_artifacts"?"needs_review":i.lifecycleState,d=((s=i.actionContract)==null?void 0:s.actionType)??null,u=d==="open_artifact"||d==="open_logs"||d==="open_session"||d==="open_run"||d==="open_workstream"||d==="open_task"||d==="open_initiative"||d==="open_pr"||d==="open_diff"||d==="open_branch"?"open_artifact":d==="approve"||d==="reject"||d==="provide_context"||d==="request_info"||d==="confirm_scope"||d==="connect_provider"||d==="refresh_credentials"||d==="reassign"||d==="escalate"?"resolve_decision":d==="retry"||d==="resume"||d==="start"||d==="auto_fix"?"retry_slice":i.outcomeState==="succeeded_without_artifacts"?"review_output":"none";t.push({id:i.sliceRunId,sliceRunId:i.sliceRunId,sliceKind:"work_slice",runId:i.runId,initiativeId:r,initiativeIds:i.lineage.initiativeIds,workstreamId:a,workstreamIds:i.lineage.workstreamIds,iwmtId:i.lineage.iwmtIds[0]??null,iwmtIds:i.lineage.iwmtIds,workstreamTitle:l,taskIds:i.lineage.taskIds,milestoneIds:i.lineage.milestoneIds,status:c,statusExplainer:i.statusExplainer,primaryAction:u,hasArtifact:i.hasArtifact,artifactCount:i.artifactCount,artifacts:i.artifacts.map(p=>({id:p.artifactId,type:p.type,title:p.title,url:p.url,createdAt:p.producedAt})),decisionCount:i.outcomeState==="needs_input"?1:0,blockingDecisionCount:i.outcomeState==="needs_input"?1:0,decisionOptions:[],sourceClient:i.sourceClient,runtimeState:i.runtimeState,startedAt:null,updatedAt:i.updatedAt,completedAt:i.completedAt,failedAt:i.failedAt,archivedAt:i.archivedAt,lastEventAt:i.updatedAt,lastEventSummary:i.statusExplainer,correlationId:i.sliceRunId,confidence:i.confidence})}return Tr(t)}function Kd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const i=e[s],r=t[s];if(i.sliceRunId!==r.sliceRunId||i.status!==r.status||i.updatedAt!==r.updatedAt||i.lastEventAt!==r.lastEventAt||i.artifactCount!==r.artifactCount||i.decisionCount!==r.decisionCount||i.blockingDecisionCount!==r.blockingDecisionCount||i.runtimeState!==r.runtimeState)return!1}return!0}function Vd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const i=e[s],r=t[s];if(i.sliceRunId!==r.sliceRunId||i.lifecycleState!==r.lifecycleState||i.outcomeState!==r.outcomeState||i.updatedAt!==r.updatedAt||i.artifactCount!==r.artifactCount||i.lineage.sessionId!==r.lineage.sessionId)return!1}return!0}function Gd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const i=e[s],r=t[s];if(i.sliceRunId!==r.sliceRunId||i.occurredAt!==r.occurredAt||i.outcome.state!==r.outcome.state||i.outcome.artifactCount!==r.outcome.artifactCount)return!1}return!0}function Xd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const i=e[s],r=t[s];if(i.initiativeId!==r.initiativeId||i.pendingCount!==r.pendingCount||i.queue.length!==r.queue.length)return!1}return!0}function Qd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function Yd(e,t){return!e&&!t?!0:!e||!t?!1:e.status===t.status&&e.totals.slices===t.totals.slices&&e.totals.missingTerminal===t.totals.missingTerminal&&e.totals.lineageGap===t.totals.lineageGap&&e.totals.artifactMismatch===t.totals.artifactMismatch&&e.totals.invalidActor===t.totals.invalidActor}function Jd(e={}){const{enabled:t=!0,pollInterval:s=bd,useMock:i=!1,enableDecisions:r=!0,initiativeId:a=null,projectId:l=null,maxSessions:c=vd,maxActivityItems:d=wd,maxHandoffs:u=kd,maxDecisions:p=Id,batchWindowMs:x=Nd}=e,b=typeof a=="string"&&a.trim().length>0?a.trim():null,h=typeof l=="string"&&l.trim().length>0?l.trim():null,[I,y]=o.useState(fo()),[j,w]=o.useState(rr),[N,f]=o.useState(!i),[T,X]=o.useState(null),Z=o.useRef(),W=o.useRef(null),ke=o.useRef(null),[D,E]=o.useState(!1),de=o.useRef(0),ie=o.useRef(!1),we=o.useRef(`${b??"__all__"}::${h??"__all__"}`),ae=o.useRef(!1),ze=o.useRef(null),pe=o.useCallback((B,K)=>{ze.current&&(clearTimeout(ze.current),ze.current=null),w(B),K!=null&&K.autoResetMs&&K.autoResetMs>0&&(ze.current=setTimeout(()=>{ze.current=null,w(rr)},K.autoResetMs))},[]);o.useEffect(()=>()=>{ze.current&&(clearTimeout(ze.current),ze.current=null)},[]),o.useEffect(()=>{const B=`${b??"__all__"}::${h??"__all__"}`;we.current!==B&&(we.current=B,ae.current=!0,pe(rr),y(K=>({...K,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Ks,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(K.snapshotVersion??0)+1})),f(!0),X(null))},[b,h,pe]);const le=o.useCallback((B,K,re,ge=null,Se=null,oe=null,ye=null,me=null,O=null,U=null)=>{de.current=Date.now(),ie.current=!1,y(Y=>{const ce=ae.current;ce&&(ae.current=!1);const qe=K===null?ce?[]:Y.activity:sa(K,d),We=re===null?ce?[]:Y.handoffs:Io(re,u),Fe=Ti(B===null?ce?{nodes:[],edges:[],groups:[]}:Y.sessions:ce?Ti(B,c):ko(Y.sessions,Ti(B,c)),c),L=ge===null?ce?[]:Y.decisions:_o(ge,p),ct=Se===null?ce?[]:Y.sliceRuns:Tr(Se),Me=oe===null?ce?Ha:Y.outbox:Ql(oe),Qe=me===null?ce?[]:Y.runtimeInstances??[]:Co(me),St=O===null?ce?Ks:Y.chat??Ks:Cr(O),zt=(U==null?void 0:U.workSliceProjections)==null?ce?[]:Y.workSliceProjections??[]:cr(U.workSliceProjections),Mt=(U==null?void 0:U.timelineNarrative)==null?ce?[]:Y.timelineNarrative??[]:ra(U.timelineNarrative),q=(U==null?void 0:U.nextUpByInitiative)==null?ce?[]:Y.nextUpByInitiative??[]:aa(U.nextUpByInitiative),_e=typeof(U==null?void 0:U.runningWorkSlices)=="number"&&Number.isFinite(U.runningWorkSlices)?Math.max(0,Math.floor(U.runningWorkSlices)):Y.runningWorkSlices??0,be=typeof(U==null?void 0:U.needsInputTotal)=="number"&&Number.isFinite(U.needsInputTotal)?Math.max(0,Math.floor(U.needsInputTotal)):Y.needsInputTotal??0,Le=typeof(U==null?void 0:U.failedActionableTotal)=="number"&&Number.isFinite(U.failedActionableTotal)?Math.max(0,Math.floor(U.failedActionableTotal)):Y.failedActionableTotal??0,tt=typeof(U==null?void 0:U.completedTodayTotal)=="number"&&Number.isFinite(U.completedTodayTotal)?Math.max(0,Math.floor(U.completedTodayTotal)):Y.completedTodayTotal??0,at=(U==null?void 0:U.consistencyFlags)==null?Y.consistencyFlags??[]:U.consistencyFlags.filter(je=>typeof je=="string"),J=(U==null?void 0:U.dataHealth)===void 0||(U==null?void 0:U.dataHealth)===null?Y.dataHealth:U.dataHealth,Ue=(Y.snapshotVersion??0)+1;return No(Y.sessions,Fe)&&Xl(Y.activity,qe)&&jo(Y.handoffs,We)&&Ao(Y.decisions,L)&&Kd(Y.sliceRuns,ct)&&Dd(Y.outbox,Me)&&Hd(Y.chat,St)&&To(Y.runtimeInstances,Qe)&&Vd(Y.workSliceProjections??[],zt)&&Gd(Y.timelineNarrative??[],Mt)&&Xd(Y.nextUpByInitiative??[],q)&&(Y.runningWorkSlices??0)===_e&&(Y.needsInputTotal??0)===be&&(Y.failedActionableTotal??0)===Le&&(Y.completedTodayTotal??0)===tt&&Qd(Y.consistencyFlags??[],at)&&Yd(Y.dataHealth,J)&&Y.lastSnapshotAt===ye&&Y.connection==="connected"?Y:Ud(Fe,qe,We,L,ct,Me,ye,Ue,Qe,St,{workSliceProjections:zt,timelineNarrative:Mt,nextUpByInitiative:q,runningWorkSlices:_e,needsInputTotal:be,failedActionableTotal:Le,completedTodayTotal:tt,consistencyFlags:at,dataHealth:J})}),f(!1)},[d,p,u,c]),te=o.useCallback(async()=>{if(!t){y(re=>re.connection==="disconnected"?re:{...re,connection:"disconnected"}),f(!1),X(null);return}const B=`${b??"__all__"}::${h??"__all__"}`;if(W.current&&ke.current===B)return W.current;if(i){y(fo()),f(!1);return}const K=(async()=>{try{const re=new URLSearchParams({sessionsLimit:String(c),activityLimit:String(d),decisionsLimit:String(p),include_idle:"true"});h&&_s(re,h),b&&re.set("initiative",b);const ge=[{label:"live/snapshot-v2",url:`/orgx/api/live/snapshot-v2?${re.toString()}`},{label:"dashboard-bundle",url:`/orgx/api/dashboard-bundle?${re.toString()}`},{label:"live/snapshot",url:`/orgx/api/live/snapshot?${re.toString()}`}],Se=[];let oe=null,ye=!1;for(let Te=0;Te<ge.length;Te+=1){const lt=ge[Te];Te>0&&await new Promise(Rt=>{setTimeout(Rt,Ad)});const ht=await zd(lt.url,{headers:Ht({workspaceId:h})},{timeoutMs:jd});if(ht.ok&&ht.data){oe=ht.data;break}(ht.status===401||ht.status===403)&&(ye=!0),Se.push(`${lt.label}: ${ht.error??"unavailable"}`)}if(!oe){if(ye){const Te=new Error("Unauthorized. Update your OrgX API key in Settings (use a user-scoped oxk_... key; userId should be blank).");throw Te.code="ORGX_AUTH",Te}throw new Error(Td(Se))}if(we.current!==B)return;const me=Array.isArray(oe.degraded)?oe.degraded.filter(Te=>typeof Te=="string"):[],O=me.map(Te=>Te.toLowerCase()),U=(...Te)=>O.some(lt=>Te.some(ht=>lt.includes(ht))),Y=Array.isArray(oe.activity)?oe.activity:[],ce=Array.isArray(oe.handoffs)?oe.handoffs:[],qe=Array.isArray(oe.decisions)?oe.decisions:[],We=Y.length===0&&U("activity unavailable","activity local fallback failed"),Fe=U("sessions unavailable","sessions local fallback failed"),L=ce.length===0&&U("handoffs unavailable"),ct=qe.length===0&&U("decisions unavailable"),Me=cr(Array.isArray(oe.projections)?oe.projections:[]),Qe=Cr(oe.chat??null),St=ra(Array.isArray(oe.timelineNarrative)?oe.timelineNarrative:[]),zt=aa(Array.isArray(oe.nextUpByInitiative)?oe.nextUpByInitiative:[]),Mt=Me.length>0?Mo(Me):Tr(Array.isArray(oe.sliceRuns)?oe.sliceRuns:[]),q=oe.sessions&&Array.isArray(oe.sessions.nodes)&&Array.isArray(oe.sessions.edges)&&Array.isArray(oe.sessions.groups)?oe.sessions:Bd(Y,oe.agents,c),_e=Mt.length===0&&Me.length===0&&U("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),be=zt.length===0&&U("next-up unavailable","next-up queue"),Le=We?null:Y,tt=L?null:ce,at=ct?null:qe,J=Fe&&q.nodes.length===0?null:q,Ue=_e?null:Me,je=_e?null:St,Q=_e?null:Mt,Ee=be?null:zt;le(J,Le,tt,at,Q,oe.outbox??null,oe.generatedAt??null,oe.runtimeInstances??null,Qe,{workSliceProjections:Ue,timelineNarrative:je,nextUpByInitiative:Ee,runningWorkSlices:_e?null:oe.runningWorkSlices??null,needsInputTotal:_e?null:oe.needsInput??null,failedActionableTotal:_e?null:oe.failedActionable??null,completedTodayTotal:_e?null:oe.completedToday??null,consistencyFlags:Array.isArray(oe.consistencyFlags)?oe.consistencyFlags:null,dataHealth:oe.dataHealth??null});const nt=me.length>0?Ed(me):[];nt.length>0?(X(`Partial live data: ${nt.join("; ")}`),y(Te=>Te.connection==="connected"?Te:{...Te,connection:"connected"}),E(!1)):(X(null),y(Te=>Te.connection==="connected"?Te:{...Te,connection:"connected"}))}catch(re){if(we.current!==B)return;const ge=re instanceof Error?re.message:"Unknown error",Se=re==null||typeof re!="object"||!("code"in re)?!1:re.code==="ORGX_AUTH";Se&&(ie.current=!0);const oe=de.current>0&&Date.now()-de.current>yo;X(ge),y(ye=>{const me=Se||oe?"disconnected":"reconnecting";return ye.connection===me?ye:{...ye,connection:me}}),E(!Se),f(!1)}finally{ke.current===B&&(W.current=null,ke.current=null)}})();return W.current=K,ke.current=B,K},[le,t,r,d,p,u,c,h,b,i]),ne=o.useCallback(async(B,K,re)=>{var O,U,Y;if(!r)throw new Error("OrgX decisions are unavailable while disconnected.");const ge=Array.from(new Set(B.filter(Boolean)));if(ge.length===0)return{updated:0,failed:0};const Se=((O=re==null?void 0:re.note)==null?void 0:O.trim())||void 0,oe=((U=re==null?void 0:re.optionId)==null?void 0:U.trim())||void 0;if(i){const ce=new Set(ge);return y(qe=>{const We=qe.decisions.filter(Me=>ce.has(Me.id));if(We.length===0)return qe;const Fe=new Date().toISOString(),L=We.map(Me=>({id:`decision:${K}:${Me.id}:${Date.now()}`,type:"decision_resolved",title:K==="approve"?`Approved: ${Me.title}`:`Rejected: ${Me.title}`,description:Me.context,agentId:null,agentName:Me.agentName,requesterAgentId:null,requesterAgentName:Me.agentName??null,executorAgentId:null,executorAgentName:Me.agentName??null,runId:null,initiativeId:null,timestamp:Fe,metadata:{decisionId:Me.id,action:K}})),ct=sa(L.concat(qe.activity),d);return{...qe,decisions:qe.decisions.filter(Me=>!ce.has(Me.id)),activity:ct,lastActivity:Pt(Fe)}}),{updated:ce.size,failed:0,firstError:void 0}}const ye=new Date().toISOString(),me=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:Ht({contentTypeJson:!0,workspaceId:h}),body:JSON.stringify({ids:ge,action:K,...Se?{note:Se}:{},...oe?{option_id:oe}:{}})});try{const ce=await me.json().catch(()=>null),qe=Array.isArray(ce==null?void 0:ce.results)?ce.results:[],We=new Set(qe.filter(Qe=>Qe.ok).map(Qe=>Qe.id)),L=((Y=qe.filter(Qe=>!Qe.ok).find(Qe=>typeof Qe.error=="string"&&Qe.error.trim().length>0))==null?void 0:Y.error)??(typeof(ce==null?void 0:ce.error)=="string"&&ce.error.trim().length>0?ce.error:void 0);if(!me.ok&&me.status!==207){const Qe=L??`Decision action failed (${me.status})`;throw new Error(Qe)}if(We.size===0&&me.ok&&((ce==null?void 0:ce.failed)??0)===0)for(const Qe of ge)We.add(Qe);We.size>0?y(Qe=>{const St=Qe.decisions.filter(be=>We.has(be.id));if(St.length===0)return Qe;const zt=new Date().toISOString(),Mt=St.map(be=>({id:`decision:${K}:${be.id}:${Date.now()}`,type:"decision_resolved",title:K==="approve"?`Approved: ${be.title}`:`Rejected: ${be.title}`,description:be.context,agentId:null,agentName:be.agentName,requesterAgentId:null,requesterAgentName:be.agentName??null,executorAgentId:null,executorAgentName:be.agentName??null,runId:null,initiativeId:null,timestamp:zt,metadata:{decisionId:be.id,action:K}})),q=sa(Mt.concat(Qe.activity),d);return{...Qe,decisions:Qe.decisions.filter(be=>!We.has(be.id)),activity:q,lastActivity:Pt(zt)}}):me.ok&&ge.length>0&&y(Qe=>({...Qe,decisions:Qe.decisions.filter(St=>!ge.includes(St.id))})),te();const ct=(ce==null?void 0:ce.updated)??We.size,Me=(ce==null?void 0:ce.failed)??Math.max(0,ge.length-We.size);return pe({phase:Me>0?"error":"success",action:K,targetCount:ge.length,message:Me>0?`${K==="approve"?"Approve":"Reject"} completed with ${Me} failure${Me===1?"":"s"}.`:K==="approve"?`Approved ${ct} decision${ct===1?"":"s"}.`:`Rejected ${ct} decision${ct===1?"":"s"}.`,startedAt:ye,completedAt:new Date().toISOString()},{autoResetMs:Me>0?8e3:4e3}),{updated:ct,failed:Me,firstError:L}}catch(ce){throw pe({phase:"error",action:K,targetCount:ge.length,message:ce instanceof Error?ce.message:"Decision update failed.",startedAt:ye,completedAt:new Date().toISOString()}),ce}},[r,te,d,h,pe,i]),Ce=o.useCallback(async(B,K)=>ne([B],"approve",K),[ne]),G=o.useCallback(async(B,K)=>ne([B],"reject",K),[ne]),R=o.useCallback(async()=>{let B=[];return y(K=>(B=K.decisions.map(re=>re.id),K)),B.length===0?{updated:0,failed:0}:ne(B,"approve")},[ne]),z=o.useCallback(async(B,K,re)=>ne(B,K,re?{note:re}:void 0),[ne]);return o.useEffect(()=>{r||pe(rr)},[r,pe]),o.useEffect(()=>{if(!t){E(!1),f(!1),X(null);return}if(i){te();return}if(te(),h){E(!0);return}const B=new URLSearchParams;h&&_s(B,h),b&&B.set("initiative",b);const K=B.toString()?`/orgx/api/live/stream?${B.toString()}`:"/orgx/api/live/stream",re=new EventSource(K),ge=new EventSource("/orgx/api/hooks/runtime/stream");let Se=null,oe=null,ye=null,me=null,O=[],U=null,Y;const ce=()=>{if(Y=void 0,Se){de.current=Date.now(),ie.current=!1;const Fe=Se;Se=null,ye=null,me=null,O=[],U=null,oe=null,le(Fe.sessions,Fe.activity,Fe.handoffs,Fe.decisions,Fe.sliceRuns,Fe.outbox,Fe.generatedAt,Fe.runtimeInstances,Fe.chat,Fe.v2);return}!ye&&!me&&!U&&!oe&&O.length===0||(de.current=Date.now(),ie.current=!1,y(Fe=>{var ct;let L=Fe;if(ye){const Me=Ti(ye,c),Qe=Ti(ko(L.sessions,Me),c);ye=null,No(L.sessions,Qe)||(L={...L,sessions:Qe})}if(me){const Me=Io(me,u);me=null,jo(L.handoffs,Me)||(L={...L,handoffs:Me})}if(U){const Me=_o(U,p);U=null,Ao(L.decisions,Me)||(L={...L,decisions:Me})}if(oe){const Me=Co(oe);oe=null,To(L.runtimeInstances,Me)||(L={...L,runtimeInstances:Me})}if(O.length>0){const Me=Fd(L.activity,O,d);O=[],Me!==L.activity&&(L={...L,activity:Me,lastActivity:(ct=Me[0])!=null&&ct.timestamp?Pt(Me[0].timestamp):L.lastActivity})}return L===Fe?Fe:L.connection==="connected"?L:{...L,connection:"connected"}}),X(null),f(!1))},qe=()=>{Y||(Y=setTimeout(ce,x))};re.onopen=()=>{de.current=Date.now(),ie.current=!1,E(!1),y(Fe=>Fe.connection==="connected"?Fe:{...Fe,connection:"connected"}),X(null)},re.onerror=()=>{if(ie.current){y(L=>L.connection==="disconnected"?L:{...L,connection:"disconnected"}),E(!1);return}const Fe=de.current>0&&Date.now()-de.current>yo;y(L=>L.connection===(Fe?"disconnected":"reconnecting")?L:{...L,connection:Fe?"disconnected":"reconnecting"}),E(!0)},re.addEventListener("snapshot",Fe=>{try{const L=JSON.parse(Fe.data),ct=typeof L.generatedAt=="string"&&L.generatedAt.length>0?L.generatedAt:new Date().toISOString();Se={sessions:L.sessions,activity:L.activity??[],handoffs:L.handoffs??[],decisions:L.decisions??null,sliceRuns:Array.isArray(L.sliceRuns)?Tr(L.sliceRuns):Array.isArray(L.projections)?Mo(cr(L.projections)):null,outbox:L.outbox??null,generatedAt:ct,runtimeInstances:Array.isArray(L.runtimeInstances)?L.runtimeInstances:null,chat:Cr(L.chat??null),v2:{workSliceProjections:Array.isArray(L.projections)?cr(L.projections):null,timelineNarrative:Array.isArray(L.timelineNarrative)?ra(L.timelineNarrative):null,nextUpByInitiative:Array.isArray(L.nextUpByInitiative)?aa(L.nextUpByInitiative):null,runningWorkSlices:typeof L.runningWorkSlices=="number"?L.runningWorkSlices:null,needsInputTotal:typeof L.needsInput=="number"?L.needsInput:null,failedActionableTotal:typeof L.failedActionable=="number"?L.failedActionable:null,completedTodayTotal:typeof L.completedToday=="number"?L.completedToday:null,consistencyFlags:Array.isArray(L.consistencyFlags)?L.consistencyFlags:null,dataHealth:L.dataHealth??null}},qe()}catch(L){X(L instanceof Error?L.message:"Invalid snapshot")}}),re.addEventListener("activity.appended",Fe=>{try{const L=JSON.parse(Fe.data);if(L.length===0)return;O=O.concat(L),qe()}catch{}}),re.addEventListener("session.updated",Fe=>{try{ye=JSON.parse(Fe.data),qe()}catch{}});const We=Fe=>{try{const L=JSON.parse(Fe.data);oe=Array.isArray(L)?L:[L],qe()}catch{}};return re.addEventListener("runtime.updated",We),ge.addEventListener("runtime.updated",We),re.addEventListener("handoff.updated",Fe=>{try{me=JSON.parse(Fe.data),qe()}catch{}}),re.addEventListener("decision.updated",Fe=>{try{U=JSON.parse(Fe.data),qe()}catch{}}),()=>{Y&&clearTimeout(Y),re.close(),ge.close()}},[le,x,t,r,te,d,p,u,c,b,h,i]),o.useEffect(()=>{if(!(!t||i||(Z.current&&clearInterval(Z.current),!D&&!!!h)))return Z.current=setInterval(te,s),()=>{Z.current&&clearInterval(Z.current)}},[t,te,h,s,D,i]),{data:I,isLoading:N,error:T,refetch:te,approveDecision:Ce,rejectDecision:G,approveAllDecisions:R,bulkDecisionAction:z,decisionMutation:j}}const Ki=[{id:"live",label:"Last hour",minutes:null},{id:"24h",label:"Today",minutes:null},{id:"7d",label:"This week",minutes:10080},{id:"custom",label:"Custom",minutes:null},{id:"all",label:"All",minutes:null}];function Jl(e){return Ki.find(t=>t.id===e)??Ki[0]}function Qi(e,t=Date.now()){if(e==="all")return null;if(e==="live")return t-60*6e4;if(e==="24h"){const i=new Date(t);return i.setHours(0,0,0,0),i.getTime()}if(e==="custom")return null;const s=Ki.find(i=>i.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function Zd(e,t=Date.now()){const s=Qi(e,t);return s?new Date(s).toISOString():null}const eu=new Set(["ungrouped","unscoped","unknown"]),tu="orgx.demo_mode",nu="orgx.show_synthetic_entities";function Xs(e){const t=(e??"").trim().toLowerCase();return!!(!t||eu.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Zt(){if(typeof window>"u")return!1;try{if(new URLSearchParams(window.location.search).get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(tu)==="1"}catch{return!1}}function su(){if(typeof window>"u")return!1;if(Zt())return!0;try{return window.localStorage.getItem(nu)==="1"}catch{return!1}}function iu(e){return Zt()?!0:!Xs(e)}function Ea(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Zl(e,t){const s=Ea(t.timestamp)-Ea(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function ru(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function au(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function ec(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=ru(e.metadata);return au(s,["initiative_id","initiativeId"])}function oa(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ra(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(e===null||t===null)return e===t;if(typeof e!="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let l=0;l<e.length;l+=1)if(!Ra(e[l],t[l]))return!1;return!0}const s=e,i=t,r=Object.keys(s).sort(),a=Object.keys(i).sort();if(r.length!==a.length)return!1;for(let l=0;l<r.length;l+=1){const c=r[l];if(c!==a[l]||!Ra(s[c],i[c]))return!1}return!0}const ou=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function pi(e,...t){}function lu(e,t,s,i){const r=new Map,a=t.sinceEpoch,l=t.untilEpoch;let c=0,d=0,u=0;for(const p of e??[]){if(!p||typeof p.id!="string")continue;if(s&&p.runId!==s){c++;continue}if(i&&ec(p)!==i){d++;continue}const x=Ea(p.timestamp);if(x){if(a!==null&&x<a){u++;continue}if(l!==null&&x>l){u++;continue}r.set(p.id,p)}}return pi("normalizeSeed",{inputCount:(e==null?void 0:e.length)??0,outputCount:r.size,runId:s,initiativeId:i,skippedRun:c,skippedInitiative:d,skippedTime:u,sinceEpoch:a?new Date(a).toISOString():null,untilEpoch:l?new Date(l).toISOString():null}),Array.from(r.values()).sort(Zl)}function Eo(e,t){if(t.length===0)return e;const s=new Map;for(const l of e)s.set(l.id,l);let i=0,r=0,a=!1;for(const l of t){const c=s.get(l.id);if(!c){s.set(l.id,l),a=!0,i++;continue}(c.timestamp!==l.timestamp||c.type!==l.type||c.title!==l.title||c.description!==l.description||c.summary!==l.summary||!Ra(c.metadata??null,l.metadata??null))&&(s.set(l.id,l),a=!0,r++)}return pi("mergeById",{currentCount:e.length,incomingCount:t.length,added:i,updated:r,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(Zl):e}function cu(e){const{seed:t,timeFilterId:s,customSinceIso:i=null,customUntilIso:r=null,runId:a=null,initiativeId:l=null,projectId:c=null,pageSize:d=50,demoMode:u=Zt()}=e,p=o.useMemo(()=>oa(a),[a]),x=o.useMemo(()=>oa(l),[l]),b=o.useMemo(()=>oa(c),[c]),h=o.useMemo(()=>Qi(s),[s]),I=o.useMemo(()=>Zd(s),[s]),y=o.useMemo(()=>{if(s==="custom"){const R=(i==null?void 0:i.trim())??"";return R.length>0?R:null}return I},[i,I,s]),j=o.useMemo(()=>{if(s!=="custom")return null;const R=(r==null?void 0:r.trim())??"";return R.length>0?R:null},[r,s]),w=o.useMemo(()=>{if(y){const R=Date.parse(y);if(Number.isFinite(R))return R}return h},[h,y]),N=o.useMemo(()=>{if(!j)return null;const R=Date.parse(j);return Number.isFinite(R)?R:null},[j]),f=o.useMemo(()=>lu(t,{sinceEpoch:w,untilEpoch:N},p,x),[t,w,N,p,x]),T=u?null:"",[X,Z]=o.useState(f),[W,ke]=o.useState(()=>T),[D,E]=o.useState(!1),[de,ie]=o.useState(null),[we,ae]=o.useState(null),ze=o.useRef(null),pe=o.useRef(!1),le=o.useRef(f);le.current=f;const te=o.useMemo(()=>`${p??""}|${x??""}|${s}|${y??""}|${j??""}|${b??""}|${u?"demo":"live"}`,[p,x,s,y,j,b,u]),ne=o.useRef(te);o.useEffect(()=>{ne.current!==te&&(ne.current=te,pi("RESET",{reason:"filter/run change",runId:p,initiativeId:x,projectId:b,timeFilterId:s,sinceIso:y,untilIso:j,seedCount:le.current.length}),Z(le.current),ke(T),ie(null),ae(null),pe.current=!1)},[te,T,p,x,b,s,y,j]),o.useEffect(()=>{Z(R=>{const z=Eo(R,f);return z!==R&&pi("SSE_MERGE",{prevCount:R.length,seedCount:f.length,nextCount:z.length,delta:z.length-R.length}),z})},[f]);const Ce=o.useCallback(async()=>{if(u){ke(null),ie(null);return}if(W===null)return;if(ze.current)return ze.current;E(!0);const R=(async()=>{try{const z=new URLSearchParams;z.set("limit",String(Math.max(1,Math.min(500,d)))),W.trim().length>0&&z.set("cursor",W),y&&z.set("since",y),j&&z.set("until",j),p&&z.set("run",p),x&&z.set("initiative",x),b&&_s(z,b);const B=await fetch(`/orgx/api/live/activity/page?${z.toString()}`,{headers:Ht({workspaceId:b})}),K=await B.json().catch(()=>null);if(!B.ok||!K){const Se=typeof(K==null?void 0:K.error)=="string"&&K.error.trim()||typeof(K==null?void 0:K.message)=="string"&&K.message.trim()||`Activity paging failed (${B.status})`;throw new Error(Se)}const re=Array.isArray(K.activities)?K.activities:[],ge=re.filter(Se=>!x||ec(Se)===x);pi("PAGE_FETCH",{cursor:W,rawCount:re.length,afterFilter:ge.length,filteredOut:re.length-ge.length,initiativeId:x,runId:p,nextCursor:K.nextCursor??null}),Z(Se=>{const oe=Eo(Se,ge);return pi("PAGE_MERGE",{prevCount:Se.length,pageCount:ge.length,nextCount:oe.length,added:oe.length-Se.length}),oe}),ke(K.nextCursor??null),ae(K.storeUpdatedAt??null),ie(null)}catch(z){const B=z instanceof Error?z.message:"";ie(B?Xt(B):"Activity paging failed"),ke(K=>K===""?null:K)}finally{E(!1),ze.current=null}})();return ze.current=R,R},[W,u,x,d,b,p,y,j]);return o.useEffect(()=>{W===""&&(pe.current||(pe.current=!0,Ce()))},[W,Ce]),{items:X,hasMore:W!==null,isLoadingMore:D,error:de,storeUpdatedAt:we,loadMore:Ce,cutoffEpoch:w,sinceIso:y,untilIso:j}}const du="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",uu="".trim().toLowerCase()==="true"||"".trim()==="1",mu="".trim().toLowerCase()==="true"||"".trim()==="1",pu={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let la=null,Ro=!1,Lo=!1,Ka=!1;function fu(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Vr(){return Ka||!uu?!1:mu?!0:!fu()}function hu(){return Vr()?(la||(la=un(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(Ka=!0,null))),la):Promise.resolve(null)}function gu(e){if(Ro)return!0;try{return e.init(du,pu),Ro=!0,!0}catch{return Ka=!0,!1}}async function Va(){const e=await hu();return!e||!gu(e)?null:e}function xu(e){if(typeof window>"u")return;const t=window;if(typeof t.requestIdleCallback=="function"){t.requestIdleCallback(()=>e(),{timeout:1500});return}window.setTimeout(e,1)}function yu(){!Vr()||typeof window>"u"||Lo||(Lo=!0,xu(()=>{Va()}))}function bu(e){if(!Vr())return;const t=e.trim();t&&Va().then(s=>{if(s)try{s.identify(t)}catch{}})}function vs(e,t){Vr()&&e.trim()&&Va().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const vu="https://orgx.mintlify.site/guides/openclaw-plugin-setup",wu=1500,ca="orgx.onboarding.skip",ku=680,Iu=`<!doctype html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="utf-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
7
+ <title>Connecting to OrgX</title>
8
+ <style>
9
+ :root {
10
+ --bg: #02040a;
11
+ --surface: #0c0e14;
12
+ --surface-soft: #0f121a;
13
+ --line: rgba(255, 255, 255, 0.1);
14
+ --text: #f2f7ff;
15
+ --muted: rgba(242, 247, 255, 0.62);
16
+ --lime: #bfff00;
17
+ --teal: #14b8a6;
18
+ --iris: #7c7cff;
19
+ }
20
+
21
+ * { box-sizing: border-box; }
22
+
23
+ body {
24
+ margin: 0;
25
+ min-height: 100vh;
26
+ background:
27
+ radial-gradient(920px 460px at 14% 14%, rgba(124, 124, 255, 0.12), transparent 68%),
28
+ radial-gradient(840px 420px at 84% 88%, rgba(20, 184, 166, 0.12), transparent 72%),
29
+ var(--bg);
30
+ color: var(--text);
31
+ font-family: "SF Pro Text", "SF Pro Display", Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
32
+ display: grid;
33
+ place-items: center;
34
+ padding: 24px;
35
+ }
36
+
37
+ .shell {
38
+ width: min(640px, 100%);
39
+ border-radius: 22px;
40
+ border: 1px solid var(--line);
41
+ background:
42
+ linear-gradient(180deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.015)),
43
+ var(--surface);
44
+ box-shadow:
45
+ 0 28px 80px rgba(0, 0, 0, 0.58),
46
+ inset 0 1px 0 rgba(255, 255, 255, 0.05);
47
+ overflow: hidden;
48
+ }
49
+
50
+ .header {
51
+ display: flex;
52
+ align-items: center;
53
+ justify-content: space-between;
54
+ gap: 12px;
55
+ padding: 16px 18px;
56
+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);
57
+ background: rgba(0, 0, 0, 0.16);
58
+ }
59
+
60
+ .brand {
61
+ display: inline-flex;
62
+ align-items: center;
63
+ gap: 10px;
64
+ }
65
+
66
+ .brand-mark {
67
+ width: 22px;
68
+ height: 22px;
69
+ color: var(--lime);
70
+ opacity: 0.95;
71
+ }
72
+
73
+ .brand-name {
74
+ font-size: 14px;
75
+ font-weight: 700;
76
+ letter-spacing: 0.01em;
77
+ color: rgba(242, 247, 255, 0.92);
78
+ }
79
+
80
+ .chip {
81
+ display: inline-flex;
82
+ align-items: center;
83
+ gap: 6px;
84
+ border: 1px solid rgba(191, 255, 0, 0.3);
85
+ background: rgba(191, 255, 0, 0.12);
86
+ color: #d8ffa1;
87
+ border-radius: 999px;
88
+ padding: 4px 10px;
89
+ font-size: 11px;
90
+ font-weight: 600;
91
+ letter-spacing: 0.06em;
92
+ text-transform: uppercase;
93
+ }
94
+
95
+ .dot {
96
+ width: 7px;
97
+ height: 7px;
98
+ border-radius: 50%;
99
+ background: var(--lime);
100
+ box-shadow: 0 0 0 0 rgba(191, 255, 0, 0.56);
101
+ animation: pulse 1.6s infinite ease-out;
102
+ }
103
+
104
+ .content {
105
+ padding: 20px 20px 18px;
106
+ }
107
+
108
+ h1 {
109
+ margin: 0;
110
+ font-size: 24px;
111
+ line-height: 1.18;
112
+ letter-spacing: -0.02em;
113
+ }
114
+
115
+ .subtitle {
116
+ margin: 8px 0 0;
117
+ color: var(--muted);
118
+ font-size: 14px;
119
+ line-height: 1.5;
120
+ }
121
+
122
+ .steps {
123
+ margin-top: 16px;
124
+ display: grid;
125
+ gap: 8px;
126
+ }
127
+
128
+ .step {
129
+ display: flex;
130
+ align-items: center;
131
+ gap: 9px;
132
+ border: 1px solid rgba(255, 255, 255, 0.08);
133
+ background: var(--surface-soft);
134
+ border-radius: 12px;
135
+ padding: 10px 12px;
136
+ font-size: 12px;
137
+ }
138
+
139
+ .step svg {
140
+ flex-shrink: 0;
141
+ width: 14px;
142
+ height: 14px;
143
+ }
144
+
145
+ .meta {
146
+ margin-top: 12px;
147
+ padding-top: 12px;
148
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
149
+ color: rgba(242, 247, 255, 0.42);
150
+ font-size: 11px;
151
+ }
152
+
153
+ @keyframes pulse {
154
+ 0% { box-shadow: 0 0 0 0 rgba(191, 255, 0, 0.56); }
155
+ 100% { box-shadow: 0 0 0 12px rgba(191, 255, 0, 0); }
156
+ }
157
+ </style>
158
+ </head>
159
+ <body>
160
+ <main class="shell">
161
+ <header class="header">
162
+ <div class="brand">
163
+ <svg class="brand-mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
164
+ <path d="M5.5 7h5.8l6.7 6"></path>
165
+ <path d="M5.5 17h5.8l6.7-6"></path>
166
+ <path d="M5.5 12h12.5"></path>
167
+ <path d="m15.3 9.3 2.7 2.7-2.7 2.7"></path>
168
+ </svg>
169
+ <span class="brand-name">OrgX</span>
170
+ </div>
171
+ <div class="chip"><span class="dot"></span>Pairing</div>
172
+ </header>
173
+ <section class="content">
174
+ <h1>Connecting to OrgX</h1>
175
+ <p class="subtitle">Preparing a secure workspace session. This window will continue automatically.</p>
176
+ <div class="steps">
177
+ <div class="step">
178
+ <svg viewBox="0 0 24 24" fill="none" stroke="#7C7CFF" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
179
+ <circle cx="12" cy="12" r="9"></circle>
180
+ <circle cx="12" cy="12" r="4.5"></circle>
181
+ </svg>
182
+ <span>Initializing plugin handshake</span>
183
+ </div>
184
+ <div class="step">
185
+ <svg viewBox="0 0 24 24" fill="none" stroke="#14B8A6" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
186
+ <path d="M5 3v18"></path>
187
+ <path d="m5 4 12 1-2 4 2 4-12-1z"></path>
188
+ </svg>
189
+ <span>Opening browser approval for this workspace</span>
190
+ </div>
191
+ <div class="step">
192
+ <svg viewBox="0 0 24 24" fill="none" stroke="#BFFF00" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
193
+ <rect x="4" y="4" width="16" height="16" rx="4"></rect>
194
+ <path d="M9 12.2 11 14.2 15.2 10"></path>
195
+ </svg>
196
+ <span>Syncing initiatives, tasks, and decisions</span>
197
+ </div>
198
+ </div>
199
+ <div class="meta">If redirect does not start, return to OpenClaw and click “Approve in browser”.</div>
200
+ </section>
201
+ </main>
202
+ </body>
203
+ </html>`,Mr={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:vu,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function ai(){return{...Mr,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function da(e){if(typeof e=="string")return Xt(e);if(e&&typeof e=="object"){const t=e;if(typeof t.error=="string")return Xt(t.error);if(typeof t.message=="string")return Xt(t.message)}}async function Mi(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:da(s==null?void 0:s.error)??da(s==null?void 0:s.message)??da(s)??Xt(`Request failed (${t.status})`)}}function dr(e){if(e)try{bu(e)}catch{}}function Nu(){const[e,t]=o.useState(()=>Zt()?ai():Mr),[s,i]=o.useState(()=>!Zt()),[r,a]=o.useState(!1),[l,c]=o.useState(!1),d=o.useRef(null),[u,p]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(ca)==="1"),x=o.useCallback(async()=>{if(Zt()){const f=ai();return t(f),f}const N=await Mi(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!N.ok||!N.data){const f=N.error??"Failed to load onboarding state",T={...Mr,status:"error",lastError:f,nextAction:"retry"};return t(T),T}return dr(N.data.installationId??null),t(N.data),N.data},[]);o.useEffect(()=>{if(Zt()){t(ai()),i(!1);return}let N=!1;return(async()=>{i(!0);const f=await x();N||(t(f),i(!1))})(),()=>{N=!0}},[x]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const f=Math.max(900,e.pollIntervalMs??wu),T=window.setInterval(async()=>{const X=await Mi(fetch("/orgx/api/onboarding/status",{method:"GET"}));X.ok&&X.data&&(dr(X.data.installationId??null),t(X.data))},f);return()=>{window.clearInterval(T)}},[e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(u){window.localStorage.setItem(ca,"1");return}window.localStorage.removeItem(ca)}},[u]);const b=o.useCallback(()=>{if(typeof window>"u")return null;try{const N=window.open("","_blank");return N?(N.opener=null,N.document.title="Connecting to OrgX…",N.document.open(),N.document.write(Iu),N.document.close(),N):null}catch{return null}},[]),h=o.useCallback(async()=>{if(Zt()){const f=ai();t(f);return}const N=b();d.current=N,a(!0);try{const f=await Mi(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),T=f.data;if(!f.ok||!(T!=null&&T.state)){N&&!N.closed&&N.close();const Z=f.error??"Could not start pairing";t(W=>({...W,status:"error",lastError:Z,nextAction:"enter_manual_key"}));return}t(T.state);const X=T.connectUrl;if(X){const Z=d.current;let W=!1;if(Z&&!Z.closed)try{window.setTimeout(()=>{if(!Z.closed)try{Z.location.href=X}catch{}},ku),W=!0}catch{W=!1}W||(W=!!window.open(X,"_blank","noopener,noreferrer")),W||t(ke=>({...ke,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{d.current=null,a(!1)}},[b]),I=o.useCallback(async N=>{if(Zt()){const f=ai();return t(f),f}c(!0);try{const f=N.trim(),T=f.replace(/^[a-z]+_/i,""),X=Array.from(new Set([f,T?`oxk_${T}`:"",T?`orgx_${T}`:""].map(W=>W.trim()).filter(W=>W.length>0)));let Z="Manual key validation failed";for(const W of X){const ke={"Content-Type":"application/json","X-OrgX-Api-Key":W,Authorization:`Bearer ${W}`},D=await Mi(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:ke,body:JSON.stringify({apiKey:W})}));if(D.ok&&D.data)return dr(D.data.installationId??null),t(D.data),D.data;Z=D.error??Z}throw t(W=>({...W,status:"manual_key",lastError:Z,nextAction:"enter_manual_key"})),new Error(Z)}finally{c(!1)}},[]),y=o.useCallback(async()=>{if(Zt()){const T=ai();return t(T),T}const N=await Mi(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(N.ok&&N.data)return dr(N.data.installationId??null),t(N.data),N.data;const f={...Mr,status:"idle"};return t(f),f},[]),j=o.useCallback(()=>{t(N=>({...N,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),w=o.useMemo(()=>Zt()||u?!1:!(e.hasApiKey&&e.connectionVerified&&e.status==="connected"),[u,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:w,isLoading:s,isStarting:r,isSubmittingManual:l,refreshStatus:x,startPairing:h,submitManualKey:I,disconnect:y,skipGate:()=>p(!0),resumeGate:()=>p(!1),backToPairing:j,setManualMode:()=>t(N=>({...N,status:"manual_key",nextAction:"enter_manual_key"}))}}const Ns={liveData:e=>["live-data",{authToken:e.authToken??null,embedMode:e.embedMode??!1,useMock:e.useMock??!1,projectId:e.projectId??null}],sessions:e=>["sessions",{activeMinutes:e.activeMinutes??null,limit:e.limit??null,authToken:e.authToken??null,embedMode:e.embedMode??!1}],initiativeDetails:e=>["initiative-details",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],entities:e=>["entities",{type:e.type,authToken:e.authToken??null,embedMode:e.embedMode??!1,projectId:e.projectId??null}],missionControlGraph:e=>["mission-control-graph",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],missionControlSlices:e=>{var t;return["mission-control-slices",{workspaceId:e.workspaceId??null,initiativeId:e.initiativeId??null,level:e.level,orderMode:e.orderMode??null,includeCompleted:e.includeCompleted??!1,search:((t=e.search)==null?void 0:t.trim().toLowerCase())??"",offset:Math.max(0,e.offset??0),limit:Math.max(1,e.limit??24),authToken:e.authToken??null,embedMode:e.embedMode??!1}]},nextUpQueue:e=>["mission-control-next-up",{initiativeId:e.initiativeId??null,authToken:e.authToken??null,embedMode:e.embedMode??!1,projectId:e.projectId??null,offset:Math.max(0,e.offset??0),limit:Math.max(1,Math.min(300,e.limit??24))}],autoContinueStatus:e=>["auto-continue-status",{initiativeId:e.initiativeId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],liveInitiatives:e=>["live-initiatives",{limit:(e==null?void 0:e.limit)??300,projectId:(e==null?void 0:e.projectId)??null}],initiativeSearch:e=>["initiative-search",{query:e.query.trim().toLowerCase(),projectId:e.projectId??null}],artifactsByEntity:e=>["artifacts-by-entity",{entityType:e.entityType,entityId:e.entityId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],artifactDetail:e=>["artifact-detail",{artifactId:e.artifactId,authToken:e.authToken??null,embedMode:e.embedMode??!1}],triageQueue:e=>["triage-queue",{workspaceId:e.workspaceId??null,status:e.status??"open",authToken:e.authToken??null,embedMode:e.embedMode??!1}]};class ju extends Error{constructor(s,i){super(s);Yn(this,"code","upgrade_required");Yn(this,"currentPlan");Yn(this,"requiredPlan");Yn(this,"actions");this.name="UpgradeRequiredError",this.currentPlan=(i==null?void 0:i.currentPlan)??null,this.requiredPlan=((i==null?void 0:i.requiredPlan)??"starter").trim()||"starter",this.actions=(i==null?void 0:i.actions)??null}}function Au(e){if(!e||typeof e!="object")return null;const t=e;if(t.code!=="upgrade_required")return null;const s=typeof t.error=="string"&&t.error.trim()?t.error.trim():"Upgrade required.";return new ju(s,{currentPlan:typeof t.currentPlan=="string"&&t.currentPlan.trim()?t.currentPlan.trim():null,requiredPlan:typeof t.requiredPlan=="string"&&t.requiredPlan.trim()?t.requiredPlan.trim():null,actions:t.actions??null})}function mx(e){const t=(e??"").trim().toLowerCase();return t?t==="free"?"Free":t==="starter"?"Starter":t==="team"?"Team":t==="enterprise"?"Enterprise":t[0].toUpperCase()+t.slice(1):"Unknown"}class tc extends Error{constructor(s){super(s.message);Yn(this,"status");Yn(this,"code");Yn(this,"errorLocation");Yn(this,"retryable");Yn(this,"details");this.name="MissionControlApiError",this.status=s.status,this.code=s.code??null,this.errorLocation=s.errorLocation??null,this.retryable=s.retryable??!1,this.details=s.details??null}}function _u(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Vi(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function Su(e,t){if(e.status!==404)return!1;const s=Vi(t,["error"])??"",i=Vi(t,["message"])??"";return/unknown api endpoint/i.test(`${s} ${i}`)}function Cu(e,t,s){if(Su(e,t))return`${s}. This queue control is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable.`;const i=Vi(t,["error","message"])??`${s} (${e.status})`;return Xt(i)}function ua(e,t,s){const i=_u(t),r=Cu(e,i,s),a=Vi(i,["code"]),l=Vi(i,["error_location","errorLocation"]),c=i==null?void 0:i.retryable,d=typeof c=="boolean"?c:!1;return new tc({message:r,status:e.status,code:a,errorLocation:l,retryable:d,details:i})}function px(e){return e instanceof tc}const Tu=750;async function Ei(e){return await e.json().catch(()=>null)}function Mu(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",i=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${i}`)}function Eu(e,t,s){if(Mu(e,t))return`${s}. This queue route is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable.`;const i=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||s;return Xt(i)}function Ru(e,t){const s=e instanceof Error?e.message:"",i=s.trim().toLowerCase();return i.includes("timed out")||i.includes("timeout")||i.includes("request cancelled")||i.includes("signal is aborted")?`${t}. Request timed out while waiting for queue data.`:i.includes("failed to fetch")||i.includes("network")?`${t}. Unable to reach the queue service right now.`:s?Xt(s):t}function Lu(e){const t=new Date().toISOString(),s=l=>new Date(Date.now()-l*6e4).toISOString(),i=(l,c,d)=>({status:l,activeTaskId:(d==null?void 0:d.activeTaskId)??null,activeRunId:(d==null?void 0:d.activeRunId)??null,stopReason:(d==null?void 0:d.stopReason)??null,maxParallelSlices:(d==null?void 0:d.maxParallelSlices)??3,parallelMode:(d==null?void 0:d.parallelMode)??"iwmt",updatedAt:c}),r=[{initiativeId:"init-1",initiativeTitle:"Content Engine: Dogfood the Larry Playbook",initiativeStatus:"active",initiativePriority:"critical",initiativePriorityNum:11,workstreamId:"ws-content-1",workstreamTitle:"Long-form article generation",workstreamStatus:"in_progress",nextTaskId:"task-content-13",nextTaskTitle:"Apply editorial revisions for sections 3-4",nextTaskPriority:1,nextTaskDueAt:s(-35),runnerAgentId:"kimi",runnerAgentName:"Kimi",runnerAgents:[{id:"kimi",name:"Kimi"}],runnerSource:"assigned",queueState:"running",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-content-12","task-content-13"],sliceTaskCount:2,executionPolicy:{domain:"content",requiredSkills:["editorial-review","voice-consistency"],profile:"quality-first",sliceScopePreference:"task",maxSliceTasks:2,maxParallelAgents:2,dependencyMode:"strict"},autoContinue:i("running",s(4),{activeTaskId:"task-content-13",activeRunId:"run-101",maxParallelSlices:2})},{initiativeId:"init-1",initiativeTitle:"Content Engine: Dogfood the Larry Playbook",initiativeStatus:"active",initiativePriority:"critical",initiativePriorityNum:12,workstreamId:"ws-content-legal",workstreamTitle:"Persona QA and legal sweep",workstreamStatus:"blocked",nextTaskId:"task-legal-2",nextTaskTitle:"Approve legal-safe copy variant",nextTaskPriority:1,nextTaskDueAt:s(-20),runnerAgentId:"holt",runnerAgentName:"Holt",runnerAgents:[{id:"holt",name:"Holt"}],runnerSource:"assigned",queueState:"blocked",blockReason:"Waiting on legal-safe variant decision from you",queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-legal-2"],sliceTaskCount:1,autoContinue:i("stopped",s(7),{stopReason:"blocked",maxParallelSlices:2})},{initiativeId:"init-2",initiativeTitle:"Live View UX Redesign — The Conductor's Display",initiativeStatus:"active",initiativePriority:"high",initiativePriorityNum:24,workstreamId:"ws-ux-devmode",workstreamTitle:"Developer-mode feature gating",workstreamStatus:"in_progress",nextTaskId:"task-ux-33",nextTaskTitle:"Capture final mobile + desktop verification",nextTaskPriority:1,nextTaskDueAt:s(-15),runnerAgentId:"holt",runnerAgentName:"Holt",runnerAgents:[{id:"holt",name:"Holt"}],runnerSource:"assigned",queueState:"running",blockReason:null,queueOrigin:"system",sliceScope:"workstream",sliceTaskIds:["task-ux-31","task-ux-32","task-ux-33"],sliceTaskCount:3,autoContinue:i("running",s(2),{activeTaskId:"task-ux-33",activeRunId:"run-202"})},{initiativeId:"init-2",initiativeTitle:"Live View UX Redesign — The Conductor's Display",initiativeStatus:"active",initiativePriority:"high",initiativePriorityNum:26,workstreamId:"ws-ux-activity",workstreamTitle:"Activity feed readability pass",workstreamStatus:"in_progress",nextTaskId:"task-ux-19",nextTaskTitle:"Finalize hierarchy labels and evidence chips",nextTaskPriority:2,nextTaskDueAt:s(-28),runnerAgentId:"dana",runnerAgentName:"Dana",runnerAgents:[{id:"dana",name:"Dana"}],runnerSource:"assigned",queueState:"queued",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-ux-18","task-ux-19"],sliceTaskCount:2,autoContinue:i("running",s(6),{activeTaskId:"task-ux-19",activeRunId:"run-201"})},{initiativeId:"init-2",initiativeTitle:"Live View UX Redesign — The Conductor's Display",initiativeStatus:"active",initiativePriority:"high",initiativePriorityNum:27,workstreamId:"ws-ux-collapse",workstreamTitle:"Grouped section collapse spacing regression",workstreamStatus:"blocked",nextTaskId:"task-ux-41",nextTaskTitle:"Apply approved collapsed spacing token",nextTaskPriority:1,nextTaskDueAt:s(-12),runnerAgentId:"kimi",runnerAgentName:"Kimi",runnerAgents:[{id:"kimi",name:"Kimi"}],runnerSource:"assigned",queueState:"blocked",blockReason:"Decision required: choose 8px or 0px collapsed spacing",queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-ux-41"],sliceTaskCount:1,autoContinue:i("stopped",s(2),{stopReason:"blocked"})},{initiativeId:"init-3",initiativeTitle:"Directory Submissions & External References",initiativeStatus:"active",initiativePriority:"medium",initiativePriorityNum:41,workstreamId:"ws-directory-import",workstreamTitle:"Enrichment import pipeline",workstreamStatus:"in_progress",nextTaskId:"task-dir-12",nextTaskTitle:"Finish vendor retry batch after cooldown",nextTaskPriority:2,nextTaskDueAt:s(-45),runnerAgentId:"pace",runnerAgentName:"Pace",runnerAgents:[{id:"pace",name:"Pace"}],runnerSource:"assigned",queueState:"running",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-dir-11","task-dir-12"],sliceTaskCount:2,autoContinue:i("running",s(3),{activeTaskId:"task-dir-12",activeRunId:"run-301"})},{initiativeId:"init-3",initiativeTitle:"Directory Submissions & External References",initiativeStatus:"active",initiativePriority:"medium",initiativePriorityNum:43,workstreamId:"ws-directory-qa",workstreamTitle:"Reference verification QA lane",workstreamStatus:"in_progress",nextTaskId:"task-dir-qa-2",nextTaskTitle:"Reconcile citation mismatches and publish QA memo",nextTaskPriority:2,nextTaskDueAt:s(-38),runnerAgentId:"kimi",runnerAgentName:"Kimi",runnerAgents:[{id:"kimi",name:"Kimi"}],runnerSource:"assigned",queueState:"queued",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-dir-qa-1","task-dir-qa-2"],sliceTaskCount:2,autoContinue:i("running",s(5),{activeTaskId:"task-dir-qa-2",activeRunId:"run-302"})},{initiativeId:"init-3",initiativeTitle:"Directory Submissions & External References",initiativeStatus:"active",initiativePriority:"medium",initiativePriorityNum:45,workstreamId:"ws-directory-outreach",workstreamTitle:"External partner outreach copy",workstreamStatus:"in_progress",nextTaskId:"task-dir-outreach-2",nextTaskTitle:"Finalize outreach sequence copy",nextTaskPriority:3,nextTaskDueAt:s(-52),runnerAgentId:"mark",runnerAgentName:"Mark",runnerAgents:[{id:"mark",name:"Mark"}],runnerSource:"assigned",queueState:"queued",blockReason:null,queueOrigin:"system",sliceScope:"task",sliceTaskIds:["task-dir-outreach-1","task-dir-outreach-2"],sliceTaskCount:2,autoContinue:i("running",s(8),{activeTaskId:"task-dir-outreach-2",activeRunId:"run-303"})},{initiativeId:"init-5",initiativeTitle:"Incident Replay & Reliability",initiativeStatus:"blocked",initiativePriority:"critical",initiativePriorityNum:8,workstreamId:"ws-reliability-replay",workstreamTitle:"Incident replay reconstruction",workstreamStatus:"blocked",nextTaskId:"task-rel-44",nextTaskTitle:"Approve snapshot restore and rerun replay",nextTaskPriority:1,nextTaskDueAt:s(-10),runnerAgentId:"ops",runnerAgentName:"Ops",runnerAgents:[{id:"ops",name:"Ops"}],runnerSource:"assigned",queueState:"blocked",blockReason:"Archive restore approval needed to continue replay",queueOrigin:"system",sliceScope:"milestone",sliceTaskIds:["task-rel-44"],sliceTaskCount:1,sliceMilestoneId:"mile-rel-9",autoContinue:i("stopped",s(25),{stopReason:"blocked",maxParallelSlices:1})},{initiativeId:"init-4",initiativeTitle:"Revenue Expansion Q2",initiativeStatus:"completed",initiativePriority:"low",initiativePriorityNum:74,workstreamId:"ws-revenue-closeout",workstreamTitle:"Revenue Expansion Q2 closeout",workstreamStatus:"completed",nextTaskId:null,nextTaskTitle:"Completed",nextTaskPriority:null,nextTaskDueAt:null,runnerAgentId:"mark",runnerAgentName:"Mark",runnerAgents:[{id:"mark",name:"Mark"}],runnerSource:"assigned",queueState:"completed",blockReason:null,queueOrigin:"system",sliceScope:"milestone",sliceTaskIds:["task-revenue-19"],sliceTaskCount:1,sliceMilestoneId:"mile-revenue-4",autoContinue:i("stopped",s(40),{stopReason:"completed",maxParallelSlices:1})}],a=typeof e=="string"&&e.trim().length>0?r.filter(l=>l.initiativeId===e.trim()):r;return Er({ok:!0,generatedAt:t,total:a.length,items:a,pagination:{offset:0,limit:a.length||1,total:a.length,nextCursor:null,hasMore:!1},degraded:[]})}function Du(e){var s,i;const t=((s=e.autoContinue)==null?void 0:s.status)??"stopped";return t==="running"?"running":t==="stopping"?"stopping":((i=e.autoContinue)==null?void 0:i.stopReason)==="error"?"error":"idle"}function $u(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;return!(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")}function Ga(e){const t=typeof e=="string"?e.trim():"";if(!t)return"unassigned";const s=t.toLowerCase();return s==="undefined"||s==="null"||s==="main"?"unassigned":t}function Xa(e,t){const s=typeof e=="string"?e.trim():"";if(!s)return t==="unassigned"?"Unassigned":t;const i=s.toLowerCase();return i==="undefined"||i==="null"||i==="main"&&t==="unassigned"?t==="unassigned"?"Unassigned":t:s}function nc(e,t,s){if(!Array.isArray(e))return t==="unassigned"?[]:[{id:t,name:s}];const i=[],r=new Set;for(const a of e){if(!a||typeof a!="object"||Array.isArray(a))continue;const l=a,c=Ga(typeof l.id=="string"?l.id:null),d=Xa(typeof l.name=="string"?l.name:null,c);if(c==="unassigned"&&d==="Unassigned")continue;const u=c.toLowerCase();r.has(u)||(r.add(u),i.push({id:c,name:d}))}return i.length===0&&t!=="unassigned"?[{id:t,name:s}]:i}function Pu(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function Fu(e){const t=Ga(e.runnerAgentId),s=Xa(e.runnerAgentName,t),i=nc(e.runnerAgents,t,s),r=i[0]??null,a=(r==null?void 0:r.id)??t,l=(r==null?void 0:r.name)??s,c=Pu(e.runnerSource,a),d=Array.isArray(e.sliceTaskIds)&&e.sliceTaskIds.length>0?e.sliceTaskIds.filter(p=>typeof p=="string"&&p.trim().length>0):e.nextTaskId?[e.nextTaskId]:[],u=e.sliceScope==="workstream"||e.sliceScope==="milestone"||e.sliceScope==="task"?e.sliceScope:null;return{...e,runnerAgentId:a,runnerAgentName:l,runnerAgents:i,runnerSource:c,playbackState:e.queueState,autoIntentEnabled:$u(e),autoRuntimeState:Du(e),queueOrigin:e.queueOrigin??"system",sliceScope:u,sliceTaskIds:d,sliceTaskCount:typeof e.sliceTaskCount=="number"&&Number.isFinite(e.sliceTaskCount)?Math.max(0,Math.floor(e.sliceTaskCount)):d.length,executionPolicy:e.executionPolicy??null}}function Er(e){const t=e.items.map(u=>Fu(u)),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(e.total,t.length):t.length,i=e.pagination&&typeof e.pagination=="object"?e.pagination:null,r=i&&Number.isFinite(i.offset)?Math.max(0,Math.floor(i.offset)):0,a=i&&Number.isFinite(i.limit)?Math.max(1,Math.floor(i.limit)):Math.max(1,t.length),l=r+a<s,c=i&&typeof i.hasMore=="boolean"?i.hasMore:l,d=i&&typeof i.nextCursor=="string"?i.nextCursor:c?String(r+a):null;return{...e,items:t,total:s,pagination:{offset:r,limit:a,total:s,nextCursor:d,hasMore:c}}}function Ou(e){const t=(e.queueState??"").trim().toLowerCase();if(t==="queued"||t==="running"||t==="blocked"||t==="idle"||t==="completed")return t;const s=e.status.trim().toLowerCase();return s==="running"||s==="in_progress"||s==="dispatching"?"running":s==="active"?"queued":e.runnable===!1||s==="blocked"||s==="failed"||s==="error"?"blocked":s==="completed"||s==="done"||s==="resolved"?"completed":"queued"}function qu(e){if(!e)return"Workstream";const t=e.trim();return t.length===0?"Workstream":/^[a-f0-9-]{16,}$/i.test(t)?`Workstream ${t.slice(0,8)}`:t}function Bu(e){var b,h,I,y,j,w,N,f,T,X,Z,W,ke,D,E,de;const t=(e.sliceKind??"").trim().toLowerCase();if(t&&t!=="work_slice")return null;const s=((h=(b=e.lineage)==null?void 0:b.initiativeIds)==null?void 0:h.filter(ie=>typeof ie=="string"&&ie.trim().length>0))??[],i=((y=(I=e.lineage)==null?void 0:I.workstreamIds)==null?void 0:y.filter(ie=>typeof ie=="string"&&ie.trim().length>0))??[],r=((j=e.initiativeId)==null?void 0:j.trim())||s[0]||null,a=((w=e.workstreamId)==null?void 0:w.trim())||((f=(N=e.sourceWorkstreamIds)==null?void 0:N.find(ie=>typeof ie=="string"&&ie.trim().length>0))==null?void 0:f.trim())||i[0]||null;if(!r||!a)return null;const l=((X=(T=e.lineage)==null?void 0:T.taskIds)==null?void 0:X.filter(ie=>typeof ie=="string"&&ie.trim().length>0))??[],c=e.level==="workstream"||e.level==="milestone"||e.level==="task"?e.level:null,d=Ga(e.runnerAgentId??null),u=Xa(e.runnerAgentName??null,d),p=nc(e.runnerAgents??null,d,u),x=p[0]??null;return{initiativeId:r,initiativeTitle:((Z=e.initiativeTitle)==null?void 0:Z.trim())||s[0]||r,initiativeStatus:"active",initiativePriority:null,initiativePriorityNum:null,workstreamId:a,workstreamTitle:((W=e.workstreamTitle)==null?void 0:W.trim())||((ke=e.title)==null?void 0:ke.trim())||((D=e.milestoneTitle)==null?void 0:D.trim())||((E=e.taskTitle)==null?void 0:E.trim())||qu(a),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((de=e.taskTitle)==null?void 0:de.trim())||null,nextTaskPriority:typeof e.priorityNum=="number"?e.priorityNum:null,nextTaskDueAt:e.dueAt,runnerAgentId:(x==null?void 0:x.id)??d,runnerAgentName:(x==null?void 0:x.name)??u,runnerAgents:p,runnerSource:e.runnerSource??(x?"inferred":"fallback"),queueState:Ou(e),blockReason:e.blockReason??null,queueOrigin:"system",sliceScope:c,sliceTaskIds:l.length>0?l:e.taskId?[e.taskId]:[],sliceTaskCount:l.length>0?l.length:e.taskId?1:0,sliceMilestoneId:e.milestoneId,executionPolicy:null,autoContinue:null}}function zu(e){const t=new Map;for(const s of e){const i=t.get(s.initiativeId);if(i){i.workstreamCount+=1,i.workstreamIds.push(s.workstreamId),i.items.push(s);for(const a of s.runnerAgents??[])i.runnerAgents.some(l=>l.id===a.id)||i.runnerAgents.push(a);const r=a=>a==="running"?3:a==="blocked"?2:a==="queued"?1:0;r(s.queueState)>r(i.queueState)&&(i.queueState=s.queueState)}else t.set(s.initiativeId,{initiativeId:s.initiativeId,initiativeTitle:s.initiativeTitle??s.initiativeId,initiativeStatus:s.initiativeStatus??"active",initiativePriority:typeof s.initiativePriority=="string"?s.initiativePriority:null,initiativePriorityNum:typeof s.initiativePriorityNum=="number"?s.initiativePriorityNum:null,workstreamCount:1,workstreamIds:[s.workstreamId],runnerAgents:[...s.runnerAgents??[]],queueState:s.queueState,items:[s]})}return Array.from(t.values())}function Uu(e){return e.map(t=>({milestoneId:t.sliceMilestoneId??null,milestoneTitle:t.sliceMilestoneId?`Milestone ${t.sliceMilestoneId.slice(0,8)}`:t.workstreamTitle??"Workstream",workstreamId:t.workstreamId,workstreamTitle:t.workstreamTitle??t.workstreamId,initiativeId:t.initiativeId,initiativeTitle:t.initiativeTitle??t.initiativeId,taskCount:t.sliceTaskCount??0,queueState:t.queueState,item:t}))}function Wu({initiativeId:e=null,projectId:t=null,offset:s=0,limit:i=20,authToken:r=null,embedMode:a=!1,enabled:l=!0,snapshotVersion:c=null,zoomLevel:d="workstream"}){var ae,ze,pe,le,te,ne,Ce;const u=Wa(),p=Zt(),x=Math.max(0,s),b=Math.max(1,Math.min(300,i)),h=o.useRef(null);o.useEffect(()=>()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]);const I=o.useMemo(()=>Ns.nextUpQueue({initiativeId:e,projectId:t,offset:x,limit:b,authToken:r,embedMode:a}),[e,t,x,b,r,a]),y=o.useRef(c);o.useEffect(()=>{c!==null&&y.current!==null&&c!==y.current&&u.invalidateQueries({queryKey:I}),y.current=c},[c,u,I]);const j=()=>{h.current&&(clearTimeout(h.current),h.current=null),h.current=setTimeout(()=>{h.current=null,u.invalidateQueries({queryKey:Ns.liveData({authToken:r,embedMode:a,projectId:t})})},Tu)},w=async({includeGraph:G=!0,includeLiveData:R=!0}={})=>{const z=[u.invalidateQueries({queryKey:I}),u.invalidateQueries({queryKey:Ns.autoContinueStatus({initiativeId:e,authToken:r,embedMode:a})})];G&&z.push(u.invalidateQueries({queryKey:Ns.missionControlGraph({initiativeId:e,authToken:r,embedMode:a})})),await Promise.all(z),R&&j()},N=async(G,R)=>{if(p)return Lu(e);const z=new URLSearchParams;e&&z.set("initiative_id",e),_s(z,t,{allTokenWhenMissing:!0}),z.set("offset",String(G)),z.set("limit",String(R));let B;try{B=await fetch(`/orgx/api/mission-control/next-up?${z.toString()}`,{headers:Ht({authToken:r,embedMode:a})})}catch(ye){throw new Error(Ru(ye,"Failed to load next up queue"))}const K=await Ei(B);if(!B.ok){const ye=Eu(B,K,"Failed to load next up queue");throw new Error(ye)}const re=K??null;if(!re||re.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:G,limit:R,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(su())return Er(re);const ge=re.items.filter(ye=>!Xs(ye.initiativeId));let Se=Er({...re,items:ge});if(Se.items.length>0)return Se;const oe=new URLSearchParams;e&&oe.set("initiative_id",e),_s(oe,t,{allTokenWhenMissing:!0}),oe.set("level","workstream"),oe.set("include_completed","0"),oe.set("offset",String(G)),oe.set("limit",String(Math.max(R,24)));try{const ye=await fetch(`/orgx/api/mission-control/slices?${oe.toString()}`,{headers:Ht({authToken:r,embedMode:a})}),me=await Ei(ye);if(ye.ok&&(me!=null&&me.ok)&&Array.isArray(me.items)){const O=me.items.map(U=>Bu(U)).filter(U=>!!U).filter(U=>!Xs(U.initiativeId));O.length>0&&(Se=Er({ok:!0,generatedAt:new Date().toISOString(),total:typeof me.total=="number"&&Number.isFinite(me.total)?Math.max(me.total,O.length):O.length,items:O,pagination:me.pagination&&typeof me.pagination=="object"?{offset:typeof me.pagination.offset=="number"?Math.max(0,Math.floor(me.pagination.offset)):G,limit:typeof me.pagination.limit=="number"?Math.max(1,Math.floor(me.pagination.limit)):Math.max(R,24),total:typeof me.pagination.total=="number"?Math.max(0,Math.floor(me.pagination.total)):O.length,nextCursor:typeof me.pagination.nextCursor=="string"?me.pagination.nextCursor:null,hasMore:typeof me.pagination.hasMore=="boolean"?me.pagination.hasMore:!1}:void 0,degraded:Array.from(new Set([...re.degraded??[],"Queue derived from slices while live queue stabilizes."]))}))}}catch{}return Se},f=ed({queryKey:I,enabled:l,initialPageParam:x,queryFn:async({pageParam:G})=>{const R=typeof G=="number"&&Number.isFinite(G)?Math.max(0,Math.floor(G)):x;return await N(R,b)},getNextPageParam:G=>{const R=G.pagination;if(!(R!=null&&R.hasMore)||!R.nextCursor)return;const z=Number.parseInt(R.nextCursor,10);if(Number.isFinite(z))return Math.max(0,Math.floor(z))},refetchInterval:G=>{var B;const R=(B=G.state.data)==null?void 0:B.pages;return!R||R.length===0?1e4:R.some(K=>Array.isArray(K.items)&&K.items.some(re=>re.queueState==="running"))?2500:8e3}}),T=Dn({mutationFn:async G=>{if(p)return{ok:!0,initiativeId:G.initiativeId,workstreamId:G.workstreamId,dispatchMode:"slice",sessionId:null};const R=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:Ht({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:G.initiativeId,workstreamId:G.workstreamId,agentId:G.agentId??void 0,scope:G.scope??void 0,maxParallelSlices:typeof G.maxParallelSlices=="number"&&Number.isFinite(G.maxParallelSlices)?Math.max(1,Math.floor(G.maxParallelSlices)):void 0,parallelMode:G.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),z=await Ei(R);if(!R.ok)throw ua(R,z,"Failed to dispatch queued workstream");return z},onMutate:async G=>{await u.cancelQueries({queryKey:I});const R=u.getQueryData(I);return R?(u.setQueryData(I,{...R,pages:R.pages.map(z=>({...z,items:z.items.map(B=>B.initiativeId===G.initiativeId&&B.workstreamId===G.workstreamId?{...B,queueState:"running",playbackState:"running"}:B.queueState==="running"?{...B,queueState:"idle",playbackState:"idle"}:B)}))}),{previous:R}):{previous:R}},onError:(G,R,z)=>{z!=null&&z.previous&&u.setQueryData(I,z.previous)},onSuccess:()=>{w({includeGraph:!1})}}),X=Dn({mutationFn:async G=>{if(p)return;const R={initiativeId:G.initiativeId,agentId:G.agentId??void 0,tokenBudgetTokens:G.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};G.scope==="workstream"&&G.workstreamId&&(R.workstreamIds=[G.workstreamId]),typeof G.maxParallelSlices=="number"&&Number.isFinite(G.maxParallelSlices)&&(R.maxParallelSlices=G.maxParallelSlices),G.parallelMode==="iwmt"&&(R.parallelMode=G.parallelMode);const z=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:Ht({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(R)}),B=await Ei(z);if(!z.ok){const K=Au(B);throw K||ua(z,B,"Failed to start auto-continue")}},onSuccess:()=>{w({includeGraph:!1})}}),Z=Dn({mutationFn:async G=>{if(p)return;const R=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ht({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:G.initiativeId})}),z=await Ei(R);if(!R.ok)throw ua(R,z,"Failed to stop auto-continue")},onSuccess:()=>{w({includeGraph:!1})}}),W=o.useMemo(()=>{var B;const G=((B=f.data)==null?void 0:B.pages)??[];if(G.length===0)return[];const R=new Set,z=[];for(const K of G)for(const re of K.items){const ge=`${re.initiativeId}:${re.workstreamId}`;R.has(ge)||(R.add(ge),z.push(re))}return z},[(ae=f.data)==null?void 0:ae.pages]),ke=o.useMemo(()=>{var z;const G=((z=f.data)==null?void 0:z.pages)??[];let R=0;for(const B of G)typeof B.total=="number"&&Number.isFinite(B.total)&&(R=Math.max(R,B.total));return Math.max(R,W.length)},[W.length,(ze=f.data)==null?void 0:ze.pages]),D=o.useMemo(()=>{var ge;const G=((ge=f.data)==null?void 0:ge.pages)??[];if(G.length===0)return null;const R=G[0],z=G[G.length-1],B=R.pagination,K=z.pagination,re=!!f.hasNextPage;return{offset:B&&Number.isFinite(B.offset)?Math.max(0,Math.floor(B.offset)):x,limit:B&&Number.isFinite(B.limit)?Math.max(1,Math.floor(B.limit)):b,total:ke,nextCursor:re?(K==null?void 0:K.nextCursor)??String(((K==null?void 0:K.offset)??x)+((K==null?void 0:K.limit)??b)):null,hasMore:re}},[ke,b,x,(pe=f.data)==null?void 0:pe.pages,f.hasNextPage]),E=((te=(le=f.data)==null?void 0:le.pages[0])==null?void 0:te.generatedAt)??null,de=o.useMemo(()=>{var z;const G=((z=f.data)==null?void 0:z.pages)??[],R=new Set;for(const B of G)for(const K of B.degraded??[])typeof K=="string"&&K.trim().length>0&&R.add(K);return Array.from(R)},[(ne=f.data)==null?void 0:ne.pages]),ie=o.useMemo(()=>d==="initiative"?zu(W):[],[W,d]),we=o.useMemo(()=>d==="milestone"?Uu(W):[],[W,d]);return{items:W,total:ke,pagination:D,generatedAt:E,degraded:de,isLoading:f.isLoading,isFetching:f.isFetching,isFetchingNextPage:f.isFetchingNextPage,hasNextPage:!!f.hasNextPage,error:((Ce=f.error)==null?void 0:Ce.message)??null,refetch:f.refetch,fetchNextPage:f.fetchNextPage,playWorkstream:T.mutateAsync,startWorkstreamAutoContinue:X.mutateAsync,stopInitiativeAutoContinue:Z.mutateAsync,isPlaying:T.isPending,isStartingAutoContinue:X.isPending,isStoppingAutoContinue:Z.isPending,zoomLevel:d,initiativeGroups:ie,milestoneGroups:we}}const Hu=750;async function jn(e){return await e.json().catch(()=>null)}function di(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",i=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${i}`)}function An(e,t,s){if(di(e,t))return`${s}. This queue control is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable. Try again in a moment.`;const i=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||`${s}.`;return Xt(i)}function Ku(e){const t=e.authToken??null,s=e.embedMode??!1,i=Zt(),r=Wa(),a=o.useRef(null);o.useEffect(()=>()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]);const l=()=>{a.current&&(clearTimeout(a.current),a.current=null),a.current=setTimeout(()=>{a.current=null,r.invalidateQueries({queryKey:["live-data"]})},Hu)},c=async()=>{await Promise.all([r.invalidateQueries({queryKey:["mission-control-next-up"]}),r.invalidateQueries({queryKey:["mission-control-graph"]}),r.invalidateQueries({queryKey:["mission-control-slices"]})]),l()},d=async N=>{if(i)return{ok:!0,demo:!0,initiativeId:N.initiativeId,workstreamId:N.workstreamId,placement:N.placement??"top"};const f=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),T=await jn(f);if(f.ok)return T;if(!di(f,T))throw new Error(An(f,T,"Failed to move Next Up item"));const X=await fetch("/orgx/api/mission-control/next-up",{headers:Ht({authToken:t,embedMode:s})}),Z=await jn(X);if(!X.ok)throw new Error(An(X,Z,"Failed to read queue for move fallback"));const ke=(Array.isArray(Z==null?void 0:Z.items)?Z.items:[]).map(we=>{const ae=typeof(we==null?void 0:we.initiativeId)=="string"?we.initiativeId:null,ze=typeof(we==null?void 0:we.workstreamId)=="string"?we.workstreamId:null;return!ae||!ze?null:{initiativeId:ae,workstreamId:ze}}).filter(we=>!!we);if(ke.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const D=ke.findIndex(we=>we.initiativeId===N.initiativeId&&we.workstreamId===N.workstreamId);if(D===-1)return{ok:!0,fallback:"reorder-move-skip"};const[E]=ke.splice(D,1);(N.placement??"top")==="bottom"?ke.push(E):ke.unshift(E);const de=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:ke})}),ie=await jn(de);if(!de.ok)throw new Error(An(de,ie,"Failed to move Next Up item with reorder fallback"));return ie??{ok:!0,fallback:"reorder-move"}},u=async N=>{if(i)return{ok:!0,demo:!0,initiativeId:N.initiativeId,workstreamId:N.workstreamId};const f=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),T=await jn(f);if(f.ok)return T;if(di(f,T)){const X=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),Z=await jn(X);if(!X.ok)throw new Error(An(X,Z,"Failed to remove item from queue with legacy fallback"));return Z??{ok:!0,fallback:"next-up-unpin"}}throw new Error(An(f,T,"Failed to remove item from queue"))},p=Dn({mutationFn:async N=>{if(i)return{ok:!0,demo:!0};const f=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),T=await jn(f);if(!f.ok)throw new Error(An(f,T,"Failed to pin Next Up item"))},onSuccess:()=>{c()}}),x=Dn({mutationFn:async N=>{if(i)return{ok:!0,demo:!0};const f=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),T=await jn(f);if(!f.ok)throw new Error(An(f,T,"Failed to unpin Next Up item"))},onSuccess:()=>{c()}}),b=Dn({mutationFn:async N=>{if(i)return{ok:!0,demo:!0,updated:N.order.length};const f=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),T=await jn(f);if(!f.ok)throw new Error(An(f,T,"Failed to reorder Next Up queue"))},onSuccess:()=>{c()}}),h=Dn({mutationFn:d,onSuccess:()=>{c()}}),I=Dn({mutationFn:async N=>{if(i)return{ok:!0,demo:!0,initiativeId:N.initiativeId,workstreamId:N.workstreamId};const f=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),T=await jn(f);if(!f.ok){if(di(f,T)){const X=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:N.initiativeId})}),Z=await jn(X);if(!X.ok)throw new Error(An(X,Z,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(An(f,T,"Failed to stop triage"))}return T},onSuccess:()=>{c()}}),y=Dn({mutationFn:u,onSuccess:()=>{c()}}),j=Dn({mutationFn:async N=>{if(i)return{ok:!0,demo:!0,cleared:!0};const f=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),T=await jn(f);if(!f.ok){if(di(f,T)&&N.initiativeId){const X=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:N.initiativeId})}),Z=await jn(X);if(!X.ok)throw new Error(An(X,Z,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(An(f,T,"Failed to clear Next Up lifecycle state"))}return T},onSuccess:()=>{c()}}),w=Dn({mutationFn:async N=>{if(i)return{ok:!0,demo:!0,updated:N.items.length,failed:0,errors:[],fallback:"demo"};const f=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:Ht({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(N)}),T=await jn(f);if(!f.ok){if(!di(f,T))throw new Error(An(f,T,"Failed to apply bulk queue action"));const X=await Promise.all(N.items.map(async D=>{try{return N.action==="remove"?await u(D):await d({initiativeId:D.initiativeId,workstreamId:D.workstreamId,placement:N.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(E){return{ok:!1,error:E instanceof Error?E.message:"Queue action failed"}}})),Z=X.filter(D=>D.ok).length,W=X.length-Z,ke=X.filter(D=>!D.ok&&D.error).map(D=>D.error);return{ok:W===0,updated:Z,failed:W,errors:ke,fallback:"sequential"}}return T},onSuccess:()=>{c()}});return{pin:p.mutateAsync,unpin:x.mutateAsync,reorder:b.mutateAsync,move:h.mutateAsync,remove:y.mutateAsync,stopTriage:I.mutateAsync,clear:j.mutateAsync,bulk:w.mutateAsync,isPinning:p.isPending,isUnpinning:x.isPending,isReordering:b.isPending,isMoving:h.isPending,isRemoving:y.isPending,isStoppingTriage:I.isPending,isClearing:j.isPending,isBulking:w.isPending}}function sc(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function Vu(e,t,s,i){const r=new URLSearchParams;e&&r.set("workspace_id",e),t&&r.set("status",t),r.set("limit","100");const a=`/orgx/api/live/triage?${r.toString()}`,l=await fetch(a,{headers:sc(s,i)});if(!l.ok){const c=await l.json().catch(()=>null),d=(c&&typeof c=="object"&&"error"in c&&typeof c.error=="string"?c.error:null)??(c&&typeof c=="object"&&"message"in c&&typeof c.message=="string"?c.message:null)??`Triage fetch failed (${l.status})`;throw new Error(Xt(String(d)))}return l.json()}async function Gu(e,t,s,i){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,l=await fetch(a,{method:"POST",headers:sc(s,i),body:JSON.stringify(t)});if(!l.ok){const c=await l.json().catch(()=>({})),d=c.error??c.message??`Action failed (${l.status})`;throw new Error(Xt(String(d)))}return l.json()}function Xu(e={}){const{enabled:t=!0,workspaceId:s=null,status:i="open",authToken:r=null,embedMode:a=!1}=e,l=Wa(),c=Ns.triageQueue({workspaceId:s,status:i,authToken:r,embedMode:a}),d=Gs({queryKey:c,queryFn:()=>Vu(s,i,r,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=Dn({mutationFn:async({itemId:h,payload:I})=>Gu(h,I,r,a),onSuccess:()=>{l.invalidateQueries({queryKey:c})}}),p=o.useCallback(async(h,I,y)=>u.mutateAsync({itemId:h,payload:{action:I,note:y==null?void 0:y.note,optionId:y==null?void 0:y.optionId,snoozeDurationMinutes:y==null?void 0:y.snoozeDurationMinutes}}),[u]),x=o.useMemo(()=>{var h,I,y;return{items:((h=d.data)==null?void 0:h.items)??[],total:((I=d.data)==null?void 0:I.total)??0,isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,degraded:((y=d.data)==null?void 0:y.degraded)??[],refetch:d.refetch}},[d]),b=o.useMemo(()=>({performAction:p,isActing:u.isPending,lastActionError:u.error?u.error.message:null}),[p,u.isPending,u.error]);return{model:x,actions:b}}function ue(...e){return e.filter(Boolean).join(" ")}const M={lime:"#BFFF00",teal:"#14B8A6",cyan:"#0AD4C4",iris:"#7C7CFF",amber:"#F5B700",red:"#FF6B88",background:"#02040A",cardBg:"#08090D",cardBgElevated:"#0C0E14",cardBorderStrong:"rgba(255, 255, 255, 0.12)",textMuted:"#8F9AB7"},Oi={active:{border:"rgba(191, 255, 0, 0.28)",background:"rgba(191, 255, 0, 0.11)",text:"rgba(223, 255, 156, 0.9)"},done:{border:"rgba(20, 184, 166, 0.26)",background:"rgba(20, 184, 166, 0.11)",text:"rgba(135, 255, 233, 0.9)"},blocked:{border:"rgba(255, 107, 136, 0.28)",background:"rgba(255, 107, 136, 0.12)",text:"rgba(255, 195, 208, 0.9)"},planned:{border:"rgba(255, 255, 255, 0.16)",background:"rgba(255, 255, 255, 0.06)",text:"rgba(236, 241, 255, 0.74)"}},ic={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},La={Pace:"Product",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},Do={engineering:{domain:"Engineering",color:"#BFFF00"},product:{domain:"Product",color:"#A78BFA"},design:{domain:"Design",color:"#FF00D4"},marketing:{domain:"Marketing",color:"#F5B700"},sales:{domain:"Sales",color:"#0AD4C4"},operations:{domain:"Operations",color:"#14B8A6"},orchestration:{domain:"Orchestrator",color:"#FF6B88"},orchestrator:{domain:"Orchestrator",color:"#FF6B88"}};function rc(e){if(La[e])return{domain:La[e],color:ic[e]??"rgba(255,255,255,0.4)"};const t=e.toLowerCase().replace(/[_\s-]+/g,"-");for(const[s,i]of Object.entries(Do))if(t===s||t===`${s}-agent`||t===`orgx-${s}`||t===`orgx-${s}-agent`)return i;for(const[s,i]of Object.entries(Do))if(t.includes(s))return i;return null}function Qa(e){var t;return ic[e]??((t=rc(e))==null?void 0:t.color)??"rgba(255, 255, 255, 0.4)"}function Gi(e){var t;return La[e]??((t=rc(e))==null?void 0:t.domain)??null}function Qu(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function nn(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const sn={durationFast:150,durationStandard:220,durationEntrance:360,easingStandard:[.22,1,.36,1],easingEntrance:[.16,1,.3,1],easingBounce:{type:"spring",stiffness:320,damping:28,mass:.7}},fx={surfaceSwitch:{duration:sn.durationStandard/1e3,ease:sn.easingStandard},contentCrossFade:{initial:{opacity:0,y:3},animate:{opacity:1,y:0},exit:{opacity:0,y:-3},transition:{duration:sn.durationFast/1e3,ease:sn.easingStandard}},railMorphSpring:{type:"spring",stiffness:340,damping:38,mass:.72},listStaggerStep:.016,listStaggerMaxItems:6,segmentedTap:{whileTap:{scale:.985},transition:{duration:.09}}},ur={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{delay:Math.min(e,8)*.04,duration:sn.durationStandard/1e3,ease:sn.easingStandard}})},hx={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},Gr="/orgx/live/assets/Fm0FhtnV.png";function ac({size:e=14,className:t="",stroke:s="currentColor",strokeWidth:i=1.8,withBackground:r=!1,backgroundColor:a="transparent"}){return n.jsxs("svg",{className:t,width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:s,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:i,children:[r?n.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"6",fill:a,stroke:"none"}):null,n.jsx("path",{d:"M6 6c3 0 5 6 8 6"}),n.jsx("path",{d:"M6 18c3 0 5-6 8-6"}),n.jsx("path",{d:"M6 12h12"}),n.jsx("path",{d:"m14 8 4 4-4 4"}),n.jsx("circle",{cx:"6",cy:"6",r:"1.5",fill:s,stroke:"none"}),n.jsx("circle",{cx:"6",cy:"12",r:"1.5",fill:s,stroke:"none"}),n.jsx("circle",{cx:"6",cy:"18",r:"1.5",fill:s,stroke:"none"})]})}function xn({type:e,className:t="",size:s=14,accent:i}){const r={className:t,width:s,height:s,viewBox:"0 0 24 24",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.8};if(e==="initiative"){const l=i??M.iris;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${l}1A`}),n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:l,stroke:"none"})]})}if(e==="workstream"){const l=i??M.lime;return n.jsx(ac,{size:s,className:t,stroke:l,strokeWidth:r.strokeWidth,withBackground:!0,backgroundColor:`${l}1A`})}if(e==="milestone"){const l=i??M.teal;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1z",fill:`${l}1A`})]})}if(e==="task")return n.jsxs("svg",{...r,stroke:"rgba(255,255,255,0.76)",children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"4",fill:"rgba(255,255,255,0.12)"}),n.jsx("path",{d:"M9 12.2 11 14.2 15.2 10"})]});if(e==="decision"){const l=i??M.amber;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("path",{d:"M12 3 5.2 6.1v5.7c0 4.8 3.2 7.5 6.8 9 3.6-1.5 6.8-4.2 6.8-9V6.1z",fill:`${l}1A`}),n.jsx("path",{d:"m9.3 12.1 1.8 1.9 3.6-3.6"})]})}if(e==="session"){const l=i??M.teal;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"4",fill:`${l}14`}),n.jsx("path",{d:"M8 9h8"}),n.jsx("path",{d:"M8 13h5"}),n.jsx("path",{d:"M8 17h3"})]})}if(e==="active"){const l=i??M.lime;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${l}12`}),n.jsx("path",{d:"M7 13h2l1.6-6 3.1 12 1.6-6H17"})]})}if(e==="blocked"){const l=i??M.red;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${l}12`}),n.jsx("rect",{x:"7.5",y:"11",width:"9",height:"7",rx:"2",fill:"rgba(255,255,255,0.03)"}),n.jsx("path",{d:"M9 11V9.2a3 3 0 0 1 6 0V11"})]})}if(e==="failed"){const l=i??M.red;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${l}12`}),n.jsx("path",{d:"M9 9l6 6"}),n.jsx("path",{d:"M15 9l-6 6"})]})}if(e==="handoff"){const l=i??M.iris;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"m13 8 4 4-4 4"}),n.jsx("path",{d:"M7 8v8",opacity:"0.55"})]})}if(e==="outbox"){const l=i??M.amber;return n.jsxs("svg",{...r,stroke:l,children:[n.jsx("path",{d:"M4 12h16"}),n.jsx("path",{d:"M6 7h12l2 5v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7z",fill:`${l}12`}),n.jsx("path",{d:"M9 14h6"})]})}const a=i??M.cyan;return n.jsxs("svg",{...r,stroke:a,children:[n.jsx("path",{d:"M12 3a6 6 0 0 0-6 6v2.9c0 .7-.3 1.4-.8 1.9L4 15.2h16l-1.2-1.4a2.8 2.8 0 0 1-.8-1.9V9a6 6 0 0 0-6-6z",fill:`${a}1A`}),n.jsx("path",{d:"M9.2 18a2.8 2.8 0 0 0 5.6 0"})]})}const Yu=[{label:"Model Routing",desc:"Right model, right cost, every prompt",iconType:"initiative"},{label:"Live Operations",desc:"Decisions, handoffs, sessions in real time",iconType:"workstream"},{label:"Quality Gates",desc:"Automated checkpoints before shipping",iconType:"milestone"}],Rr=[{id:"hierarchy",kicker:"Mission Control",title:"Map the full execution ladder in one place",description:"Trace initiatives through workstreams, milestones, and tasks with sticky context, dependency mapping, and inline edits.",highlights:[{type:"initiative",label:"Initiative",detail:"Top-level outcomes with owner and status."},{type:"workstream",label:"Workstream",detail:"Operational lanes and runner context."},{type:"milestone",label:"Milestone",detail:"Checkpoints that gate readiness."},{type:"task",label:"Task",detail:"Priority, ETA, budget, and dependencies."}],footnote:"Use the hierarchy filters to isolate open, blocked, or done work instantly."},{id:"activity",kicker:"Activity + Decisions",title:"Stay in flow while execution evolves",description:"Track agent output as it happens, review decision payloads, and keep operational context attached from plan to completion.",highlights:[{type:"notification",label:"Live feed",detail:"Messages, failures, and progress in one stream."},{type:"decision",label:"Decision queue",detail:"Approve or reject with full execution context."},{type:"workstream",label:"Handoffs",detail:"Runner transitions across domains and tasks."},{type:"task",label:"Artifacts",detail:"Completion evidence attached where it belongs."}],footnote:"Focus a session to pin a run while the rest of the org remains visible."},{id:"dispatch",kicker:"Autopilot + Next Up",title:"Dispatch work confidently with clear guardrails",description:"Queue the next workstream, open the owning initiative instantly, and escalate from manual play to controlled auto-continue.",highlights:[{type:"workstream",label:"Next Up",detail:"Queued workstreams with resolved runner and next task."},{type:"initiative",label:"Open target",detail:"Jump to the owning initiative and sticky hierarchy."},{type:"milestone",label:"Guardrails",detail:"Blocked states are surfaced before dispatch."},{type:"notification",label:"System notices",detail:"Inline success and failure feedback loops."}],footnote:"Start with Play, then enable auto-continue when queue health is stable."}],Ju=[{type:"initiative",label:"Live Initiative Sync",detail:"Initiatives and ownership stay aligned with OpenClaw execution."},{type:"decision",label:"Decision Control",detail:"Review approvals in-app without losing mission context."},{type:"workstream",label:"Queue Visibility",detail:"Understand what runs next, who runs it, and why."}],$o="openclaw plugins install @useorgx/openclaw-plugin",Po="orgx.demo_mode",Zu=6500;function em(e){switch(e){case"config":return"Plugin config";case"environment":return"Environment variable";case"persisted":return"Saved local credential";case"openclaw-config-file":return"OpenClaw config file";case"legacy-dev":return"Local development key";default:return"Not detected"}}const tm={hidden:{},visible:{transition:{staggerChildren:.07}}},ws={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},nm={initiative:"text-[#A8A0FF]",workstream:"text-[#BFFF00]",milestone:"text-[#43E7D8]",task:"text-primary",session:"text-[#43E7D8]",active:"text-[#BFFF00]",blocked:"text-[#FF6B88]",failed:"text-[#FF6B88]",handoff:"text-[#A8A0FF]",outbox:"text-[#F5D37A]",decision:"text-[#F5D37A]",notification:"text-[#7EEDE1]"};function ma(e){const t=Rr.length;return(e+t)%t}function sm({state:e,isStarting:t,onConnect:s,onUseManualKey:i,onContinueWithoutOrgX:r}){const a=!!e.lastError,l=e.lastError?Xt(e.lastError):null,[c,d]=o.useState("idle"),[u,p]=o.useState("idle"),[x,b]=o.useState(0),[h,I]=o.useState(!1),y=e.hasApiKey&&e.keySource&&e.keySource!=="none",j=Rr[x];o.useEffect(()=>{if(c==="idle")return;const f=window.setTimeout(()=>d("idle"),2e3);return()=>window.clearTimeout(f)},[c]),o.useEffect(()=>{if(u==="idle")return;const f=window.setTimeout(()=>p("idle"),2e3);return()=>window.clearTimeout(f)},[u]),o.useEffect(()=>{if(h)return;const f=window.setInterval(()=>{b(T=>ma(T+1))},Zu);return()=>window.clearInterval(f)},[h]);const w=async()=>{try{await navigator.clipboard.writeText($o),d("ok")}catch{d("error")}},N=async()=>{try{const f={at:new Date().toISOString(),onboarding:{status:e.status,nextAction:e.nextAction,hasApiKey:e.hasApiKey,keySource:e.keySource,installationId:e.installationId,lastError:e.lastError},page:typeof window<"u"?window.location.href:null,userAgent:typeof navigator<"u"?navigator.userAgent:null};await navigator.clipboard.writeText(JSON.stringify(f,null,2)),p("ok")}catch{p("error")}};return n.jsxs(he.section,{variants:tm,initial:"hidden",animate:"visible",className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] soft-shadow rounded-2xl",children:[n.jsxs("div",{className:"px-6 pt-4 sm:px-8 sm:pt-5",children:[n.jsxs(he.div,{variants:ws,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Gr,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsxs(he.h2,{variants:ws,className:"mt-3 flex items-center gap-2.5 text-[24px] font-semibold leading-[1.2] tracking-[-0.02em] text-white sm:text-[28px]",children:[n.jsx(xn,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(he.p,{variants:ws,className:"mt-2 max-w-2xl text-heading leading-relaxed text-secondary",children:"Orchestrate agents, approve decisions, and track progress from a single live dashboard."})]}),n.jsxs("div",{className:"mt-3 grid gap-3 px-6 sm:px-8 lg:grid-cols-[1.24fr_0.86fr]",children:[n.jsxs(he.div,{variants:ws,className:"space-y-2.5",children:[n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5",onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(xn,{type:"workstream",size:14,className:"text-[#BFFF00]"}),n.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-secondary",children:"Guided Tour"})]}),n.jsxs("span",{className:"chip text-micro",children:[x+1,"/",Rr.length]})]}),n.jsx(It,{initial:!1,mode:"wait",children:n.jsxs(he.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.24,ease:[.22,1,.36,1]},className:"mt-2.5 min-h-[214px] space-y-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.09em] text-muted",children:j.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:j.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:j.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:j.highlights.map(f=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(xn,{type:f.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:f.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:f.detail})]},`${j.id}-${f.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:j.footnote})]},j.id)}),n.jsxs("div",{className:"mt-1.5 flex items-center justify-between",children:[n.jsx("div",{className:"flex items-center gap-1.5",children:Rr.map((f,T)=>{const X=T===x;return n.jsx("button",{type:"button",onClick:()=>b(T),"aria-label":`View slide ${T+1}`,className:`h-1.5 rounded-full transition-all ${X?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},f.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>b(f=>ma(f-1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Prev"}),n.jsx("button",{type:"button",onClick:()=>b(f=>ma(f+1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Next"})]})]})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-3",children:Yu.map(f=>n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.025] px-3 py-2.5",children:[n.jsx("div",{className:`mb-1.5 ${nm[f.iconType]}`,children:n.jsx(xn,{type:f.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:f.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:f.desc})]},f.label))}),n.jsxs(he.div,{variants:ws,className:"flex flex-wrap items-center gap-2.5",children:[n.jsx("button",{type:"button",onClick:s,disabled:t,className:"inline-flex items-center gap-2 rounded-full bg-[#BFFF00] px-5 py-2.5 text-body font-semibold text-black shadow-[0_0_24px_rgba(191,255,0,0.12)] transition-all hover:bg-[#d3ff42] hover:shadow-[0_0_32px_rgba(191,255,0,0.22)] disabled:cursor-not-allowed disabled:opacity-50",children:t?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"h-3.5 w-3.5 animate-spin",viewBox:"0 0 16 16",fill:"none",children:[n.jsx("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),n.jsx("path",{d:"M14 8a6 6 0 00-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),"Connecting..."]}):"Connect OrgX"}),n.jsx("button",{type:"button",onClick:i,className:"rounded-full border border-white/[0.1] px-4 py-2 text-body text-secondary transition hover:border-white/[0.18] hover:text-bright",children:"Use API key"})]})]}),n.jsxs(he.div,{variants:ws,className:"space-y-2.5",children:[n.jsxs("div",{className:"rounded-xl border border-[#14B8A6]/20 bg-[#14B8A6]/[0.06] px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(xn,{type:"workstream",size:12,className:"text-[#7EEDE1]"}),n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-[#7EEDE1]",children:"OpenClaw Integration"})]}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-[#CFF8F3]",children:"OrgX syncs with OpenClaw so initiatives, workstreams, milestones, and tasks stay aligned with live execution."})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(xn,{type:"task",size:12,className:"opacity-90"}),n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"Quick Setup"})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[n.jsx("code",{className:"rounded-md border border-white/[0.08] bg-black/30 px-2 py-1 font-mono text-caption text-primary",children:$o}),n.jsx("button",{type:"button",onClick:()=>{w()},className:"rounded-full border border-strong px-3 py-1 text-caption text-secondary transition hover:border-white/[0.2] hover:text-bright",children:c==="ok"?"Copied":c==="error"?"Copy failed":"Copy command"})]}),y&&n.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["API key source detected: ",em(e.keySource)]})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"What Unlocks After Connect"}),n.jsx("div",{className:"mt-2 space-y-1.5",children:Ju.map(f=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(xn,{type:f.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:f.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:f.detail})]},f.label))})]})]})]}),n.jsx(he.div,{variants:ws,className:"mx-6 mt-2 sm:mx-8",children:a?n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-red-500/15 bg-red-500/[0.04] px-4 py-3",children:[n.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500/15",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:n.jsx("path",{d:"M5 2.5v3M5 7.5h.004",stroke:"#FF6B88",strokeWidth:"1.4",strokeLinecap:"round"})})}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx("p",{className:"text-body text-red-300/80",children:l})}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void N(),className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",title:"Copy debug details for support",children:u==="ok"?"Copied":u==="error"?"Copy failed":"Copy debug"}),n.jsx("button",{type:"button",onClick:i,className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Use API key"}),n.jsx("button",{type:"button",onClick:s,disabled:t,className:"rounded-full border border-red-500/20 bg-red-500/[0.06] px-3 py-1 text-caption font-semibold text-red-200/85 transition hover:bg-red-500/[0.09] hover:text-red-100 disabled:opacity-50",children:"Retry"})]})]}):n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-subtle bg-white/[0.02] px-3.5 py-2",children:[n.jsx("span",{className:"relative flex h-1.5 w-1.5",children:n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-white/40"})}),n.jsx("span",{className:"text-body text-muted",children:"Ready to connect"})]})}),n.jsxs(he.div,{variants:ws,className:"mt-2 flex flex-wrap items-center justify-between gap-2 border-t border-subtle px-6 py-2 sm:px-8",children:[n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx("button",{type:"button",onClick:()=>{try{window.localStorage.setItem(Po,"1")}catch{}r()},className:"text-left text-caption text-muted transition hover:text-secondary",children:"Explore demo dashboard"}),n.jsx("button",{type:"button",onClick:()=>{try{window.localStorage.removeItem(Po)}catch{}r()},className:"text-left text-caption text-faint transition hover:text-secondary",children:"Continue offline"})]}),n.jsxs("a",{href:e.docsUrl,target:"_blank",rel:"noopener noreferrer",className:"group inline-flex items-center gap-1 text-caption text-muted transition hover:text-secondary",children:["Setup guide",n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:"transition-transform group-hover:translate-x-0.5",children:n.jsx("path",{d:"M3.5 2.5l3 2.5-3 2.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})]})}const im={hidden:{},visible:{transition:{staggerChildren:.06}}},qs={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function rm({isSubmitting:e,onSubmit:t,onBack:s}){const[i,r]=o.useState(""),[a,l]=o.useState(null),c="https://www.useorgx.com/settings#security",d=async()=>{l(null);const p=i.trim();if(!p){l("API key is required.");return}const x=/^[a-z]+_/i.test(p)?p:`oxk_${p}`;try{await t(x),r("")}catch(b){const h=b instanceof Error?b.message:"Failed to validate API key.";l(Xt(h))}},u=a!==null;return n.jsxs(he.section,{variants:im,initial:"hidden",animate:"visible",className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] soft-shadow rounded-2xl",children:[n.jsxs("div",{className:"px-6 pt-6 sm:px-8 sm:pt-8",children:[n.jsxs(he.div,{variants:qs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Gr,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsx(he.h3,{variants:qs,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(he.p,{variants:qs,className:"mt-1.5 text-heading leading-relaxed text-secondary",children:["Paste a key from your ",n.jsx("span",{className:"text-secondary",children:"useorgx.com"})," dashboard. Browser pairing is recommended."]}),n.jsxs(he.p,{variants:qs,className:"mt-1 text-body text-muted",children:["Paste full key or only the part after ",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_"}),"."]}),n.jsx(he.div,{variants:qs,className:"mt-3",children:n.jsxs("a",{href:c,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 rounded-full border border-white/[0.10] bg-white/[0.03] px-3 py-1.5 text-body font-semibold text-secondary transition hover:bg-white/[0.06] hover:text-primary",title:"Open OrgX settings to generate an API key",children:["Generate an API key",n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",children:[n.jsx("path",{d:"M4.5 2.5h5v5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M9.5 2.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M2.75 3.5H2.5c-.55 0-1 .45-1 1v5c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]})]})})]}),n.jsxs(he.div,{variants:qs,className:"mt-6 space-y-4 px-6 sm:px-8",children:[n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1.5 block text-caption font-medium uppercase tracking-[0.14em] text-muted",children:"API key"}),n.jsxs("div",{className:`flex items-stretch overflow-hidden rounded-xl border transition-colors focus-within:border-[#BFFF00]/40 ${u?"border-red-500/30":"border-white/[0.08]"}`,children:[n.jsx("span",{className:"flex items-center border-r border-subtle bg-white/[0.03] px-3 font-mono text-body text-faint select-none",children:"oxk_"}),n.jsx("input",{value:i,onChange:p=>{r(p.target.value),a&&l(null)},placeholder:"paste your key",className:"w-full bg-transparent px-3 py-2.5 font-mono text-body text-white outline-none placeholder:text-faint"})]}),u&&n.jsx(he.p,{initial:{opacity:0,y:-3},animate:{opacity:1,y:0},className:"mt-1.5 text-body text-red-400/70",children:a})]}),n.jsxs("p",{className:"text-body text-muted",children:["User-scoped keys (",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_..."}),") do not require a separate user ID header."]})]}),n.jsxs(he.div,{variants:qs,className:"mt-6 flex flex-wrap items-center gap-3 px-6 sm:px-8",children:[n.jsx("button",{type:"button",onClick:()=>{d()},disabled:e,className:"inline-flex items-center gap-2 rounded-full bg-[#BFFF00] px-5 py-2.5 text-body font-semibold text-black shadow-[0_0_24px_rgba(191,255,0,0.12)] transition-all hover:bg-[#d3ff42] hover:shadow-[0_0_32px_rgba(191,255,0,0.22)] disabled:cursor-not-allowed disabled:opacity-50",children:e?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"h-3.5 w-3.5 animate-spin",viewBox:"0 0 16 16",fill:"none",children:[n.jsx("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),n.jsx("path",{d:"M14 8a6 6 0 00-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),"Validating..."]}):"Validate & Connect"}),n.jsx("button",{type:"button",onClick:s,className:"rounded-full border border-white/[0.1] px-4 py-2 text-body text-secondary transition hover:border-white/[0.18] hover:text-bright",children:"Back to pairing"})]}),n.jsx("div",{className:"mt-6 border-t border-subtle px-6 py-4 sm:px-8",children:n.jsx("p",{className:"text-body text-faint",children:"Keys are stored locally and never leave your device."})})]})}const Fo="orgx.user.display-name",Oo="orgx.user.avatar-seed-suffix";function qo(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function Bo(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function am(){const[e,t]=o.useState(()=>qo(Fo)),[s,i]=o.useState(()=>qo(Oo)),r=(e||"orgx-user")+s,a=o.useCallback(c=>{const d=c.trim();Bo(Fo,d),t(d)},[]),l=o.useCallback(()=>{const c=String(Date.now());Bo(Oo,c),i(c)},[]);return{displayName:e,avatarSeed:r,updateName:a,regenerateAvatar:l}}function om(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function lm(e){let t=e|0;return()=>{t=t+1831565813|0;let s=Math.imul(t^t>>>15,1|t);return s=s+Math.imul(s^s>>>7,61|s)^s,((s^s>>>14)>>>0)/4294967296}}const zo=[M.lime,M.teal,M.iris,M.cyan];function cm(e,t,s,i,r,a){const l=T=>T*Math.PI/180,c=Math.cos,d=Math.sin,u=l(r),p=l(a),x=a-r>180?1:0,b=e+i*c(u),h=t+i*d(u),I=e+i*c(p),y=t+i*d(p),j=e+s*c(p),w=t+s*d(p),N=e+s*c(u),f=t+s*d(u);return[`M ${b} ${h}`,`A ${i} ${i} 0 ${x} 1 ${I} ${y}`,`L ${j} ${w}`,`A ${s} ${s} 0 ${x} 0 ${N} ${f}`,"Z"].join(" ")}function dm(e){const t=lm(om(e)),s=3+Math.floor(t()*2),i=[],r=50,a=50;for(let l=0;l<s;l++){const c=8+l*10,d=c+9,u=6+Math.floor(t()*6),p=360/u,x=1.5+t()*2;for(let b=0;b<u;b++){if(t()<.15)continue;const h=b*p+x/2,I=(b+1)*p-x/2,y=zo[Math.floor(t()*zo.length)],j=.25+t()*.55;i.push({d:cm(r,a,c,d,h,I),fill:y,opacity:j})}}return i}function oc({seed:e,size:t,className:s,animate:i=!0}){const r=o.useMemo(()=>dm(e),[e]);return n.jsxs(he.svg,{viewBox:"0 0 100 100",width:t,height:t,className:ue("flex-shrink-0",s),initial:i?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease:sn.easingEntrance},children:[n.jsxs("defs",{children:[n.jsx("clipPath",{id:`avatar-clip-${e}`,children:n.jsx("circle",{cx:"50",cy:"50",r:"48"})}),n.jsxs("radialGradient",{id:`avatar-glow-${e}`,cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:M.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:M.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:M.cardBg}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#avatar-glow-${e})`}),n.jsx("g",{clipPath:`url(#avatar-clip-${e})`,children:r.map((a,l)=>n.jsx(he.path,{d:a.d,fill:a.fill,initial:i?{opacity:0,scale:.85}:!1,animate:{opacity:a.opacity,scale:1},transition:{delay:l*.012,duration:.35,ease:sn.easingEntrance},style:{transformOrigin:"50px 50px"}},l))}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"1"})]},e)}function um({onComplete:e}){const{displayName:t,updateName:s}=am(),[i,r]=o.useState(t),a=o.useCallback(()=>{s(i),e()},[i,s,e]),l=o.useCallback(()=>{e()},[e]),c=o.useCallback(u=>{u.key==="Enter"&&a()},[a]),d=(i.trim()||"orgx-user")+"";return n.jsx(he.div,{initial:{opacity:0,y:14,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.985},transition:{duration:.32,ease:sn.easingEntrance},className:"flex items-center justify-center",children:n.jsx("div",{className:"w-full max-w-md rounded-2xl border border-white/[0.08] bg-[--orgx-surface-elevated] p-6 sm:p-8",children:n.jsxs("div",{className:"flex flex-col items-center text-center",children:[n.jsx(oc,{seed:d,size:96}),n.jsx("h2",{className:"mt-5 text-title font-medium text-white",children:"Welcome to OrgX"}),n.jsx("p",{className:"mt-2 text-body leading-relaxed text-secondary",children:"What should we call you? This appears in your settings and is stored locally."}),n.jsx("input",{type:"text",value:i,onChange:u=>r(u.target.value),onKeyDown:c,maxLength:64,autoFocus:!0,placeholder:"Your name",className:"mt-5 h-10 w-full max-w-xs rounded-xl border border-white/[0.12] bg-white/[0.04] px-4 text-center text-body text-white placeholder:text-muted focus:border-lime/30 focus:outline-none"}),n.jsx("button",{type:"button",onClick:a,className:"mt-5 rounded-full bg-lime px-6 py-2.5 text-body font-medium text-black transition hover:brightness-110",children:i.trim()?"Continue":"Continue without name"}),i.trim()&&n.jsx("button",{type:"button",onClick:l,className:"mt-3 text-caption text-secondary transition hover:text-white",children:"Skip"})]})})})}const mm=[{label:"Terms",href:"https://www.useorgx.com/terms"},{label:"Privacy",href:"https://www.useorgx.com/privacy"},{label:"IP notice",href:"https://www.useorgx.com/legal"}];function pm({className:e,compact:t=!1}){return n.jsxs("div",{className:ue("flex flex-wrap items-center gap-x-3 gap-y-1 text-muted",t?"text-micro":"text-caption",e),children:[n.jsxs("span",{className:"text-faint",children:["© ",new Date().getFullYear()," OrgX"]}),mm.map(s=>n.jsx("a",{href:s.href,target:"_blank",rel:"noopener noreferrer nofollow",className:"transition-colors hover:text-secondary",children:s.label},s.label))]})}const Uo="orgx.user.name-asked";function fm(e){switch(e){case"starting":return"Starting secure session...";case"awaiting_browser_auth":return"Waiting for browser approval...";case"pairing":return"Confirming connection...";case"manual_key":return"Manual key entry";case"connected":return"Connected";case"error":return"Connection issue";default:return"Ready to connect"}}function hm(e){switch(e){case"config":return"Config key";case"environment":return"Env key";case"persisted":return"Saved key";case"openclaw-config-file":return"OpenClaw key";case"legacy-dev":return"Local dev key";default:return"No key"}}function gm(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Wo={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},pa="orgx.onboarding.mc_hint.dismissed",fa={initial:{opacity:0,y:14,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.985},transition:{duration:.32,ease:[.16,1,.3,1]}};function xm({state:e,isLoading:t,isStarting:s,isSubmittingManual:i,onRefresh:r,onStartPairing:a,onSubmitManualKey:l,onBackToPairing:c,onUseManualKey:d,onSkip:u}){const[p,x]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(pa)==="1"),[b,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Uo)!=="1"),I=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(Uo,"1"),h(!1)},[]);o.useEffect(()=>{typeof window>"u"||(p?window.localStorage.setItem(pa,"1"):window.localStorage.removeItem(pa))},[p]);const y=e.status==="manual_key",j=e.status==="awaiting_browser_auth"||e.status==="pairing",w=gm(e.status),N=w==="active"&&e.status!=="connected",f=e.status==="connected"&&!p;return n.jsx("div",{className:"relative flex min-h-screen items-start justify-center px-4 pb-6 pt-0 sm:pt-2",style:{backgroundColor:"#02040A"},children:n.jsxs(he.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.45},className:`relative z-10 w-full ${y?"max-w-lg":"max-w-[1120px]"}`,children:[t?n.jsxs("div",{className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] rounded-2xl p-6 sm:p-8",children:[n.jsx("div",{className:"shimmer-skeleton h-7 w-28 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-5 h-8 w-3/4 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-3 h-4 w-2/3 rounded-lg"}),n.jsxs("div",{className:"mt-7 grid grid-cols-3 gap-2.5",children:[n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"})]}),n.jsx("div",{className:"shimmer-skeleton mt-7 h-10 w-36 rounded-full"})]}):n.jsx(It,{mode:"wait",children:e.status==="connected"&&b?n.jsx(he.div,{...fa,children:n.jsx(um,{onComplete:I})},"welcome-name"):y?n.jsx(he.div,{...fa,children:n.jsx(rm,{isSubmitting:i,onSubmit:l,onBack:c})},"manual"):n.jsx(he.div,{...fa,children:n.jsx(sm,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(j||e.status==="connected")&&n.jsxs(he.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:6},transition:{delay:.15,duration:.35,ease:[.16,1,.3,1]},className:"mt-4 flex items-center justify-between rounded-xl border border-subtle bg-white/[0.025] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2.5",children:[n.jsxs("span",{className:"relative flex h-2 w-2",children:[N&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Wo[w]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Wo[w]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:fm(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:hm(e.keySource)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[e.expiresAt&&n.jsx("span",{className:"text-caption text-muted",children:new Date(e.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),e.connectUrl&&j&&n.jsx("a",{href:e.connectUrl,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-[#BFFF00]/25 bg-[#BFFF00]/[0.05] px-3 py-1 text-caption font-medium text-[#D8FFA1] transition hover:bg-[#BFFF00]/[0.1]",children:"Approve in browser"}),n.jsx("button",{type:"button",onClick:()=>{r()},className:"rounded-full border border-white/[0.08] px-2.5 py-1 text-caption text-muted transition hover:bg-white/[0.04] hover:text-secondary",children:"Refresh"})]})]}),f&&n.jsxs(he.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:.2,duration:.3},className:"mt-3 rounded-xl border border-[#7C7CFF]/25 bg-[#7C7CFF]/10 px-4 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-[#CFCBFF]",children:"Mission Control Tip"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-[#E6E4FF]",children:"Open Mission Control to see initiative → workstream → milestone → task flow with dependencies and recent todos in one expandable view."}),n.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[n.jsx("a",{href:"/orgx/live?view=mission-control",className:"rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/15 px-3 py-1 text-caption font-medium text-[#D8FFA1]",children:"Open Mission Control"}),n.jsx("button",{type:"button",onClick:()=>x(!0),className:"text-caption text-secondary underline underline-offset-2",children:"Dismiss"})]})]}),!t&&n.jsx("div",{className:"mt-3 flex justify-center",children:n.jsx(pm,{compact:!0})})]})})}function ym({children:e,color:t,pulse:s,title:i}){const r=t??M.lime;return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-micro font-semibold uppercase tracking-[0.14em]",title:i,style:{backgroundColor:`${r}22`,border:`1px solid ${r}5a`,color:r},children:[n.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[s&&n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",style:{backgroundColor:r}}),n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full",style:{backgroundColor:r}})]}),e]})}function Xr({open:e,onClose:t,children:s,maxWidth:i="max-w-2xl",fitContent:r=!1,closeOnBackdropClick:a=!0,closeOnEscape:l=!0,closeOnEscapeWhenTyping:c=!0}){const d=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{if(!e)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(()=>{const I=d.current;if(!I)return;const y=I.querySelector('[data-modal-autofocus="true"]');if(y){y.focus();return}const j=I.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');j.length>0?j[0].focus():I.focus()})();const b=I=>{if(I.key==="Escape"){if(!l)return;if(!c){const T=I.target;if(T&&(T.tagName==="INPUT"||T.tagName==="TEXTAREA"||T.tagName==="SELECT"||T.isContentEditable))return}I.preventDefault(),t();return}if(I.key!=="Tab")return;const y=d.current;if(!y)return;const j=y.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(j.length===0){I.preventDefault(),y.focus();return}const w=j[0],N=j[j.length-1],f=document.activeElement;!I.shiftKey&&f===N?(I.preventDefault(),w.focus()):I.shiftKey&&f===w&&(I.preventDefault(),N.focus())},h=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",b),()=>{var I;document.body.style.overflow=h,document.removeEventListener("keydown",b),(I=u.current)==null||I.focus()}},[e,t,l,c]);const p=n.jsx(It,{children:e&&n.jsxs(he.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[420] flex items-stretch justify-center p-0 sm:items-center sm:p-6",onClick:()=>{a&&t()},"aria-hidden":!e,children:[n.jsx("div",{className:"absolute inset-0 bg-black/80 backdrop-blur-md"}),n.jsxs(he.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.24,ease:[.16,1,.3,1]},className:`glass-panel soft-shadow relative flex flex-col w-full ${i} overflow-hidden ${r?"h-auto max-h-[100dvh] rounded-none sm:max-h-[88vh] sm:rounded-2xl":"h-[100dvh] max-h-[100dvh] rounded-none sm:h-[88vh] sm:max-h-[88vh] sm:rounded-2xl"}`,style:{backgroundColor:M.cardBgElevated,borderColor:M.cardBorderStrong},onClick:x=>x.stopPropagation(),role:"dialog","aria-modal":"true",tabIndex:-1,ref:d,children:[n.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-white/50 to-transparent"}),s]})]})});return typeof document>"u"?p:Jc.createPortal(p,document.body)}const bm=[{id:"agents",label:"Agents",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]})},{id:"activity",label:"Activity",icon:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})})},{id:"decisions",label:"Decisions",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"}),n.jsx("path",{d:"m9 12 2 2 4-4"})]})},{id:"initiatives",label:"Next Up",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"}),n.jsx("line",{x1:"4",x2:"4",y1:"22",y2:"15"})]})}];function vm({activeTab:e,onTabChange:t,pendingDecisionCount:s=0}){return n.jsx("nav",{className:"pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3 lg:hidden",style:{bottom:"max(10px, env(safe-area-inset-bottom))"},"aria-label":"Mobile sections",children:n.jsx("div",{className:"pointer-events-auto relative flex items-stretch gap-1 rounded-[24px] border border-strong bg-[#090d16]/90 p-1.5 shadow-[0_20px_50px_rgba(0,0,0,0.52)] backdrop-blur-xl",children:bm.map(i=>{const r=e===i.id;return n.jsxs("button",{type:"button",onClick:()=>t(i.id),"aria-current":r?"page":void 0,className:ue("relative flex min-w-[76px] flex-1 flex-col items-center gap-1 overflow-hidden rounded-[18px] px-2 pb-1.5 pt-2.5 transition-colors",r?"text-lime":"text-secondary hover:text-white/72"),children:[r&&n.jsxs(n.Fragment,{children:[n.jsx(he.span,{layoutId:"mobile-tab-active-pill",className:"absolute inset-0 rounded-[18px] border border-[#BFFF00]/28 bg-[#BFFF00]/[0.1]",transition:{type:"spring",stiffness:420,damping:34,mass:.8}}),n.jsx(he.span,{layoutId:"mobile-tab-active-line",className:"absolute inset-x-3 top-0.5 h-[2px] rounded-full",style:{backgroundColor:M.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:ue("relative inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors",r?"border-[#BFFF00]/35 bg-[#BFFF00]/[0.12] text-[#D8FFA1]":"border-white/[0.1] bg-white/[0.03]"),children:[n.jsx("span",{className:"relative z-[1]",children:i.icon}),i.id==="decisions"&&s>0&&n.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-3.5 min-w-[14px] items-center justify-center rounded-full border border-black/35 px-1 text-[8px] font-bold text-black shadow-[0_2px_8px_rgba(0,0,0,0.35)]",style:{backgroundColor:M.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:ue("relative z-[1] text-micro font-medium",r?"text-[#D8FFA1]":"text-secondary"),children:i.label})]},i.id)})})})}function Vs({children:e,className:t="",surface:s=!0}){return n.jsx("section",{className:ue("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const wm={xs:"w-6 h-6 text-micro",sm:"w-8 h-8 text-micro",md:"w-10 h-10 text-body",lg:"w-16 h-16 text-title"},km={xs:24,sm:32,md:40,lg:64},Im="orgx.user.display-name",Nm="orgx.user.avatar-seed-suffix",jm="/orgx/live/",_n=e=>`${jm.replace(/\/+$/,"/")}${e}`,Am={pace:_n("brand/product-orchestrator.png"),eli:_n("brand/engineering-autopilot.png"),mark:_n("brand/launch-captain.png"),sage:_n("brand/pipeline-intelligence.png"),orion:_n("brand/control-tower.png"),dana:_n("brand/design-codex.png"),xandy:_n("brand/xandy-orchestrator.png"),nova:_n("brand/xandy-orchestrator.png"),openclaw:_n("brand/openclaw-mark.svg"),codex:_n("brand/openai-mark.svg"),openai:_n("brand/openai-mark.svg"),anthropic:_n("brand/anthropic-mark.svg"),orgx:_n("brand/orgx-logo.png")},_m=[{test:/\bpace\b|product|nova|strategist/i,key:"pace"},{test:/\beli\b|engineering|dev-delivery|executor/i,key:"eli"},{test:/\bmark\b|marketing|launch-captain/i,key:"mark"},{test:/\bsage\b|sales|pipeline-intelligence|sales-sage/i,key:"sage"},{test:/\borion\b|operations|ops-orbit|control-tower/i,key:"orion"},{test:/\bdana\b|design/i,key:"dana"},{test:/\bxandy\b|orchestrator|router-all-agents/i,key:"xandy"},{test:/\bholt\b|openclaw/i,key:"openclaw"},{test:/openai|gpt|o[1345]-|codex/i,key:"codex"},{test:/anthropic|claude/i,key:"anthropic"},{test:/\borgx\b/i,key:"orgx"}];function Sm(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of _m)if(s.test.test(t))return Am[s.key];return null}function Cm(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ho(e){const t=Cm(e);return t?!!(t==="you"||t==="main"||t==="me"||t==="user"||t==="usr"||t.startsWith("user_")||t.startsWith("usr_")):!1}function Tm(){if(typeof window>"u")return"orgx-user";try{const e=(window.localStorage.getItem(Im)??"").trim(),t=window.localStorage.getItem(Nm)??"";return`${e||"orgx-user"}${t}`}catch{return"orgx-user"}}function en({name:e,size:t="xs",hint:s,src:i}){const r=Qa(e),[a,l]=o.useState(!1),c=o.useMemo(()=>Ho(e)||Ho(s),[s,e]),d=o.useMemo(()=>c?Tm():null,[c]),u=o.useMemo(()=>i&&i.trim()?i:Sm(e,s),[s,e,i]),p=!!(!c&&u&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${wm[t]} overflow-hidden rounded-full flex items-center justify-center font-semibold flex-shrink-0`,style:{backgroundColor:`${r}20`,color:r,border:`1px solid ${r}30`},children:c&&d?n.jsx(oc,{seed:d,size:km[t],animate:!1,className:"h-full w-full"}):p?n.jsx("img",{src:u??void 0,alt:e,className:"h-full w-full rounded-full object-cover",onError:()=>l(!0),loading:"lazy"}):Qu(e)})}en.displayName="AgentAvatar";const Mm={neutral:"border-strong bg-white/[0.04] text-primary",muted:"border-strong bg-white/[0.03] text-secondary",lime:"border-lime/28 bg-lime/[0.12] text-[#D8FFA1]",cyan:"border-cyan-300/28 bg-cyan-500/[0.12] text-cyan-100",red:"border-red-300/28 bg-red-500/[0.12] text-red-100"};function Ln({children:e,tone:t="muted",className:s,...i}){const r=o.Children.toArray(e).some(a=>{if(!o.isValidElement(a))return!1;const l=a.type;return l.displayName==="AgentAvatar"||l.name==="AgentAvatar"});return n.jsx("span",{className:ue("inline-flex h-7 items-center rounded-full border text-caption font-medium leading-none whitespace-nowrap",r?"gap-1.5 pl-[3px] pr-2.5 [&>[data-agent-avatar]]:h-5 [&>[data-agent-avatar]]:w-5":"gap-1.5 px-2.5",Mm[t],s),...i,children:e})}function Em(e){var s,i;const t=[];if(e.initiativeId){const r={id:e.initiativeId,label:e.initiativeTitle||Ws(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=lc(e.status),l={id:e.workstreamId,label:e.workstreamTitle||Ws(e.workstreamId,"Workstream"),type:"workstream",status:a,progress:e.scopeProgress?{done:e.scopeProgress.completedTasks,total:e.scopeProgress.totalTasks}:void 0,agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]};if((s=e.scopeProgress)!=null&&s.milestones&&e.scopeProgress.milestones.length>0)for(const c of e.scopeProgress.milestones){const d=c.done>=c.total?"done":c.done>0?"active":"pending",u={id:c.id,label:c.title||Ws(c.id,"Milestone"),type:"milestone",status:d,progress:{done:c.done,total:c.total}};c.total>0&&(u.children=Array.from({length:c.total},(p,x)=>({id:`${c.id}-task-${x}`,label:`Task ${x+1}`,type:"task",status:x<c.done?"done":"pending"}))),l.children.push(u)}else if(e.taskIds&&e.taskIds.length>0){const c=((i=e.scopeProgress)==null?void 0:i.completedTasks)??0;l.children=e.taskIds.map((d,u)=>({id:d,label:Ws(d,"Task"),type:"task",status:u<c?"done":"pending"}))}r.children.push(l)}t.push(r)}return t}function gx(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||Ws(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,i=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||Ws(e.workstreamId,"Workstream"),type:"workstream",status:lc(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,r=e.taskId?{id:e.taskId,label:e.taskTitle||Ws(e.taskId,"Task"),type:"task",highlight:!0}:null;return i&&r&&(i.children=[r]),s&&i?(s.children=[i],t.push(s)):i?t.push(i):s&&t.push(s),t}function Ws(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function lc(e){return e?e==="completed"||e==="done"?"done":e==="running"||e==="in_progress"||e==="needs_review"?"active":e==="failed"?"failed":e==="blocked"||e==="awaiting_input"?"blocked":"pending":"pending"}function Rm(e){return e==="done"||e==="completed"?"done":e==="active"||e==="running"||e==="in_progress"?"active":e==="blocked"?"blocked":e==="failed"?"failed":"pending"}function Lm(e){return e.map(t=>({id:t.id,label:t.title,type:"milestone",status:t.doneTasks===t.totalTasks&&t.totalTasks>0?"done":t.tasks.some(s=>s.status==="active"||s.status==="running"||s.status==="in_progress")?"active":"pending",progress:{done:t.doneTasks,total:t.totalTasks},children:t.tasks.map(s=>({id:s.id,label:s.title,type:"task",status:Rm(s.status)}))}))}function Dm(e){const t=[],s=[],i=[],r=[];for(const a of e)a.status==="done"?s.push(a):a.status==="active"?t.push(a):a.status==="blocked"||a.status==="failed"?r.push(a):i.push(a);return{inProgress:t,completed:s,upcoming:i,blocked:r}}const xx=o.memo(function({milestones:t,height:s=3}){const i=t.reduce((r,a)=>r+a.totalTasks,0);return i===0?null:n.jsx("div",{className:"flex w-full gap-px overflow-hidden rounded-full",style:{height:s},children:t.map(r=>{const a=r.totalTasks/i*100,l=r.totalTasks>0?r.doneTasks/r.totalTasks*100:0,c=r.doneTasks===r.totalTasks&&r.totalTasks>0;return n.jsx("div",{className:"relative overflow-hidden rounded-full bg-white/[0.06]",style:{width:`${a}%`},children:n.jsx("div",{className:"absolute inset-y-0 left-0 rounded-full transition-[width] duration-500",style:{width:`${l}%`,backgroundColor:c?M.teal:`${M.lime}99`}})},r.id)})})}),$m={active:Oi.active,done:Oi.done,blocked:Oi.blocked,planned:Oi.planned};function mr({label:e,count:t,tone:s,nodes:i,defaultOpen:r,compact:a}){const[l,c]=o.useState(r),d=$m[s]??Oi.planned;return n.jsxs("div",{className:"overflow-hidden rounded-lg border",style:{borderColor:d.border,backgroundColor:d.background},children:[n.jsxs("button",{type:"button",onClick:()=>c(u=>!u),className:"flex w-full items-center justify-between px-2.5 py-1.5",children:[n.jsxs("span",{className:"text-micro font-semibold uppercase tracking-[0.08em]",style:{color:d.text},children:[e," ",n.jsx("span",{className:"ml-1 font-normal opacity-70",children:t})]}),n.jsx(he.svg,{viewBox:"0 0 12 12",fill:"none",className:"h-3 w-3",style:{color:d.text},animate:{rotate:l?180:0},transition:{duration:.15},children:n.jsx("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n.jsx(It,{initial:!1,children:l&&n.jsx(he.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:n.jsx("div",{className:"px-1 pb-1.5",children:n.jsx(uc,{nodes:i,compact:a})})})})]})}const Pm=o.memo(function({nodes:t,compact:s=!1}){const i=Dm(t);return n.jsxs("div",{className:"space-y-2",children:[i.blocked.length>0&&n.jsx(mr,{label:"BLOCKED",count:i.blocked.length,tone:"blocked",nodes:i.blocked,defaultOpen:!0,compact:s}),i.inProgress.length>0&&n.jsx(mr,{label:"IN PROGRESS",count:i.inProgress.length,tone:"active",nodes:i.inProgress,defaultOpen:!0,compact:s}),i.completed.length>0&&n.jsx(mr,{label:"COMPLETED",count:i.completed.length,tone:"done",nodes:i.completed,defaultOpen:!1,compact:s}),i.upcoming.length>0&&n.jsx(mr,{label:"UPCOMING",count:i.upcoming.length,tone:"planned",nodes:i.upcoming,defaultOpen:!1,compact:s})]})});function cc(e){switch(e){case"done":return M.lime;case"active":return M.teal;case"blocked":return M.amber;case"failed":return M.red;default:return"rgba(255,255,255,0.15)"}}function Fm(e){const t=cc(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const Om=o.memo(function({done:t,total:s,color:i}){const r=s>0?Math.max(2,Math.round(t/s*100)):0;return n.jsx("div",{className:"h-[3px] w-full overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx(he.div,{className:"h-full rounded-full",style:{backgroundColor:i},initial:{width:0},animate:{width:`${r}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),qm=16,Bm=14,Ko=8,zm=8,Um=28,Wm=24,Hm=24,Km=20,ha="rgba(255,255,255,0.07)";function Vm(e){const t=e?Bm:qm,s=t+zm+4;return{iconSz:t,colW:s,rowH:e?Hm:Um,rowHTask:e?Km:Wm}}function dc({node:e,depth:t,isLast:s,activeId:i,compact:r,index:a,taskLimit:l,expanded:c,onToggleExpand:d}){const u=i===e.id||e.highlight,p=e.progress&&e.progress.total>0,x=e.type==="task",{iconSz:b,colW:h,rowH:I,rowHTask:y}=Vm(r),j=x?y:I,w=e.children??[],N=w.filter(D=>D.type==="task"),f=w.filter(D=>D.type!=="task"),T=N.length>l&&!c,X=T?N.slice(0,l):N,Z=N.length-X.length,W=[...f,...X],ke=W.length>0||T;return n.jsxs("div",{className:"relative",style:{minHeight:j},children:[t>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute w-px",style:{backgroundColor:ha,left:(t-1)*h+h/2,top:0,bottom:s?void 0:0,height:s?j/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:ha,left:(t-1)*h+h/2,top:j/2,width:h}})]}),n.jsxs(he.div,{initial:{opacity:0,x:-3},animate:{opacity:1,x:0},transition:{delay:a*.02,duration:.15},className:`flex items-center ${u?"rounded-md bg-white/[0.03]":""}`,style:{height:j,paddingLeft:t*h},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:h,height:j},children:x?n.jsx("span",{className:"inline-block rounded-full",style:{...Fm(e.status),width:Ko,height:Ko}}):n.jsx(xn,{type:e.type,size:b,accent:u?M.lime:void 0})}),n.jsxs("div",{className:"min-w-0 flex-1 pr-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:`min-w-0 truncate ${x?`text-[12px] leading-none ${e.status==="done"?"text-white/40 line-through decoration-white/10":"text-white/35"}`:e.type==="milestone"?"text-[13px] font-medium leading-none text-white/55":t===0?"text-[13px] font-medium leading-none text-white/80":"text-[13px] font-medium leading-none text-white/70"} ${u?"!text-white/90 !no-underline":""}`,children:e.label}),p&&n.jsxs("span",{className:"flex-shrink-0 text-[10px] tabular-nums leading-none text-white/20",children:[e.progress.done,"/",e.progress.total]}),e.agent&&n.jsx("span",{className:"ml-auto flex-shrink-0 rounded-full bg-white/[0.05] px-1.5 py-px text-[9px] font-medium leading-none text-white/25",children:e.agent.name})]}),p&&!x&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(Om,{done:e.progress.done,total:e.progress.total,color:cc(e.status)})})]})]}),ke&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:ha,left:t*h+h/2,top:j/2,height:j/2}}),ke&&n.jsxs("div",{children:[W.map((D,E)=>n.jsx(dc,{node:D,depth:t+1,isLast:E===W.length-1&&!T,activeId:i,compact:r,index:a+E+1,taskLimit:l,expanded:c,onToggleExpand:d},D.id)),T&&n.jsxs(he.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+W.length+1)*.02},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{height:y,paddingLeft:(t+1)*h+h},children:["+",Z," more · see all"]}),n.jsx(It,{children:c&&N.length>l&&n.jsx(he.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:y},exit:{opacity:0,height:0},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{paddingLeft:(t+1)*h+h},children:"show less"})})]})]})}const uc=o.memo(function({nodes:t,className:s,activeId:i,compact:r,taskLimit:a=4}){const[l,c]=o.useState(!1);return t.length===0?null:n.jsx("div",{className:s,children:t.map((d,u)=>n.jsx(dc,{node:d,depth:0,isLast:u===t.length-1,activeId:i,compact:r,index:u,taskLimit:a,expanded:l,onToggleExpand:()=>c(p=>!p)},d.id))})}),Da={engineering:{domain:"engineering",displayName:"Engineering",gradient:["#22c55e","#14b8a6"],accentColor:"#22c55e",glowColor:"#22c55e33",icon:"hammer",progressStyle:"linear",verb:"Building"},design:{domain:"design",displayName:"Design",gradient:["#a78bfa","#ec4899"],accentColor:"#a78bfa",glowColor:"#a78bfa33",icon:"palette",progressStyle:"wave",verb:"Designing"},product:{domain:"product",displayName:"Product",gradient:["#3b82f6","#6366f1"],accentColor:"#3b82f6",glowColor:"#3b82f633",icon:"compass",progressStyle:"stepped",verb:"Specifying"},marketing:{domain:"marketing",displayName:"Marketing",gradient:["#f59e0b","#ef4444"],accentColor:"#f59e0b",glowColor:"#f59e0b33",icon:"megaphone",progressStyle:"wave",verb:"Crafting"},sales:{domain:"sales",displayName:"Sales",gradient:["#06b6d4","#3b82f6"],accentColor:"#06b6d4",glowColor:"#06b6d433",icon:"handshake",progressStyle:"linear",verb:"Preparing"},operations:{domain:"operations",displayName:"Operations",gradient:["#64748b","#475569"],accentColor:"#64748b",glowColor:"#64748b33",icon:"shield",progressStyle:"stepped",verb:"Securing"},orchestrator:{domain:"orchestrator",displayName:"Orchestrator",gradient:["#8b5cf6","#6366f1"],accentColor:"#8b5cf6",glowColor:"#8b5cf633",icon:"workflow",progressStyle:"linear",verb:"Coordinating"}},Gm=Object.keys(Da);function Vo(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of Gm)if(t.includes(s))return s;return"engineering"}function Go(e){return Da[e]??Da.engineering}const oi={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Ri={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},Xo={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},Qo={eli:"Eli",pace:"Pace",dana:"Dana",mark:"Mark",sage:"Sage",orion:"Orion",xandy:"Xandy",nova:"Nova","engineering-agent":"Eli","product-agent":"Pace","design-agent":"Dana","marketing-agent":"Mark","strategy-agent":"Sage","sales-agent":"Sage","operations-agent":"Orion","orchestrator-agent":"Xandy","research-agent":"Nova","engineering-bot":"Eli","product-bot":"Pace","design-bot":"Dana","marketing-bot":"Mark","dev-delivery":"Eli","launch-captain":"Mark","pipeline-intelligence":"Sage","control-tower":"Orion","design-codex":"Dana","router-all-agents":"Xandy","ops-orbit":"Orion","sales-sage":"Sage"};function mc(e,t){const s={name:(t==null?void 0:t.trim())||"OrgX",domain:"",color:"rgba(255,255,255,0.4)",displayLabel:(t==null?void 0:t.trim())||"OrgX"};if(e){const i=e.trim().toLowerCase(),r=Qo[i];if(r){const a=Ri[r]??"";return{name:r,domain:a,color:oi[r]??s.color,displayLabel:a?`${r} (${a})`:r}}for(const[a,l]of Object.entries(Xo))if(i.includes(a)){const c=Ri[l]??"";return{name:l,domain:c,color:oi[l]??s.color,displayLabel:c?`${l} (${c})`:l}}}if(t){const i=t.trim();if(oi[i]){const l=Ri[i]??"";return{name:i,domain:l,color:oi[i],displayLabel:l?`${i} (${l})`:i}}const r=i.toLowerCase(),a=Qo[r];if(a){const l=Ri[a]??"";return{name:a,domain:l,color:oi[a]??s.color,displayLabel:l?`${a} (${l})`:a}}for(const[l,c]of Object.entries(Xo))if(r.includes(l)){const d=Ri[c]??"";return{name:c,domain:d,color:oi[c]??s.color,displayLabel:d?`${c} (${d})`:c}}}return s}function yx({agents:e,max:t=4}){if(!e.length)return null;const s=e.slice(0,t),i=e.length-t;return n.jsxs("div",{className:"inline-flex min-w-0 items-center justify-end -space-x-1.5 pl-1",children:[s.map(r=>n.jsx("div",{className:"relative flex-shrink-0",title:`${r.name} (${r.confidence} confidence)`,style:{borderRadius:"9999px",border:r.confidence==="high"?"1.5px solid rgba(255,255,255,0.25)":r.confidence==="medium"?"1.5px dashed rgba(255,255,255,0.15)":"1.5px dotted rgba(255,255,255,0.10)"},children:n.jsx(en,{name:r.name,size:"xs"})},r.id)),i>0&&n.jsxs("span",{className:"ml-1 flex-shrink-0 text-micro text-muted",children:["+",i]})]})}const Xm=new Set(["running","active","in_progress","working","planning","dispatching"]),Qm=new Set(["running","dispatching"]),Ym=3*6e4;function Jm(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=Ym:!1}function Zm(e){const t=nn(e.status??""),s=nn(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:Xm.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?Jm(e.lastHeartbeatAt):!1}function pc(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function ep(e){const t=nn(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"border-teal-300/28 bg-teal-400/[0.10] text-teal-100":t==="blocked"||t==="failed"||t==="error"?"border-red-400/26 bg-red-500/[0.10] text-red-100":t==="paused"||t==="pending"||t==="queued"?"border-amber-300/28 bg-amber-300/[0.10] text-amber-100":"border-[#BFFF00]/24 bg-[#BFFF00]/[0.10] text-[#E8FFD0]"}function tp(e){const t=nn(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"from-teal-300/0 via-teal-300/65 to-teal-300/0":t==="blocked"||t==="failed"||t==="error"?"from-red-300/0 via-red-300/65 to-red-300/0":t==="paused"||t==="pending"||t==="queued"?"from-amber-300/0 via-amber-300/65 to-amber-300/0":"from-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function fc(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function pr(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Bs(e,t){const s=[],i=r=>{if(typeof r!="string")return;const a=r.trim();a&&(s.some(l=>l.toLowerCase()===a.toLowerCase())||s.push(a))};if(Array.isArray(e))for(const r of e)i(r);return i(t??null),s}function $a(e,t){if(!e)return t;const s=e.trim();return s?Wn(s)?`${t} ${Is(s)}`:s:t}const np=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),sp=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function ip(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?np.has(t)||t.startsWith("telegram:"):!1}function rp(e){if(!e)return!1;const t=e.trim();return t?sp.some(s=>s.test(t)):!1}function hc({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var x,b,h,I,y,j;const i=new Map;for(const w of s)w.id&&i.set(w.id,w.name??w.id);const r=new Map;for(const w of e){const N=(x=w.runId)==null?void 0:x.trim();!N||r.has(N)||r.set(N,w)}const a=new Map;for(const w of e){const N=((b=w.initiativeId)==null?void 0:b.trim())??"",f=((h=w.workstreamId)==null?void 0:h.trim())??"";if(!N||!f)continue;const T=`${N}:${f}`;a.has(T)||a.set(T,w)}const l=new Set;for(const w of e){const N=(I=w.runId)==null?void 0:I.trim();N&&l.add(N)}const c=[];for(const w of t){const N=(w.sliceKind??"").trim().toLowerCase();if(N&&N!=="work_slice"||!Qm.has(w.status))continue;const f=(w.runId??w.sliceRunId??"").trim();if(!f)continue;const T=Bs(w.initiativeIds,w.initiativeId),X=Bs(w.workstreamIds,w.workstreamId),Z=T[0]??null,W=X[0]??null;if(!Z||!W)continue;const ke=[];for(const we of T)for(const ae of X)!we||!ae||ke.push(`${we}:${ae}`);if(!(l.has(f)||ke.some(we=>a.has(we))))continue;const E=r.get(f)??(ke.length>0?ke.map(we=>a.get(we)??null).find(we=>!!we)??null:null),de=Z?i.get(Z)??Z:null,ie=w.scopeProgress&&typeof w.scopeProgress.totalTasks=="number"&&w.scopeProgress.totalTasks>0?Math.round(w.scopeProgress.completedTasks/w.scopeProgress.totalTasks*100):null;c.push({key:`slice:${w.sliceRunId}`,source:"slice",session:E??null,runId:f,status:nn(w.status),title:w.workstreamTitle??(E==null?void 0:E.title)??`Work slice ${w.sliceRunId.slice(0,8)}`,subtitle:w.statusExplainer??w.lastEventSummary??(E==null?void 0:E.lastEventSummary)??null,progress:ie??(E==null?void 0:E.progress)??null,initiativeId:Z,initiativeIds:T,initiativeTitle:de,workstreamId:W,workstreamIds:X,iwmtId:w.iwmtId??null,iwmtIds:Bs(w.iwmtIds,w.iwmtId),workstreamTitle:w.workstreamTitle??(E==null?void 0:E.title)??null,taskIds:Array.isArray(w.taskIds)?w.taskIds:[],milestoneIds:Array.isArray(w.milestoneIds)?w.milestoneIds:[],artifactCount:w.artifactCount??0,decisionCount:w.blockingDecisionCount??w.decisionCount??0,updatedAt:w.updatedAt??w.lastEventAt??(E==null?void 0:E.updatedAt)??null,scope:w.scope,milestoneProgress:(y=w.scopeProgress)==null?void 0:y.milestones})}if(c.sort((w,N)=>pr(N.updatedAt)-pr(w.updatedAt)),c.length>0){const w=[],N=new Set;for(const f of c){const T=f.initiativeId??((j=f.initiativeIds)==null?void 0:j[0])??"none",Z=(f.workstreamId?`scope:${T}:${f.workstreamId}`:null)??(f.runId?`run:${f.runId}`:f.key);N.has(Z)||(N.add(Z),w.push(f))}return w}const d=e.filter(w=>{if(!Zm(w))return!1;const N=(w.initiativeId??"").trim(),f=(w.workstreamId??"").trim();return N.length>0&&f.length>0});d.sort((w,N)=>{const f=pr(w.updatedAt??w.lastEventAt??w.startedAt);return pr(N.updatedAt??N.lastEventAt??N.startedAt)-f});const u=[],p=new Set;for(const w of d){const N=w.workstreamId&&w.workstreamId.trim().length>0?`${w.initiativeId??"none"}:${w.workstreamId}`:w.runId;p.has(N)||(p.add(N),u.push(w))}return u.map(w=>{var N;return{key:`session:${w.id}`,source:"session",session:w,runId:w.runId,status:nn(w.status??""),title:w.title,subtitle:(N=w.lastEventSummary)!=null&&N.trim()?w.lastEventSummary.trim():null,progress:w.progress,initiativeId:w.initiativeId,initiativeIds:Bs(void 0,w.initiativeId),initiativeTitle:w.initiativeId?i.get(w.initiativeId)??w.groupLabel??null:w.groupLabel??null,workstreamId:w.workstreamId,workstreamIds:Bs(void 0,w.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:w.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:w.updatedAt??w.lastEventAt??w.startedAt??null}})}const ap=o.memo(function({sessions:t,sliceRuns:s=[],initiatives:i=[],title:r="In Progress",className:a,showHeader:l=!0,panelStyle:c="card",needsAttentionCount:d=0,onSwitchToNeedsAttention:u,onOpenSession:p,onFocusRunId:x,onPlayWorkstream:b,onPauseWorkstream:h,onResumeWorkstream:I,onRestartSession:y,onIntervene:j,onOpenSliceDetail:w}){const[N,f]=o.useState(null),[T,X]=o.useState(null),[Z,W]=o.useState(null),[ke,D]=o.useState(null),E=o.useMemo(()=>{const te=new Map;if(!Array.isArray(s))return te;for(const ne of s){const Ce=Bs(ne.initiativeIds,ne.initiativeId),G=Bs(ne.workstreamIds,ne.workstreamId);for(const z of Ce)for(const B of G){if(!z||!B)continue;const K=`${z}:${B}`;te.has(K)||te.set(K,ne)}const R=(ne.runId??ne.sliceRunId??"").trim();R&&!te.has(`run:${R}`)&&te.set(`run:${R}`,ne)}return te},[s]),de=o.useMemo(()=>hc({sessions:t,sliceRuns:s,initiatives:i}),[i,t,s]),ie=o.useMemo(()=>{const te=new Map;for(const ne of de){const Ce=nn(ne.status);te.set(Ce,(te.get(Ce)??0)+1)}return Array.from(te.entries()).sort((ne,Ce)=>Ce[1]-ne[1]).map(([ne,Ce])=>({status:ne,count:Ce}))},[de]),we=o.useMemo(()=>N?de.filter(te=>nn(te.status)===N):de,[N,de]),ae=o.useMemo(()=>{var G,R;const te=new Map,ne=[];for(const z of we){const B=(((G=z.initiativeIds)==null?void 0:G[0])??z.initiativeId??"").trim(),K=(((R=z.workstreamIds)==null?void 0:R[0])??z.workstreamId??"").trim();if(!B){ne.push(z);continue}let re=te.get(B);re||(re={title:z.initiativeTitle??B,wsMap:new Map},te.set(B,re));const ge=K||"__none__";let Se=re.wsMap.get(ge);Se||(Se={title:z.workstreamTitle??(K||"Unassigned"),rows:[],completedCount:0,lastActivity:null},re.wsMap.set(ge,Se));const oe=nn(z.status);if(oe==="completed"||oe==="done"?Se.completedCount+=1:Se.rows.push(z),z.updatedAt){const ye=Date.parse(z.updatedAt),me=Se.lastActivity?Date.parse(Se.lastActivity):0;Number.isFinite(ye)&&ye>me&&(Se.lastActivity=z.updatedAt)}}const Ce=[];for(const[z,B]of te){const K=[];for(const[re,ge]of B.wsMap)K.push({workstreamId:re,workstreamTitle:ge.title,rows:ge.rows,completedCount:ge.completedCount,lastActivityAt:ge.lastActivity});K.sort((re,ge)=>{const Se=re.lastActivityAt?Date.parse(re.lastActivityAt):0;return(ge.lastActivityAt?Date.parse(ge.lastActivityAt):0)-Se}),Ce.push({initiativeId:z,initiativeTitle:B.title,workstreams:K})}return Ce.sort((z,B)=>{const K=Math.max(0,...z.workstreams.map(ge=>ge.lastActivityAt?Date.parse(ge.lastActivityAt):0));return Math.max(0,...B.workstreams.map(ge=>ge.lastActivityAt?Date.parse(ge.lastActivityAt):0))-K}),{groups:Ce,ungrouped:ne}},[we]),[ze,pe]=o.useState(new Set),le=async(te,ne,Ce)=>{if(te.session){D(null),X(te.session.id);try{await ne(te.session),D(Ce)}catch(G){const R=G instanceof Error?G.message:"";D(R?Xt(R):"Workstream action failed")}finally{X(null)}}};return n.jsxs(Vs,{surface:c==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${c==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${a??""}`,children:[l?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:r}),n.jsx("span",{className:"chip text-micro",children:de.length})]})}):null,ie.length>1&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-b border-subtle px-3 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>f(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${N===null?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:["All",n.jsx("span",{className:"tabular-nums opacity-70",children:de.length})]}),ie.map(({status:te,count:ne})=>n.jsxs("button",{type:"button",onClick:()=>f(Ce=>Ce===te?null:te),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${N===te?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[pc(te),n.jsx("span",{className:"tabular-nums opacity-70",children:ne})]},te))]}),ke&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:ke}),we.length===0?de.length===0&&d>0&&u?n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 px-6 py-10 text-center",children:[n.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.03]",children:n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:"h-5 w-5 text-secondary","aria-hidden":!0,children:n.jsx("path",{d:"M10 6v4m0 4h.01M3 10a7 7 0 1114 0 7 7 0 01-14 0z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-medium text-primary",children:"All clear"}),n.jsxs("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:["No active runs right now."," ",n.jsx("span",{className:"tabular-nums font-semibold text-[#F5B700]/90",children:d})," ",d===1?"item needs":"items need"," your attention."]})]}),n.jsxs("button",{type:"button",onClick:u,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-[#F5B700]/25 bg-[#F5B700]/[0.08] px-4 text-caption font-semibold text-[#FFE7A8] transition-colors hover:border-[#F5B700]/40 hover:bg-[#F5B700]/[0.14]",children:[n.jsx("span",{children:"Review needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:d})]})]}):n.jsx("div",{className:"flex flex-1 items-center justify-center px-4 py-10",children:n.jsx("p",{className:"text-body text-secondary",children:de.length===0?"No runs in progress.":"No runs match this filter."})}):n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-2",children:n.jsxs(he.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[ae.groups.map(te=>n.jsxs("div",{children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[n.jsx(xn,{type:"initiative",size:13,className:"opacity-90"}),n.jsx("h3",{className:"text-[15px] font-semibold text-white/90",children:Bt(te.initiativeTitle&&!Wn(te.initiativeTitle)?te.initiativeTitle:$a(te.initiativeId,"Initiative"))})]}),te.workstreams.map(ne=>{var Se,oe;const Ce=`${te.initiativeId}:${ne.workstreamId}`,G=ze.has(Ce),R=ne.rows[0]??null,z=R?mc((Se=R.session)==null?void 0:Se.agentId,(oe=R.session)==null?void 0:oe.agentName):null,B=R!=null&&R.milestoneProgress?R.milestoneProgress.reduce((ye,me)=>ye+me.total,0):null,K=R!=null&&R.milestoneProgress?R.milestoneProgress.reduce((ye,me)=>ye+me.done,0):null,re=B&&B>0?`Task ${(K??0)+1} of ${B}`:null,ge=B&&B>0?Math.round((K??0)/B*100):(R==null?void 0:R.progress)!=null?fc(R.progress):null;return n.jsxs("div",{className:"pl-4 border-l border-white/[0.08] mb-3",children:[n.jsxs("div",{className:"mb-2 flex items-start gap-2",children:[n.jsxs("div",{className:"min-w-0 flex flex-1 items-center gap-1.5",children:[n.jsx(xn,{type:"workstream",size:12,className:"flex-shrink-0 opacity-80"}),z&&n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${z.color}20`,color:z.color},children:z.name.charAt(0).toUpperCase()}),z?n.jsx("p",{className:"truncate text-[11px] font-medium",style:{color:z.color},title:z.displayLabel,children:z.displayLabel}):n.jsx("span",{className:"text-[11px] text-white/45",children:"Workstream"})]}),re&&n.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/50",children:re}),n.jsx("div",{className:"h-1 rounded-full bg-white/10 w-24",children:n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,ge??0)}%`,backgroundColor:(z==null?void 0:z.color)??"#14B8A6"}})})]})]}),n.jsx("div",{className:"space-y-2",children:ne.rows.map((ye,me)=>n.jsx(Yo,{row:ye,index:me,sliceRunByScope:E,busySessionId:T,expandedRowKey:Z,setExpandedRowKey:W,onOpenSession:p,onFocusRunId:x,onPauseWorkstream:h,onResumeWorkstream:I,onRestartSession:y,onPlayWorkstream:b,onIntervene:j,onOpenSliceDetail:w,runWorkstreamAction:le,showInitiativeLabel:!1},ye.key))}),ne.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>pe(ye=>{const me=new Set(ye);return me.has(Ce)?me.delete(Ce):me.add(Ce),me}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:G?`Hide ${ne.completedCount} completed`:`${ne.completedCount} completed`})})]},ne.workstreamId)})]},te.initiativeId)),ae.ungrouped.length>0&&n.jsxs("div",{children:[ae.groups.length>0&&n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:"Ungrouped"}),n.jsx("div",{className:"space-y-2",children:ae.ungrouped.map((te,ne)=>n.jsx(Yo,{row:te,index:ne,sliceRunByScope:E,busySessionId:T,expandedRowKey:Z,setExpandedRowKey:W,onOpenSession:p,onFocusRunId:x,onPauseWorkstream:h,onResumeWorkstream:I,onRestartSession:y,onPlayWorkstream:b,onIntervene:j,onOpenSliceDetail:w,runWorkstreamAction:le,showInitiativeLabel:!0},te.key))})]})]})})]})});function Yo({row:e,index:t,sliceRunByScope:s,busySessionId:i,expandedRowKey:r,setExpandedRowKey:a,onOpenSession:l,onFocusRunId:c,onPauseWorkstream:d,onResumeWorkstream:u,onRestartSession:p,onPlayWorkstream:x,onIntervene:b,onOpenSliceDetail:h,runWorkstreamAction:I,showInitiativeLabel:y=!0}){var Ce,G,R,z,B,K,re,ge,Se,oe;const j=nn(e.status??""),w=e.updatedAt,N=e.subtitle?e.subtitle:w?`Updated ${Pt(w)}`:null,f=y&&(e.initiativeTitle||e.initiativeId)?Bt(e.initiativeTitle&&!Wn(e.initiativeTitle)?e.initiativeTitle:$a(e.initiativeId,"Initiative")):null,T=(Ce=e.title)!=null&&Ce.trim()?e.title:"",X=ip(T)&&((G=e.workstreamTitle)!=null&&G.trim())?e.workstreamTitle:T||e.workstreamTitle||"",Z=$a(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),W=Bt(X&&!Wn(X)?X:Z),ke=N&&!rp(N)?Bt(N):null,D=fc(e.progress),E=["running","active","in_progress","working","planning","dispatching"].includes(j),de=["paused","blocked","queued","pending"].includes(j),ie=p??x,we=D===null&&["running","active","in_progress","working","planning","dispatching"].includes(j),ae=e.session?i===e.session.id:!1,ze=r===e.key,pe=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),le=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),te=e.scope==="task"?"task":e.scope==="milestone"?"milestone":e.scope==="workstream"||e.source==="slice"?"workstream":"session",ne=mc((R=e.session)==null?void 0:R.agentId,(z=e.session)==null?void 0:z.agentName);return n.jsxs(he.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.24,delay:Math.min(t,7)*.02,ease:[.22,1,.36,1]},className:"group hover-lift relative overflow-visible rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 py-2.5 cursor-pointer transition-colors hover:border-white/[0.14]",onClick:()=>h==null?void 0:h(e,le),role:"button",tabIndex:0,onKeyDown:ye=>{(ye.key==="Enter"||ye.key===" ")&&(ye.preventDefault(),h==null||h(e,le))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${tp(j)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[n.jsx("div",{className:e.status==="running"?"agent-glow-ring rounded-full":"",style:e.status==="running"?{"--agent-glow-color":ne.color}:void 0,children:n.jsx(en,{name:((B=e.session)==null?void 0:B.agentName)??"OrgX",hint:((K=e.session)==null?void 0:K.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[f?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:f}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(xn,{type:te,size:12,className:"mt-[3px] flex-shrink-0 opacity-80"}),n.jsx("p",{className:"min-w-0 line-clamp-2 text-body font-semibold leading-snug text-white",title:W,children:W})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(Ln,{tone:e.scope==="milestone"?"cyan":"lime",children:e.scope}),n.jsx("span",{className:`inline-flex rounded-full border px-2 py-[1px] text-micro font-semibold uppercase tracking-[0.08em] ${ep(j)}`,children:pc(j)}),w&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:sd(new Date(w),{addSuffix:!0})})]}),ke?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:ke,children:ke}):null,null,(D!==null||we)&&n.jsxs("div",{className:"mt-2",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro",children:[n.jsx("span",{className:"text-secondary",children:"Progress"}),n.jsx("span",{className:"font-semibold text-primary tabular-nums",children:D===null?"Live":`${D}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${D===100?" shimmer-on-complete":""}`,children:D===null?n.jsx("div",{className:"h-full w-1/3 animate-pulse rounded-full bg-[#7dd3c0]/70"}):n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,D)}%`,background:`linear-gradient(90deg, ${Go(Vo((re=e.session)==null?void 0:re.agentId)).gradient[0]}, ${Go(Vo((ge=e.session)==null?void 0:ge.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(uc,{nodes:Em({initiativeId:e.initiativeId,initiativeTitle:e.initiativeTitle,workstreamId:e.workstreamId,workstreamTitle:e.workstreamTitle,taskIds:e.taskIds,milestoneIds:e.milestoneIds,scopeProgress:e.milestoneProgress?{totalTasks:e.milestoneProgress.reduce((ye,me)=>ye+me.total,0),completedTasks:e.milestoneProgress.reduce((ye,me)=>ye+me.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((Se=e.session)==null?void 0:Se.agentName)??null,agentId:((oe=e.session)==null?void 0:oe.agentId)??null}),activeId:e.workstreamId,compact:!0})}),pe?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:ye=>{ye.stopPropagation(),a(me=>me===e.key?null:e.key)},className:"inline-flex h-6 items-center gap-1 rounded-md px-1 text-micro font-semibold text-secondary transition-colors hover:text-white",children:ze?"Hide details":"Slice details"}),ze?n.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-white/[0.08] bg-black/[0.18] px-2.5 py-2",children:[e.workstreamTitle?n.jsxs("p",{className:"text-caption text-secondary",children:["Workstream: ",n.jsx("span",{className:"text-white/90",children:e.workstreamTitle})]}):null,n.jsxs("div",{className:"flex flex-wrap gap-1.5 text-micro",children:[n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Tasks ",e.taskIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Milestones ",e.milestoneIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Artifacts ",e.artifactCount]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Needs input ",e.decisionCount]})]})]}):null]}):null,n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 border-t border-white/[0.07] pt-2",onClick:ye=>ye.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>{if(e.session){l==null||l(e.session.id);return}c==null||c(e.runId)},className:"control-pill h-7 px-2.5 text-micro font-semibold",title:e.session?"Open session detail":"Focus in Activity",children:e.session?"Open":"Focus"}),e.session&&E&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ae,onClick:()=>void I(e,d,`Paused ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Pause and return this workstream to queue",children:"Pause"}),e.session&&de&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ae,onClick:()=>void I(e,u,`Resumed ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Resume this workstream",children:"Resume"}),e.session&&ie&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ae,onClick:()=>void I(e,ie,`Restarted ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Restart this workstream",children:"Restart"}),e.session&&b&&n.jsx("button",{type:"button",disabled:ae,onClick:()=>void I(e,b,`Opened intervention for ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Intervene with context and guidance",children:"Intervene"})]})]})]})]},e.key)}const op={inbox:n.jsx("path",{d:"M22 12h-6l-2 3H10l-2-3H2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),search:n.jsxs(n.Fragment,{children:[n.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"m21 21-4.3-4.3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),activity:n.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),agents:n.jsx(n.Fragment,{children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",stroke:"currentColor",strokeWidth:"1.5",fill:"none"})}),initiative:n.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),queue:n.jsxs(n.Fragment,{children:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"M8 12h8M12 8v8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),error:n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"M12 9v4M12 17h.01",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};function Qr({icon:e="inbox",headline:t,description:s,primaryAction:i,secondaryAction:r,className:a}){return n.jsxs(he.div,{className:ue("flex flex-col items-center justify-center py-12 px-6 text-center max-w-md mx-auto",a),initial:"hidden",animate:"visible",variants:{visible:{transition:{staggerChildren:.04}}},children:[n.jsx(he.div,{className:"flex h-12 w-12 items-center justify-center rounded-xl border border-white/[0.08] bg-white/[0.04]",variants:ur,custom:0,children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",className:"text-secondary",children:op[e]})}),n.jsx(he.h4,{className:"mt-5 text-heading font-semibold text-white",variants:ur,custom:1,children:t}),n.jsx(he.p,{className:"mt-2 text-body text-secondary leading-relaxed",variants:ur,custom:2,children:s}),(i||r)&&n.jsxs(he.div,{className:"mt-5 flex items-center gap-2",variants:ur,custom:3,children:[i&&n.jsx("button",{type:"button",onClick:i.onClick,className:"control-pill px-4 text-[12px] font-medium",style:{borderColor:"rgba(191, 255, 0, 0.24)",background:"rgba(191, 255, 0, 0.09)",color:"#d8ffa1"},children:i.label}),r&&n.jsx("button",{type:"button",onClick:r.onClick,className:"control-pill px-4 text-[12px] font-medium",children:r.label})]})]})}const lp=new Set(["awaiting_input","needs_review","failed"]);function Jo(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function cp(e){var r,a;const t=e.initiativeId??((r=e.initiativeIds)==null?void 0:r[0])??"none",s=e.workstreamId??((a=e.workstreamIds)==null?void 0:a[0])??"none",i=(e.statusExplainer??"").trim().toLowerCase();return[t,s,e.status,e.primaryAction,i].join("|")}function gc(e){const t=e.filter(i=>lp.has(i.status)).sort((i,r)=>Jo(r.updatedAt??r.lastEventAt??"")-Jo(i.updatedAt??i.lastEventAt??"")),s=new Map;for(const i of t){const r=cp(i),a=s.get(r);if(!a){s.set(r,{item:i,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function dp(e){return e==="failed"?"border-red-400/30 bg-red-500/[0.10] text-red-100":e==="needs_review"?"border-amber-300/30 bg-amber-300/[0.10] text-amber-100":"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]"}function up(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function mp(e){return e==="failed"?"from-red-300/0 via-red-300/65 to-red-300/0":e==="needs_review"?"from-amber-300/0 via-amber-300/65 to-amber-300/0":"from-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function pp(e){return e.primaryAction==="resolve_decision"?"Review choices":e.primaryAction==="open_artifact"?"Open result":e.primaryAction==="retry_slice"?"Review and retry":e.primaryAction==="review_output"?"Review activity":"Open details"}function fp(e){if(e.artifactCount>0)return`${e.artifactCount} artifact${e.artifactCount===1?"":"s"} ready to review.`;if(e.blockingDecisionCount>0||e.decisionCount>0){const t=Math.max(e.blockingDecisionCount,e.decisionCount);return`${t} decision${t===1?"":"s"} need${t===1?"s":""} your input.`}return e.status==="failed"?"Execution stopped before finishing.":e.status==="needs_review"?"Output is available and needs a quick review.":"This work needs your attention to continue."}function Pa(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return Wn(s)?`${t} ${Is(s)}`:s}function hp(e){if(!e)return null;const t=Bt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function gp(e,t,s){const i=(t==null?void 0:t.trim())??"";if(i&&!Wn(i)){const a=Bt(i);if(a!=="Untitled session")return a}const r=hp(e.statusExplainer);return r||(s?Pa(s,"Workstream"):Pa(e.sliceRunId,"Slice"))}const xp=o.memo(function({sliceRuns:t,initiatives:s=[],title:i="Needs Input",className:r,showHeader:a=!0,panelStyle:l="card",onOpenDecisions:c,onFocusRunId:d,onReviewActivity:u,onOpenSliceDetail:p}){const x=o.useMemo(()=>gc(t),[t]),b=o.useMemo(()=>{const y=new Map;for(const j of s)j.id&&y.set(j.id,j.name??j.id);return y},[s]),h=o.useMemo(()=>{const y=new Map;for(const j of s)for(const w of j.workstreams??[])w.id&&(y.has(w.id)||y.set(w.id,w.name??w.id));return y},[s]),I=y=>{var j;if(y.primaryAction==="resolve_decision"){c==null||c();return}if(y.primaryAction==="review_output"||y.primaryAction==="retry_slice"){u==null||u(y);return}if(y.primaryAction==="open_artifact"){const w=(j=y.artifacts.find(N=>N.url))==null?void 0:j.url;if(w&&typeof window<"u"){window.open(w,"_blank","noopener,noreferrer");return}u==null||u(y);return}if(y.runId){d==null||d(y.runId);return}y.sliceRunId&&(d==null||d(y.sliceRunId))};return n.jsxs(Vs,{surface:l==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${l==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${r??""}`,children:[a?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:i}),n.jsx("span",{className:"chip text-micro",children:x.length})]})}):null,x.length===0?n.jsx(Qr,{icon:"inbox",headline:"No slices need attention",description:"All workstreams are running smoothly. Decisions will appear here when agents need your input."}):n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-3 py-2",children:x.map(({item:y,duplicateCount:j},w)=>{var we;const N=(Array.isArray(y.initiativeIds)&&y.initiativeIds.length>0?y.initiativeIds[0]:y.initiativeId)??null,f=(Array.isArray(y.workstreamIds)&&y.workstreamIds.length>0?y.workstreamIds[0]:y.workstreamId)??null,T=(N?b.get(N):null)??Pa(N,"Initiative"),X=y.workstreamTitle??(f?h.get(f)??null:null),Z=gp(y,X,f),W=(we=y.statusExplainer)!=null&&we.trim().length?y.statusExplainer:"Review this slice to continue execution.",ke=Bt(fp(y)),D=Bt(W),E=Bt(T),de=y.scope?y.scope.replace(/_/g," "):null,ie=y.updatedAt??y.lastEventAt??null;return n.jsxs(he.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.24,delay:Math.min(w,7)*.022,ease:[.22,1,.36,1]},className:`group hover-lift relative overflow-visible rounded-2xl border bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-white/[0.14] ${y.status==="failed"?"border-red-400/20":y.blockingDecisionCount>0?"border-amber-400/20":"border-white/[0.08]"}`,role:"button",tabIndex:0,onClick:()=>p==null?void 0:p(y),onKeyDown:ae=>{(ae.key==="Enter"||ae.key===" ")&&(ae.preventDefault(),p==null||p(y))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${mp(y.status)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex min-w-0 items-center gap-1 text-micro uppercase tracking-[0.08em] text-muted",children:[n.jsx(xn,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:E})]}),n.jsxs("p",{className:"mt-0.5 inline-flex min-w-0 items-start gap-1.5 text-body font-semibold leading-snug text-white",title:Z,children:[n.jsx(xn,{type:"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:Z})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:ke,children:ke}),D!==ke&&n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:D,children:D})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-1.5",children:[n.jsx("span",{className:`inline-flex h-6 items-center rounded-full border px-2 text-micro font-semibold uppercase tracking-[0.08em] ${dp(y.status)}`,children:up(y.status)}),de?n.jsx("span",{className:"chip text-micro capitalize",children:de}):null]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[j>1&&n.jsxs("span",{className:"chip text-micro",children:[j," similar updates"]}),typeof y.blockingDecisionCount=="number"&&y.blockingDecisionCount>0&&n.jsxs("span",{className:"chip text-micro border-red-400/30 bg-red-500/[0.1] text-red-200/90",children:["Blocks ",y.blockingDecisionCount," task",y.blockingDecisionCount===1?"":"s"]}),typeof y.decisionCount=="number"&&y.decisionCount>0&&n.jsxs("span",{className:"chip text-micro",children:[y.decisionCount," decision",y.decisionCount===1?"":"s"]}),typeof y.artifactCount=="number"&&y.artifactCount>0&&n.jsxs("span",{className:"chip text-micro",children:[y.artifactCount," artifact",y.artifactCount===1?"":"s"]}),ie&&n.jsxs("span",{children:["Updated ",Pt(ie)]})]}),y.decisionOptions&&y.decisionOptions.length>0&&y.decisionOptions.length<=3&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",onClick:ae=>ae.stopPropagation(),children:y.decisionOptions.slice(0,3).map(ae=>n.jsx("button",{type:"button",onClick:()=>p==null?void 0:p(y),className:"chip text-micro font-medium hover:bg-white/[0.08] transition-colors cursor-pointer",title:ae.description??ae.label,children:ae.label},ae.id))}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:ae=>ae.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>p==null?void 0:p(y),className:"control-pill h-7 px-2.5 text-micro font-semibold",children:"Details"}),n.jsx("button",{type:"button",onClick:()=>I(y),className:"control-pill h-7 px-2.5 text-micro font-semibold","data-tone":y.status==="failed"?"teal":void 0,children:pp(y)})]})]},y.sliceRunId)})})]})});function yp(e){if(!e)return"Unknown";const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toLocaleString():"Unknown"}function Zo(e){return e?Pt(e):"unknown"}const bp={run_completed:"text-[#BFFF00]",milestone_completed:"text-[#7dd3c0]",artifact_created:"text-cyan-200",handoff_fulfilled:"text-violet-200",decision_resolved:"text-amber-200",run_started:"text-white/80",delegation:"text-white/80"};function vp(e){var s;const t=(s=e.title)==null?void 0:s.trim();return t||e.type.replace(/_/g," ")}const wp=o.memo(function({className:t,rows:s,onFocusRunId:i,onOpenNextUp:r}){return s.length===0?n.jsx(Vs,{className:t??"",children:n.jsx("div",{className:"flex h-full min-h-[220px] items-center justify-center px-5 py-8 text-center",children:n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-medium text-primary",children:"No completed work in this scope yet."}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Completed slices will appear here with full scope, artifacts, and timeline."})]})})}):n.jsx("div",{className:`flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2 ${t??""}`,children:s.map(a=>n.jsxs("section",{className:"rounded-xl border border-subtle bg-white/[0.02] p-3",children:[n.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-body font-semibold text-primary",children:Bt(a.title)}),n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Completed ",Zo(a.completedAt)," · ",yp(a.completedAt)]}),a.statusExplainer?n.jsx("p",{className:"mt-0.5 truncate text-micro text-muted",children:Bt(a.statusExplainer)}):null]}),n.jsx(Ln,{tone:"lime",className:"whitespace-nowrap",children:"Completed"})]}),n.jsxs("div",{className:"mt-2 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Hierarchy"}),n.jsx("p",{className:"mt-1 text-caption text-primary",children:Bt([a.initiativeTitle,a.workstreamTitle].filter(Boolean).join(" > ")||"Unscoped")}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[a.scope&&n.jsx("span",{className:"chip capitalize",children:a.scope}),n.jsxs("span",{className:"chip",children:[a.taskIds.length," tasks"]}),n.jsxs("span",{className:"chip",children:[a.milestoneIds.length," milestones"]})]})]}),n.jsxs("div",{className:"mt-2 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:["Artifacts (",a.artifactCount,")"]}),a.artifacts.length>0?n.jsx("ul",{className:"mt-1.5 space-y-1.5",children:a.artifacts.map(l=>n.jsxs("li",{className:"flex items-center justify-between gap-2 text-caption",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-primary",children:Bt(l.title)}),n.jsxs("p",{className:"text-micro text-secondary",children:[l.type??"artifact"," · ",Zo(l.createdAt)]})]}),l.url?n.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-primary transition hover:bg-white/[0.08]",children:"Open"}):null]},`${a.key}:${l.id??l.title}`))}):n.jsx("p",{className:"mt-1.5 text-caption text-secondary",children:"No artifact metadata attached."})]}),n.jsxs("div",{className:"mt-2 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:["Timeline (",a.timelineEvents.length,")"]}),a.timelineEvents.length>0?n.jsx("ul",{className:"mt-1.5 space-y-1",children:a.timelineEvents.map(l=>{const c=bp[l.type]??"text-primary";return n.jsxs("li",{className:"flex items-start justify-between gap-2 text-caption",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:`truncate ${c}`,children:Bt(vp(l))}),l.description?n.jsx("p",{className:"truncate text-micro text-secondary",children:Bt(l.description)}):null]}),n.jsx("span",{className:"whitespace-nowrap text-micro text-muted",children:Pt(l.timestamp)})]},`${a.key}:event:${l.id}`)})}):n.jsx("p",{className:"mt-1.5 text-caption text-secondary",children:"No related timeline events found."})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[i?n.jsx("button",{type:"button",onClick:()=>i(a.runId),className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Open work session"}):null,r?n.jsx("button",{type:"button",onClick:r,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1 text-caption font-semibold text-[#E3FFAE] transition hover:bg-[#BFFF00]/18",children:"Connect back to Next Up"}):null]})]},a.key))})});function kp(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Ip(e){if(!e)return 0;const t=new Date(e),s=new Date;return Math.max(0,Math.ceil((t.getTime()-s.getTime())/864e5))}function Np(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function jp(e){return{id:e.id,name:e.title,status:kp(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:Ip(e.target_date),targetDate:e.target_date??null,createdAt:e.created_at??null,updatedAt:e.updated_at??e.created_at??null,activeAgents:0,totalAgents:0,description:e.summary??void 0}}const el=150,Ap=12;function tl(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function _p(){const e=new Date,t=864e5;return[{id:"init-1",name:"Q4 Feature Ship",status:"active",rawStatus:"active",priority:"high",health:38,daysRemaining:16,targetDate:new Date(e.getTime()+16*t).toISOString(),createdAt:new Date(e.getTime()-18*t).toISOString(),updatedAt:new Date(e.getTime()-5*6e4).toISOString(),activeAgents:2,totalAgents:3,description:"Finalize launch readiness for the Q4 initiative."},{id:"init-2",name:"Black Friday Email",status:"active",rawStatus:"active",priority:"medium",health:55,daysRemaining:10,targetDate:new Date(e.getTime()+10*t).toISOString(),createdAt:new Date(e.getTime()-22*t).toISOString(),updatedAt:new Date(e.getTime()-15*6e4).toISOString(),activeAgents:1,totalAgents:2,description:"Generate and validate campaign assets for holiday launch."}]}function xc(e,t=null){return Gs({queryKey:Ns.entities({type:"initiative",projectId:t}),queryFn:async()=>{var c;if(Zt())return _p();const s=[],i=(t==null?void 0:t.trim())??"";let r=0;for(let d=0;d<Ap;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(el),offset:String(r)});i&&_s(u,i);const p=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:Ht({workspaceId:i})});if(!p.ok)break;const x=await p.json(),b=x.data??[];if(s.push(...b),!!!((c=x.pagination)!=null&&c.has_more)||b.length===0)break;r+=el}const a=i.length>0&&s.some(d=>(d.command_center_id??d.commandCenterId??"").trim().length>0),l=new Map;for(const d of s){const u=l.get(d.id);if(!u){l.set(d.id,d);continue}tl(d.updated_at??d.created_at)>tl(u.updated_at??u.created_at)&&l.set(d.id,d)}return Array.from(l.values()).filter(d=>!i||!a?!0:(d.command_center_id??d.commandCenterId??"").trim()===i).filter(d=>Np(d.status)).sort((d,u)=>{const p=Date.parse(d.updated_at??d.created_at??"")||0;return(Date.parse(u.updated_at??u.created_at??"")||0)-p}).map(jp)},enabled:e,staleTime:6e4})}const fr=50,nl=8;function Sp(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Cp(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Tp(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Mp(e){const t=Tp(e.sequence);return{id:e.id,name:e.title,status:Sp(e.status),rawStatus:e.status??null,priority:e.priority??null,category:void 0,health:Math.max(0,Math.min(100,Math.round(e.progress??0))),daysRemaining:0,targetDate:e.targetDate??e.dueDate??e.etaEndAt??null,createdAt:e.createdAt??null,updatedAt:e.updatedAt??null,sequenceIndex:t,hierarchyLabel:typeof t=="number"?`I${t+1}`:void 0,activeAgents:e.activeAgents??0,totalAgents:e.totalAgents??0,description:void 0}}function Ep(e,t=null){return Gs({queryKey:Ns.liveInitiatives({limit:fr*nl,projectId:t}),queryFn:async()=>{var l;if(Zt())return[];const s=[];let i=0;for(let c=0;c<nl;c+=1){const d=new URLSearchParams({limit:String(fr),offset:String(i)});t&&t.trim().length>0&&_s(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:Ht({workspaceId:t})});if(!u.ok)break;const p=await u.json(),x=p.initiatives??[];s.push(...x);const b=typeof p.total=="number"?p.total:null,h=(l=p.pagination)==null?void 0:l.has_more;if(!(typeof h=="boolean"?h:b!==null?i+x.length<b:x.length===fr)||x.length===0)break;i+=fr}const r=(t==null?void 0:t.trim())??"",a=r.length>0&&s.some(c=>(c.command_center_id??c.commandCenterId??"").trim().length>0);return s.filter(c=>!r||!a?!0:(c.command_center_id??c.commandCenterId??"").trim()===r).filter(c=>Cp(c.status)).map(Mp)},enabled:e,staleTime:3e4})}const yc=o.createContext(null);function Rp({children:e}){const[t,s]=o.useState({artifactId:null}),i=o.useCallback((a,l)=>{s({artifactId:a,context:l})},[]),r=o.useCallback(()=>{s({artifactId:null})},[]);return n.jsx(yc.Provider,{value:{state:t,open:i,close:r},children:e})}function bc(){const e=o.useContext(yc);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Lp(e){const{running:t,blocked:s,decisionsCount:i,completedToday:r,onDecisionsClick:a,onBlockedClick:l,onNewInitiative:c}=e,d=i+s;if(t===0&&d===0&&r===0)return{key:"idle-empty",segments:[{text:"All caught up. "},c?{text:"Start something new?",color:M.lime,clickable:!0,onClick:c}:{text:"Nothing running."}]};if(t===0&&d===0)return{key:"idle-done",segments:[{text:`${r} done today`,color:M.teal},{text:" · all caught up"}]};if(s>0&&i>0){const u=s>20?"20+ blocked":`${s} blocked`;return{key:`blocked-decisions-${s}-${i}-${t}`,segments:[...t>0?[{text:`${t} running · `}]:[],{text:u,color:M.textMuted,clickable:!0,onClick:l},{text:" · "},{text:`${i} decisions`,color:M.amber,clickable:!0,onClick:a}]}}if(s>0){const u=s>20?"20+ blocked":`${s} blocked`;return{key:`blocked-${s}-${t}`,segments:[{text:u,color:M.textMuted,clickable:!0,onClick:l},...t>0?[{text:` · ${t} running`}]:[]]}}return i>0?{key:`decisions-${i}-${t}`,segments:[...t>0?[{text:`${t} running`,color:M.lime},{text:" · "}]:[],{text:`${i} decisions`,color:M.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:M.lime},{text:" · all systems go"}]}}function sl(e){const{className:t}=e,{key:s,segments:i}=Lp(e);return n.jsx("div",{className:`flex items-center gap-1.5 whitespace-nowrap text-body ${t??""}`,children:n.jsx(It,{mode:"wait",children:n.jsx(he.span,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.18,ease:[.22,1,.36,1]},className:"inline-flex flex-wrap items-baseline gap-0",children:i.map((r,a)=>r.clickable&&r.onClick?n.jsx("button",{onClick:r.onClick,className:"font-semibold underline decoration-dotted underline-offset-4 transition-opacity hover:opacity-80",style:{color:r.color},children:r.text},a):n.jsx("span",{className:r.color?"font-semibold":"text-secondary",style:r.color?{color:r.color}:void 0,children:r.text},a))},s)})})}const bx={active:"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20",paused:"text-[#F5B700] bg-[#F5B700]/10 border-[#F5B700]/20",blocked:"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20",completed:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20"},Dp={done:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20",completed:"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20",in_progress:"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20",active:"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20",blocked:"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20",todo:"text-white/60 bg-white/5 border-white/10"},vx=e=>Dp[nn(e)]??"text-white/60 bg-white/5 border-white/10",wx=e=>{const t=nn(e);return t==="active"||t==="in_progress"?"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20":t==="blocked"?"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20":t==="completed"||t==="done"?"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20":"text-white/60 bg-white/5 border-white/10"},kx=e=>{const t=nn(e);return t==="done"||t==="completed"?"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20":t==="active"||t==="in_progress"?"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20":"text-white/60 bg-white/5 border-white/10"},Ix=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Nx=e=>{const t=nn(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},zs=e=>{const t=nn(e);return t==="blocked"||t==="failed"||t==="cancelled"?M.red:t==="active"||t==="in_progress"||t==="running"?M.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?M.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?M.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},Br={codex:{id:"codex",label:"Codex",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},openai:{id:"openai",label:"OpenAI",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},anthropic:{id:"anthropic",label:"Anthropic",accent:"#F5B700",tint:"rgba(245, 183, 0, 0.18)"},openclaw:{id:"openclaw",label:"OpenClaw",accent:"#FF4D4D",tint:"rgba(255, 77, 77, 0.18)"},orgx:{id:"orgx",label:"OrgX",accent:M.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:M.teal,tint:"rgba(20, 184, 166, 0.18)"}},$p=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Lr(e,t,s,i){if(!(e==null||s>2)){if(typeof e=="string"){const r=e.trim();r.length>0&&t.push(r);return}if(Array.isArray(e)){for(const r of e)Lr(r,t,s+1,i);return}if(typeof e=="object"){if(i.has(e))return;i.add(e);for(const[r,a]of Object.entries(e)){const l=r.toLowerCase();typeof a=="string"?($p.some(c=>l.includes(c))||l.startsWith("meta")||l.endsWith("id"))&&Lr(a,t,s+1,i):typeof a=="object"&&a!==null&&Lr(a,t,s+1,i)}}}}function Pp(e){const t=e.toLowerCase();return/\bcodex\b/.test(t)||/\bcursor\b/.test(t)||t.includes("openai/codex")?"codex":t.includes("openclaw")||t.includes("clawdbot")||t.includes("moltbot")?"openclaw":t.includes("anthropic")||t.includes("claude")||t.includes("sonnet")||t.includes("opus")?"anthropic":t.includes("openai")||t.includes("chatgpt")||/\bgpt[-\s]?\d/.test(t)||/\bo[134]/.test(t)?"openai":t.includes("orgx")?"orgx":null}function js(...e){const t=[],s=new Set;for(const i of e)Lr(i,t,0,s);for(const i of t){const r=Pp(i);if(r)return Br[r]}return Br.unknown}function Fp(e){return Br[e]??Br.unknown}const Op={xs:18,sm:24,md:30};function qp({provider:e}){switch(e){case"openai":case"codex":return n.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:n.jsx("path",{fill:"currentColor",d:"M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z"})});case"anthropic":return n.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:n.jsx("path",{fill:"currentColor",d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z"})});case"openclaw":return n.jsxs("svg",{viewBox:"0 0 120 120","aria-hidden":"true",children:[n.jsx("path",{d:"M60 10C30 10 15 35 15 55C15 75 30 95 45 100V110H55V100C55 100 60 102 65 100V110H75V100C90 95 105 75 105 55C105 35 90 10 60 10Z",fill:"currentColor"}),n.jsx("path",{d:"M20 45C5 40 0 50 5 60C10 70 20 65 25 55C28 48 25 45 20 45Z",fill:"currentColor"}),n.jsx("path",{d:"M100 45C115 40 120 50 115 60C110 70 100 65 95 55C92 48 95 45 100 45Z",fill:"currentColor"}),n.jsx("circle",{cx:"45",cy:"35",r:"6",fill:"rgba(2,4,10,0.92)"}),n.jsx("circle",{cx:"75",cy:"35",r:"6",fill:"rgba(2,4,10,0.92)"})]});case"orgx":return n.jsx("img",{src:Gr,alt:"","aria-hidden":"true",className:"h-full w-full rounded-[4px] object-contain"});default:return n.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[n.jsx("circle",{cx:"12",cy:"12",r:"8",stroke:"currentColor",strokeWidth:"1.8",fill:"none"}),n.jsx("path",{d:"m12 6-2 7h3l-1 5 4-8h-3l1-4Z",fill:"currentColor"})]})}}function hi({provider:e,size:t="sm",className:s,showRing:i=!0}){const r=Fp(e),a=Op[t];return n.jsx("span",{className:ue("inline-flex items-center justify-center rounded-md",s),style:{width:a,height:a,color:r.accent,backgroundColor:r.tint,border:i?`1px solid ${r.accent}55`:"none"},title:r.label,"aria-label":r.label,children:n.jsx("span",{style:{width:Math.round(a*.66),height:Math.round(a*.66),display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(qp,{provider:e})})})}function vc({running:e,blocked:t,paused:s,size:i=36,children:r}){const a=ps(),l=e+t+s,c=o.useMemo(()=>{if(l===0)return[];const h=[];return e>0&&h.push({color:M.lime,fraction:e/l}),t>0&&h.push({color:M.red,fraction:t/l}),s>0&&h.push({color:M.amber,fraction:s/l}),h},[e,t,s,l]),d=2.5,u=(i-d)/2,p=2*Math.PI*u,x=i/2;if(l===0)return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:i,height:i},children:[n.jsx("svg",{width:i,height:i,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:n.jsx("circle",{cx:x,cy:x,r:u,fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:d})}),n.jsx("div",{className:"relative z-10",children:r})]});let b=0;return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:i,height:i},children:[n.jsxs("svg",{width:i,height:i,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:[n.jsx("circle",{cx:x,cy:x,r:u,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),c.map((h,I)=>{const y=h.fraction*p,j=-b;return b+=y,n.jsx(he.circle,{cx:x,cy:x,r:u,fill:"none",stroke:h.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${y} ${p-y}`,strokeDashoffset:j,initial:a?!1:{strokeDasharray:`0 ${p}`},animate:{strokeDasharray:`${y} ${p-y}`},transition:{duration:.5,delay:I*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},I)})]}),n.jsx("div",{className:"relative z-10",children:r})]})}const hr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function Ya(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Ja(e,t){if(typeof t=="number")return`${e}${t+1}`}const Bp=(e,t)=>{const s=Ya(e.sequence??e.order);return{id:e.id,name:e.name??"Untitled workstream",summary:e.summary??null,status:e.status??"planned",progress:typeof e.progress=="number"&&!Number.isNaN(e.progress)?Math.max(0,Math.min(100,e.progress<=1?e.progress*100:e.progress)):null,initiativeId:e.initiative_id??t,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:Ja("W",s)}},zp=(e,t)=>{const s=Ya(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled milestone",description:e.description??null,status:e.status??"planned",dueDate:e.due_date??null,initiativeId:e.initiative_id??t,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:Ja("M",s)}},Up=(e,t)=>{const s=Ya(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled task",description:e.description??null,status:e.status??"todo",priority:e.priority??null,dueDate:e.due_date??null,initiativeId:e.initiative_id??t,milestoneId:e.milestone_id??null,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:Ja("T",s)}};function ga(e){return[...e].sort((t,s)=>{const i=typeof t.sequenceIndex=="number"?t.sequenceIndex:Number.POSITIVE_INFINITY,r=typeof s.sequenceIndex=="number"?s.sequenceIndex:Number.POSITIVE_INFINITY;if(i!==r)return i-r;const a=t.createdAt?Date.parse(t.createdAt):0,l=s.createdAt?Date.parse(s.createdAt):0;return a!==l?a-l:0})}function Wp(e){const t=new Date().toISOString();return e==="init-1"?{initiativeId:e,workstreams:[{id:"ws-4",name:"Dashboard UI pass",summary:"Polish interaction details and close accessibility feedback.",status:"active",progress:70,initiativeId:e,createdAt:t},{id:"ws-5",name:"Usage tracking instrumentation",summary:"Waiting on events table access.",status:"blocked",progress:25,initiativeId:e,createdAt:t}],milestones:[{id:"ms-1",title:"UX polish complete",description:"All blocking review comments resolved.",status:"active",dueDate:null,initiativeId:e,workstreamId:"ws-4",createdAt:t}],tasks:[{id:"task-1",title:"Polish timeline controls",description:null,status:"in_progress",priority:"high",dueDate:null,initiativeId:e,milestoneId:"ms-1",workstreamId:"ws-4",createdAt:t},{id:"task-2",title:"Validate mobile overlays",description:null,status:"todo",priority:"medium",dueDate:null,initiativeId:e,milestoneId:"ms-1",workstreamId:"ws-4",createdAt:t},{id:"task-3",title:"Grant data pipeline access",description:null,status:"blocked",priority:"high",dueDate:null,initiativeId:e,milestoneId:null,workstreamId:"ws-5",createdAt:t}]}:{initiativeId:e,workstreams:[{id:"ws-9",name:"Email campaign generation",summary:"Final review of subject line variants.",status:"active",progress:55,initiativeId:e,createdAt:t}],milestones:[],tasks:[{id:"task-9",title:"Prepare launch variants",description:null,status:"in_progress",priority:"medium",dueDate:null,initiativeId:e,milestoneId:null,workstreamId:"ws-9",createdAt:t}]}}function Hp({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:i=!0}){var c;const r=iu(e),a=o.useMemo(()=>Ns.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),l=Gs({queryKey:a,enabled:i&&!!e&&r,queryFn:async()=>{if(!e)return hr;if(Zt())return Wp(e);if(!r)return{...hr,initiativeId:e};const d={};s&&(d["X-Orgx-Embed"]="true"),t&&(d.Authorization=`Bearer ${t}`);const u=Object.keys(d).length?d:void 0,p=async w=>{try{const N=new URLSearchParams({type:w,initiative_id:e,limit:"100"}),f=await fetch(`/orgx/api/entities?${N.toString()}`,{headers:u});return f.ok?await f.json():{data:[]}}catch{return{data:[]}}},[x,b,h]=await Promise.all([p("workstream"),p("milestone"),p("task")]),I=Array.isArray(x.data)?ga(x.data.map(w=>Bp(w,e))):[],y=Array.isArray(b.data)?ga(b.data.map(w=>zp(w,e))):[],j=Array.isArray(h.data)?ga(h.data.map(w=>Up(w,e))):[];return{initiativeId:e,workstreams:I,milestones:y,tasks:j}}});return{details:(r?l.data:null)??(e?{...hr,initiativeId:e}:hr),isLoading:r?l.isLoading:!1,error:r?((c=l.error)==null?void 0:c.message)??null:null,refetch:l.refetch}}function Kp(){const e=new Date().toISOString();return{generatedAt:e,agents:[{id:"eli",name:"Eli",workspace:"Q4 Feature Ship",model:"gpt-5",isDefault:!0,status:"running",currentTask:"Planning",runId:"run-1",startedAt:e,blockers:[],context:null},{id:"dana",name:"Dana",workspace:"Q4 Feature Ship",model:"claude-sonnet-4.5",isDefault:!1,status:"running",currentTask:"Dashboard UI pass",runId:"run-2",startedAt:e,blockers:["Approval pending"],context:null},{id:"mark",name:"Mark",workspace:"Black Friday Email",model:"gpt-5-mini",isDefault:!1,status:"running",currentTask:"Campaign variants",runId:"run-4",startedAt:e,blockers:[],context:null}]}}function Za({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return Gs({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Zt())return Kp();const i=await fetch("/orgx/api/agents/catalog");if(!i.ok){const r=await i.text().catch(()=>"");throw new Error(r||`Agent catalog failed (${i.status})`)}return await i.json()},enabled:e,staleTime:t,refetchInterval:s??(e?8e3:!1)})}function Li(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:M.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:M.iris,bg:"rgba(124,124,255,0.10)"}}function Vp(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function Gp(e,t){return[...t?e.tasks.filter(i=>i.workstreamId===t):e.tasks].sort((i,r)=>i.title.localeCompare(r.title))}function Xp({open:e,onClose:t,onLaunched:s}){var re,ge,Se,oe,ye,me;const i=Za({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:r}=xc(e),[a,l]=o.useState(""),[c,d]=o.useState(""),[u,p]=o.useState(""),[x,b]=o.useState(""),[h,I]=o.useState("auto"),[y,j]=o.useState(""),[w,N]=o.useState(null),[f,T]=o.useState(null),[X,Z]=o.useState("starter"),[W,ke]=o.useState(!1),[D,E]=o.useState(1),de=Zt(),ie=o.useMemo(()=>{const O=c.trim();return O?(r==null?void 0:r.find(U=>U.id===O))??null:null},[r,c]),{details:we}=Hp({initiativeId:ie?ie.id:null,enabled:e&&!!ie}),ae=o.useMemo(()=>Vp(we),[we]),ze=o.useMemo(()=>Gp(we,u||null),[we,u]),pe=((re=i.data)==null?void 0:re.agents)??[],le=o.useMemo(()=>{const O=a.trim();return O?pe.find(U=>U.id===O)??null:null},[pe,a]);o.useEffect(()=>{var U,Y;if(!e)return;const O=((U=pe.find(ce=>ce.isDefault))==null?void 0:U.id)??((Y=pe[0])==null?void 0:Y.id)??"";!a&&O&&l(O)},[pe,e,a]),o.useEffect(()=>{if(!e||c.trim())return;const O=r??[],U=O.length===1?O[0]:null;U&&d(U.id)},[r,e,c]),o.useEffect(()=>{if(!e)return;const O=(le==null?void 0:le.model)??"",U=O.includes("openrouter")?"openrouter":O.includes("anthropic")?"anthropic":O.includes("openai")?"openai":"auto";I(U)},[e,le==null?void 0:le.model,a]),o.useEffect(()=>{e&&(N(null),T(null),Z("starter"),E(1))},[e]),o.useEffect(()=>{p(""),b("")},[c]),o.useEffect(()=>{b("")},[u]),o.useEffect(()=>{e&&(y.trim().length>0||ie&&j(`Kick off: ${ie.name}`))},[y,e,ie]);const te=!!a.trim()&&!!c.trim(),ne=D===1?!!a.trim():D===2?!!c.trim():te,Ce=async()=>{var We;const O=(f==null?void 0:f.checkout)??"/orgx/api/billing/checkout",U=X&&X.trim().length>0?X.trim():"starter",ce=await(await fetch(O,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:U,billingCycle:"monthly"})})).json().catch(()=>null),qe=((We=ce==null?void 0:ce.data)==null?void 0:We.url)??(ce==null?void 0:ce.url)??null;if(!qe)throw new Error((ce==null?void 0:ce.error)??"Checkout unavailable");window.open(qe,"_blank","noopener,noreferrer")},G=async()=>{var qe;const O=(f==null?void 0:f.portal)??"/orgx/api/billing/portal",Y=await(await fetch(O,{method:"POST"})).json().catch(()=>null),ce=((qe=Y==null?void 0:Y.data)==null?void 0:qe.url)??(Y==null?void 0:Y.url)??null;if(!ce)throw new Error((Y==null?void 0:Y.error)??"Billing portal unavailable");window.open(ce,"_blank","noopener,noreferrer")},R=async()=>{if(!(!te||W)){if(de){t(),s==null||s();return}N(null),T(null),ke(!0);try{const O={agentId:a.trim(),message:y.trim()?y.trim():void 0,initiativeId:c.trim(),initiativeTitle:(ie==null?void 0:ie.name)??null,workstreamId:u.trim()?u.trim():null,taskId:x.trim()?x.trim():null,provider:h!=="auto"?h:null},U=new URLSearchParams;U.set("agentId",O.agentId),U.set("initiativeId",O.initiativeId),O.initiativeTitle&&U.set("initiativeTitle",O.initiativeTitle),O.workstreamId&&U.set("workstreamId",O.workstreamId),O.taskId&&U.set("taskId",O.taskId),O.message&&U.set("message",O.message),O.provider&&U.set("provider",O.provider);const Y=await fetch(`/orgx/api/agents/launch?${U.toString()}`,{method:"POST"}),ce=await Y.json().catch(()=>null);if(!Y.ok||!(ce!=null&&ce.ok))throw(ce==null?void 0:ce.code)==="upgrade_required"&&(T(ce.actions??null),Z(ce.requiredPlan??"starter")),new Error((ce==null?void 0:ce.error)??`Launch failed (${Y.status})`);t(),s==null||s()}catch(O){N(O instanceof Error?O.message:"Launch failed")}finally{ke(!1)}}},z=!!((ge=le==null?void 0:le.run)!=null&&ge.runId)&&!!((Se=le==null?void 0:le.run)!=null&&Se.pid),B=async()=>{var O;if(!(!((O=le==null?void 0:le.run)!=null&&O.runId)||!z||W)&&!de){N(null),ke(!0);try{const U=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(le.run.runId)}`,{method:"POST"}),Y=await U.json().catch(()=>null);if(!U.ok||!(Y!=null&&Y.ok))throw new Error((Y==null?void 0:Y.error)??`Stop failed (${U.status})`);await i.refetch()}catch(U){N(U instanceof Error?U.message:"Stop failed")}finally{ke(!1)}}},K=async()=>{var O;if(!(!((O=le==null?void 0:le.run)!=null&&O.runId)||W)){if(de){t(),s==null||s();return}N(null),ke(!0);try{const U=new URLSearchParams;U.set("runId",le.run.runId),y.trim()&&U.set("message",y.trim()),h&&h!=="auto"&&U.set("provider",h);const Y=await fetch(`/orgx/api/agents/restart?${U.toString()}`,{method:"POST"}),ce=await Y.json().catch(()=>null);if(!Y.ok||!(ce!=null&&ce.ok))throw new Error((ce==null?void 0:ce.error)??`Restart failed (${Y.status})`);t(),s==null||s()}catch(U){N(U instanceof Error?U.message:"Restart failed")}finally{ke(!1)}}};return e?n.jsx(Xr,{open:e,onClose:t,maxWidth:"max-w-2xl",children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n.jsx("div",{className:"border-b border-subtle px-5 py-4 sm:px-6",children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-heading font-semibold text-white",children:"Launch OpenClaw Agent"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:"Starts a background agent turn and scopes the resulting sessions/activity to the selected OrgX initiative."}),n.jsx("div",{className:"mt-3 inline-flex items-center gap-1 rounded-full border border-strong bg-white/[0.03] p-1 text-micro uppercase tracking-[0.12em] text-secondary",children:[[1,"Agent"],[2,"Scope"],[3,"Message"]].map(([O,U])=>n.jsxs("button",{type:"button",onClick:()=>E(O),className:ue("rounded-full px-3 py-1 transition-colors",D===O?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[O,". ",U]},O))})]}),n.jsx("button",{type:"button",onClick:t,className:"rounded-lg border border-strong bg-white/[0.03] px-3 py-1.5 text-body text-secondary hover:bg-white/[0.08] hover:text-white",children:"Close"})]})}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4 sm:px-6",children:[i.isLoading&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-4 text-body text-secondary",children:"Loading agent catalog…"}),i.error&&n.jsx("div",{className:"rounded-xl border border-rose-300/20 bg-rose-400/10 p-4 text-body text-rose-100",children:i.error.message}),n.jsx(It,{mode:"wait",children:n.jsxs(he.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.22,ease:[.16,1,.3,1]},className:"mt-3 space-y-4",children:[D===1&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Agent"}),n.jsx("select",{value:a,onChange:O=>l(O.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",children:pe.map(O=>{const U=Li(O.status);return n.jsxs("option",{value:O.id,children:[O.name," (",O.id,") · ",U.label]},O.id)})})]}),le&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-3 text-body text-secondary",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"font-medium text-primary",children:le.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${Li(le.status).color}55`,color:Li(le.status).color,backgroundColor:Li(le.status).bg},children:Li(le.status).label})]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Model:"})," ",le.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",le.workspace??"unknown"]}),((oe=le.context)==null?void 0:oe.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",le.context.initiativeTitle??le.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value:h,onChange:O=>I(O.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",children:[n.jsx("option",{value:"auto",children:"Auto (keep agent model)"}),n.jsx("option",{value:"anthropic",children:"Anthropic"}),n.jsx("option",{value:"openrouter",children:"OpenRouter"}),n.jsx("option",{value:"openai",children:"OpenAI"})]}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Selecting a provider updates the agent's default model before launch."})]}),le.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",le.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",le.run.status,")"]})]}),le.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:B,disabled:!z||W,className:"rounded-lg border border-rose-300/25 bg-rose-400/10 px-3 py-2 text-caption font-semibold text-rose-100 transition-colors hover:bg-rose-400/20 disabled:opacity-45",children:"Stop Run"}),n.jsx("button",{type:"button",onClick:K,disabled:W,className:"rounded-lg border border-strong bg-white/[0.03] px-3 py-2 text-caption font-semibold text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-45",children:"Restart"})]})]})]})]}),D===2&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Initiative Scope"}),n.jsxs("select",{value:c,onChange:O=>d(O.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",children:[n.jsx("option",{value:"",children:"Select an initiative…"}),(r??[]).map(O=>n.jsx("option",{value:O.id,children:O.name},O.id))]})]}),n.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream (optional)"}),n.jsxs("select",{value:u,onChange:O=>p(O.target.value),disabled:!ie,className:ue("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!ie&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),ae.map(O=>n.jsx("option",{value:O.id,children:O.name},O.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task (optional)"}),n.jsxs("select",{value:x,onChange:O=>b(O.target.value),disabled:!ie,className:ue("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!ie&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),ze.slice(0,80).map(O=>n.jsx("option",{value:O.id,children:O.title},O.id))]}),ze.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),D===3&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Kickoff Message"}),n.jsx("textarea",{value:y,onChange:O=>j(O.target.value),rows:4,className:"mt-1 w-full resize-none rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",placeholder:"Optional. If left blank, a default kickoff message is used."})]}),n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-3 text-body text-secondary",children:[n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Review"}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Agent"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((le==null?void 0:le.name)??a.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Initiative"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((ie==null?void 0:ie.name)??c.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:u.trim()?((ye=ae.find(O=>O.id===u))==null?void 0:ye.name)??u:"Any"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:x.trim()?((me=ze.find(O=>O.id===x))==null?void 0:me.title)??x:"Any"})]})]})]})]})]},D)}),w&&n.jsx("div",{className:"mt-3 rounded-xl border border-rose-300/20 bg-rose-400/10 px-3 py-2 text-body text-rose-100",children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("div",{children:w}),f&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void Ce().catch(O=>N(O instanceof Error?O.message:"Checkout failed")),className:"rounded-full border border-amber-200/25 bg-amber-200/10 px-3 py-1.5 text-caption font-semibold text-amber-100 transition-colors hover:bg-amber-200/15",children:"Upgrade"}),n.jsx("button",{type:"button",onClick:()=>void G().catch(O=>N(O instanceof Error?O.message:"Portal failed")),className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition-colors hover:bg-white/[0.08]",children:"Billing portal"}),f.pricing&&n.jsx("a",{href:f.pricing,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary underline decoration-white/20 hover:text-primary",children:"View pricing"})]})]})})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-subtle px-5 py-3.5 sm:px-6",children:[n.jsx("div",{className:"text-caption text-secondary",children:D===1?"Pick an agent to configure.":D===2?"Select an initiative scope (required).":te?"Launch will update sessions/activity under the selected initiative.":"Select an agent and initiative to launch."}),n.jsxs("div",{className:"flex items-center gap-2",children:[D>1&&n.jsx("button",{type:"button",onClick:()=>E(O=>O>1?O-1:O),disabled:W,className:"rounded-xl border border-strong bg-white/[0.03] px-4 py-2 text-body font-semibold text-primary transition-colors hover:bg-white/[0.08] disabled:opacity-45",children:"Back"}),D<3?n.jsx("button",{type:"button",onClick:()=>E(O=>O<3?O+1:O),disabled:!ne||W,className:ue("rounded-xl px-4 py-2 text-body font-semibold transition-colors",ne&&!W?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:ne&&!W?{backgroundColor:M.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:R,disabled:!te||W,className:ue("rounded-xl px-4 py-2 text-body font-semibold transition-colors",te&&!W?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:te&&!W?{backgroundColor:M.lime}:void 0,children:W?"Launching…":"Launch"})]})]})]})}):null}function Qp({breadcrumbs:e,typeBadge:t,onClose:s,footer:i,children:r}){return n.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 text-body text-secondary",children:[e.map((a,l)=>n.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[l>0&&n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"flex-shrink-0 text-faint",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),a.onClick?n.jsx("button",{type:"button",onClick:a.onClick,className:`truncate transition-colors hover:text-primary ${l===e.length-1?"text-primary font-medium":""}`,children:a.label}):n.jsx("span",{className:`truncate ${l===e.length-1?"text-primary font-medium":""}`,children:a.label})]},l)),t&&n.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 rounded-full border border-white/[0.1] bg-white/[0.04] px-2 py-0.5 text-micro uppercase tracking-[0.06em] text-secondary",children:[t.icon&&n.jsx(xn,{type:t.icon,size:11,className:"opacity-90"}),t.label]})]}),n.jsx("button",{type:"button",onClick:s,"aria-label":"Close detail",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full border border-strong bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08] hover:text-white",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:r}),i&&n.jsx("div",{className:"flex-shrink-0 border-t border-subtle px-5 py-3 sm:px-6",children:i})]})}const xa=10,Yp=20;function Jp(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:M.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:M.iris,bg:"rgba(124,124,255,0.10)"}}function Zp(e){return e?e.includes("error")||e.includes("fail")?M.red:e.includes("decision")||e.includes("block")?M.amber:e.includes("complete")||e.includes("success")?M.teal:e.includes("start")||e.includes("launch")?M.lime:M.iris:M.iris}const ef={hidden:{opacity:0,y:-4},visible:e=>({opacity:1,y:0,transition:{duration:.28,delay:e*.04,ease:[.16,1,.3,1]}})},gr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{duration:.22,delay:e*.04,ease:[.22,1,.36,1]}})};function tf(){return n.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"})}function nf({open:e,onClose:t,agentName:s,catalogAgent:i,sessions:r,activity:a,onSelectSession:l,onRefresh:c}){var E,de,ie,we,ae,ze;const[d,u]=o.useState(!1),[p,x]=o.useState(!1),[b,h]=o.useState(null),I=Gi(s),y=Jp((i==null?void 0:i.status)??null),j=Qa(s),w=o.useMemo(()=>{let pe=0,le=0,te=0,ne=0;for(const Ce of r)Ce.status==="running"||Ce.status==="queued"||Ce.status==="pending"?pe++:Ce.status==="blocked"?le++:Ce.status==="failed"||Ce.status==="cancelled"?te++:(Ce.status==="completed"||Ce.status==="archived")&&ne++;return{running:pe,blocked:le,failed:te,completed:ne}},[r]),N=o.useMemo(()=>[...r].sort((pe,le)=>Date.parse(le.updatedAt??le.lastEventAt??le.startedAt??"")-Date.parse(pe.updatedAt??pe.lastEventAt??pe.startedAt??"")),[r]),f=d?N:N.slice(0,xa),T=N.length>xa,X=o.useMemo(()=>[...a].sort((pe,le)=>Date.parse(le.timestamp)-Date.parse(pe.timestamp)).slice(0,Yp),[a]),Z=!!((E=i==null?void 0:i.run)!=null&&E.runId)&&!!((de=i==null?void 0:i.run)!=null&&de.pid),W=async()=>{var pe;if(!(!((pe=i==null?void 0:i.run)!=null&&pe.runId)||!Z||p)){h(null),x(!0);try{const le=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(i.run.runId)}`,{method:"POST"}),te=await le.json().catch(()=>null);if(!le.ok||!(te!=null&&te.ok))throw new Error((te==null?void 0:te.error)??`Stop failed (${le.status})`);c==null||c()}catch(le){h(le instanceof Error?le.message:"Stop failed")}finally{x(!1)}}},ke=async()=>{var pe;if(!(!((pe=i==null?void 0:i.run)!=null&&pe.runId)||p)){h(null),x(!0);try{const le=new URLSearchParams;le.set("runId",i.run.runId);const te=await fetch(`/orgx/api/agents/restart?${le.toString()}`,{method:"POST"}),ne=await te.json().catch(()=>null);if(!te.ok||!(ne!=null&&ne.ok))throw new Error((ne==null?void 0:ne.error)??`Restart failed (${te.status})`);c==null||c()}catch(le){h(le instanceof Error?le.message:"Restart failed")}finally{x(!1)}}};if(!e)return null;const D=i!=null&&i.run?n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("p",{className:"text-caption text-secondary",children:["Run ",i.run.runId.slice(0,8),"…",n.jsxs("span",{className:"text-muted ml-1",children:["(",i.run.status,")"]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:W,disabled:!Z||p,className:"rounded-md px-2.5 py-1.5 text-caption font-medium text-red-400/70 hover:bg-red-500/[0.08] hover:text-red-300 disabled:opacity-40 transition-colors",children:p?"Stopping…":"Stop"}),n.jsx("button",{type:"button",onClick:ke,disabled:p,className:"h-8 rounded-lg border border-lime/25 bg-lime/10 px-4 text-caption font-semibold text-lime transition-colors hover:bg-lime/20 disabled:opacity-40",children:p?"Restarting…":"Restart"})]})]}):void 0;return n.jsxs(Xr,{open:e,onClose:t,maxWidth:"max-w-3xl",children:[n.jsx("div",{className:"h-[2px] rounded-t-xl",style:{background:`linear-gradient(90deg, ${j}, transparent)`}}),n.jsx(Qp,{breadcrumbs:[{label:"Agents"},{label:s}],onClose:t,footer:D,children:n.jsxs("div",{className:"px-8 py-6 space-y-8",children:[n.jsxs(he.div,{className:"flex items-start gap-5",variants:ef,initial:"hidden",animate:"visible",custom:0,children:[n.jsx(vc,{running:w.running,blocked:w.blocked+w.failed,paused:0,size:72,children:n.jsx(en,{name:s,size:"lg",hint:s})}),n.jsxs("div",{className:"min-w-0 flex-1 pt-1",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("h3",{className:"text-[28px] font-medium leading-none text-white truncate",children:s}),n.jsx("span",{className:"status-pill",style:{color:y.color,backgroundColor:y.bg,borderColor:`${y.color}30`},children:y.label})]}),I&&n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted mt-2",children:I})]})]}),n.jsx(he.div,{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",variants:gr,initial:"hidden",animate:"visible",custom:1,children:[{label:"Running",value:w.running,color:M.lime},{label:"Blocked",value:w.blocked,color:M.red},{label:"Failed",value:w.failed,color:M.amber},{label:"Completed",value:w.completed,color:M.teal}].map(pe=>n.jsxs("div",{children:[n.jsx("p",{className:"section-kicker",children:pe.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:pe.value>0?pe.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:pe.value})]},pe.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs(he.div,{variants:gr,initial:"hidden",animate:"visible",custom:2,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Sessions"}),r.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No sessions recorded."}):n.jsxs("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-6",children:[f.map(pe=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[29px] top-1.5 h-2 w-2 rounded-full border border-black ring-4 ring-black",style:{backgroundColor:zs(pe.status)}}),n.jsxs("button",{onClick:()=>{l(pe.id),t()},className:"w-full text-left focus:outline-none group-hover:bg-white/[0.02] -mx-3 px-3 py-2 rounded-lg transition-colors",children:[n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsx("p",{className:"truncate text-[14px] font-medium text-white transition-colors group-hover:text-lime",children:pe.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:Pt(pe.updatedAt??pe.lastEventAt??pe.startedAt??Date.now())})]}),n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[12px] text-secondary",children:[n.jsx("span",{className:"capitalize",children:pe.status}),pe.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(pe.progress),"%"]})]})]})]})]},pe.id)),T&&n.jsx("button",{type:"button",onClick:()=>u(pe=>!pe),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${N.length-xa} older sessions`})]})]}),n.jsxs(he.div,{variants:gr,initial:"hidden",animate:"visible",custom:3,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Live Activity"}),X.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No recent activity."}):n.jsx("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-5",children:X.map((pe,le)=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[27px] top-1.5 h-1.5 w-1.5 rounded-full ring-4 ring-black",style:{backgroundColor:Zp(pe.type)}}),n.jsxs("div",{className:"flex items-start justify-between gap-4 py-0.5",children:[n.jsx("p",{className:"text-[13px] leading-relaxed text-secondary group-hover:text-white transition-colors line-clamp-2",children:pe.title??pe.summary??pe.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:Pt(pe.timestamp)})]})]},pe.id??le))})]})]}),n.jsx(tf,{}),i&&n.jsxs(he.div,{variants:gr,initial:"hidden",animate:"visible",custom:4,children:[n.jsx("p",{className:"section-kicker mb-4",children:"Configuration"}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-y-4 gap-x-8",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Provider"}),n.jsx("p",{className:"text-[14px] text-primary",children:(ie=i.model)!=null&&ie.includes("openrouter")?"OpenRouter":(we=i.model)!=null&&we.includes("anthropic")?"Anthropic":(ae=i.model)!=null&&ae.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Model"}),n.jsx("p",{className:ue("text-[14px] truncate",i.model?"text-primary":"text-muted"),children:i.model??"Not configured"})]}),i.workspace&&n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Workspace"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:i.workspace})]}),((ze=i.context)==null?void 0:ze.initiativeTitle)&&n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Initiative"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:i.context.initiativeTitle})]})]})]}),b&&n.jsx("p",{className:"rounded-md border border-red-400/30 bg-red-500/10 px-3 py-2 text-caption text-red-200",children:b})]})})]})}const xr=120,il=10,sf=24,rl=520,rf=58,af=56,of=20,lf=8,eo=new Set(["running","active","in_progress","working","planning","handoff","review"]),cf=new Set(["blocked","failed"]),df=10,uf=[{id:"orchestrator",name:"Orchestrator",role:"Coordinates cross-team execution"},{id:"engineering",name:"Engineering",role:"Builds and ships technical work"},{id:"product",name:"Product",role:"Defines features and requirements"},{id:"marketing",name:"Marketing",role:"Drives campaigns and content"},{id:"design",name:"Design",role:"Creates interfaces and experiences"},{id:"operations",name:"Operations",role:"Manages reliability and processes"}],mf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Fa=[{id:"eli",name:"Eli",role:"Engineering",aliases:[/\beli\b/i,/\borgx[\s_-]*engineering\b/i,/^\s*engineering\s*$/i]},{id:"dana",name:"Dana",role:"Product Design",aliases:[/\bdana\b/i,/\borgx[\s_-]*design\b/i,/\borgx[\s_-]*product\b/i,/\bproduct[\s_-]*design\b/i]},{id:"mark",name:"Mark",role:"Marketing",aliases:[/\bmark\b/i,/\borgx[\s_-]*marketing\b/i,/^\s*marketing\s*$/i]},{id:"sage",name:"Sage",role:"Sales",aliases:[/\bsage\b/i,/\borgx[\s_-]*sales\b/i,/^\s*sales\s*$/i]},{id:"orion",name:"Orion",role:"Operations",aliases:[/\borion\b/i,/\borgx[\s_-]*operations\b/i,/^\s*operations\s*$/i]},{id:"xandy",name:"Xandy",role:"Orchestrator",aliases:[/\bxandy\b/i,/\borgx[\s_-]*orchestrator\b/i,/^\s*orchestrator\s*$/i]},{id:"pace",name:"Pace",role:"Engineering",aliases:[/\bpace\b/i,/\borgx[\s_-]*pace\b/i]}];function mt(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function Cn(e,t){const s=mt(e),i=mt(t);if(!s&&!i)return null;const r=[s,i].filter(Boolean).join(" ");if(!r)return null;for(const a of Fa)if(a.aliases.some(l=>l.test(r)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function pf(e){const t=Cn(e.agentId,e.agentName);if(t)return t;const s=[e.groupLabel,e.title,e.runtimeLabel,e.lastEventSummary];for(const i of s){const r=Cn(null,i);if(r)return r}return null}function ff(e){const t=mt(e.runtimeClient);if(t==="codex")return"codex";if(t==="claude-code")return"claude-code";if(t==="openclaw")return"openclaw";if(t==="api")return"api";const s=[e.title,e.lastEventSummary,e.runtimeLabel,e.runtimeProvider,e.groupLabel].filter(i=>typeof i=="string"&&i.trim().length>0).join(" ").toLowerCase();return s.includes("claude-code")||s.includes("anthropic")||s.includes("claude")?"claude-code":s.includes("openclaw")?"openclaw":s.includes("codex")||s.includes("openai")?"codex":s.includes("orgx api")||s.includes("source_client=api")?"api":null}function wc(e){const t=pf(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=mt(e.agentId),i=mt(e.agentName);if(s||i)return{agentId:e.agentId??null,agentName:e.agentName??null};const r=ff(e);return r==="codex"?{agentId:"runtime:codex",agentName:"Codex"}:r==="claude-code"?{agentId:"runtime:claude-code",agentName:"Claude Code"}:r==="openclaw"?{agentId:"runtime:openclaw",agentName:"OpenClaw"}:r==="api"?{agentId:"runtime:api",agentName:"OrgX API"}:{agentId:null,agentName:null}}function hf(e){const t=wc(e),s=mt(t.agentId);if(s)return`id:${s}`;const i=mt(t.agentName);return i?`name:${i}`:"unassigned"}function gf(e){const t=e.trim();return t?mf.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function zr(e){const t=(e??"").trim();return t?Xs(t):!1}function xf(e){var t,s;return!!(zr((t=e.context)==null?void 0:t.initiativeId)||zr(((s=e.run)==null?void 0:s.initiativeId)??null))}function yr(e){if(Cn(e.agentId,e.agentName))return!0;const s=mt(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function Sn(e){const t=mt(e.status)??"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=mt(e.phase);if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const i=mt(e.state);return i==="error"?"failed":i==="stopped"?"paused":i==="stale"?"queued":eo.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function Oa(e){const t=mt(e);return t?eo.has(t)||cf.has(t):!1}function al(e){const t=mt(e);return t?eo.has(t):!1}function li(e){return e?!!(Oa(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function yf(e){return e?e.state==="active":!1}function bf(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function zn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function br(e,t){return zn(t.updatedAt??t.lastEventAt??t.startedAt)-zn(e.updatedAt??e.lastEventAt??e.startedAt)}function vf({status:e,nodes:t,onSelectSession:s,selectedSessionId:i}){const[r,a]=o.useState(!1),l=zs(e),c=e==="blocked"?"blocked":e==="failed"?"failed":"paused";return n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>a(d=>!d),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-white/[0.05]",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:l}}),n.jsxs("span",{className:"flex-1 text-body text-secondary",children:[t.length," ",c," sessions"]}),n.jsx(he.span,{animate:{rotate:r?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(It,{children:r&&n.jsx(he.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden pl-4",children:t.map((d,u)=>{const p=i===d.id,x=js(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(he.button,{onClick:()=>s(d.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.12,delay:Math.min(u*.02,.1)},className:ue("w-full rounded-lg px-2.5 py-1.5 text-left transition-colors",p?"bg-white/[0.09]":"bg-white/[0.02] hover:bg-white/[0.05]"),children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(hi,{provider:x.id,size:"xs"}),n.jsx("p",{className:"min-w-0 flex-1 truncate text-body text-bright",title:d.title,children:d.title}),n.jsx("span",{className:"text-micro text-muted",children:Pt(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const wf=o.memo(function({sessions:t,activity:s,selectedSessionId:i,onSelectSession:r,timeFilterId:a,onAgentFilter:l,agentFilter:c,onReconnect:d,onLaunched:u,connectionStatus:p,runtimeInstances:x=[],showSyntheticEntities:b=!1,autopilotState:h=null}){var Mt;const[I,y]=o.useState(new Set),[j,w]=o.useState(!1),[N,f]=o.useState(!1),[T,X]=o.useState(0),[Z,W]=o.useState(null),[ke,D]=o.useState(!1),E=Za({enabled:!0}),de=((Mt=E.data)==null?void 0:Mt.agents)??[],ie=o.useMemo(()=>Qi(a),[a]),we=o.useMemo(()=>ie===null?s:s.filter(q=>zn(q.timestamp)>=ie),[s,ie]);o.useMemo(()=>{var be,Le,tt;const q=new Map,_e=[...we].sort((at,J)=>zn(J.timestamp)-zn(at.timestamp));for(const at of _e){const J=at.runId;if(!J||q.has(J))continue;const Ue=((be=at.summary)==null?void 0:be.trim())??((Le=at.description)==null?void 0:Le.trim())??((tt=at.title)==null?void 0:tt.trim())??"";Ue.length>0&&q.set(J,Ue)}return q},[we]);const{agents:ae,hiddenGroupCount:ze,filteredOutGroupsByDate:pe,filteredOutSessionsByDate:le,visibleSessionCount:te,archivedGroups:ne,sessionCountInScope:Ce}=o.useMemo(()=>{var Ft;const q=b?t.nodes:t.nodes.filter(H=>!zr(H.initiativeId)),_e=b?de:de.filter(H=>!xf(H)),be=b?x:x.filter(H=>!zr(H.initiativeId)),Le=new Map,tt=new Map,at=[...be].sort((H,Ae)=>zn(Ae.lastEventAt??Ae.lastHeartbeatAt)-zn(H.lastEventAt??H.lastHeartbeatAt));for(const H of at){H.runId&&!Le.has(H.runId)&&Le.set(H.runId,H);const Ae=Cn(H.agentId,H.agentName??H.displayName),Ve=mt((Ae==null?void 0:Ae.agentId)??H.agentId);if(Ve){const Je=tt.get(Ve)??[];Je.push(H),tt.set(Ve,Je)}}const J=new Map;for(const H of q){const Ae=wc(H),Ve=hf(H),Je=mt(Ae.agentId),He=mt(Ae.agentName);let Ge=J.get(Ve)??null;if(!Ge&&Je&&He){const Ke=`name:${He}`,gt=J.get(Ke);gt&&(J.delete(Ke),gt.groupKey=Ve,J.set(Ve,gt),Ge=gt)}if(!Ge&&He){const Ke=Array.from(J.values()).find(gt=>mt(gt.agentName)===He);Ke&&(Ge=Ke)}Ge?(Ge.nodes.push(H),!Ge.agentId&&Ae.agentId&&(Ge.agentId=Ae.agentId),(Ge.agentName==="OrgX"||!Ge.agentName)&&Ae.agentName&&(Ge.agentName=Ae.agentName)):J.set(Ve,{groupKey:Ve,agentId:Ae.agentId,agentName:Ae.agentName??Ae.agentId??"OrgX",nodes:[H],latest:H,runtime:null,runtimeActiveCount:0})}for(const H of _e){const Ae=Cn(H.id,H.name),Ve=(Ae==null?void 0:Ae.agentId)??H.id,Je=(Ae==null?void 0:Ae.agentName)??H.name,He=mt(Ve),Ge=mt(Je),Ke=He?`id:${He}`:null,gt=Ge?`name:${Ge}`:null;let Lt=null;if(Ke&&J.has(Ke))Lt=Ke;else if(gt&&J.has(gt))Lt=gt;else{const bt=Array.from(J.entries()).find(([,Ct])=>He&&mt(Ct.agentId)===He||Ge&&mt(Ct.agentName)===Ge);Lt=(bt==null?void 0:bt[0])??null}if(Lt){const bt=J.get(Lt);bt.catalogAgent=H,!bt.agentId&&Ve&&(bt.agentId=Ve),(bt.agentName==="OrgX"||!bt.agentName)&&Je&&(bt.agentName=Je),Ke&&bt.groupKey!==Ke&&!J.has(Ke)&&(J.delete(bt.groupKey),bt.groupKey=Ke,J.set(Ke,bt))}else{const bt=Ke??gt??`catalog:${Je.toLowerCase()}`;J.set(bt,{groupKey:bt,agentId:Ve,agentName:Je,nodes:[],latest:null,catalogAgent:H,runtime:null,runtimeActiveCount:0})}}for(const H of Fa){const Ae=`orgx:${H.id}`,Ve=`id:${Ae}`;let Je=J.get(Ve)??null;if(!Je){const He=Array.from(J.entries()).find(([,Ge])=>{const Ke=Cn(Ge.agentId,Ge.agentName);return mt(Ke==null?void 0:Ke.agentId)===mt(Ae)});He&&(J.delete(He[0]),Je=He[1],Je.groupKey=Ve,J.set(Ve,Je))}if(Je||(Je={groupKey:Ve,agentId:Ae,agentName:H.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},J.set(Ve,Je)),Je.agentId=Ae,Je.agentName=H.name,!Je.catalogAgent){const He=_e.find(Ge=>{const Ke=Cn(Ge.id,Ge.name);return mt(Ke==null?void 0:Ke.agentId)===mt(Ae)});He&&(Je.catalogAgent=He)}}const Ue=new Map(Fa.map((H,Ae)=>[mt(`orgx:${H.id}`),Ae]));for(const H of J.values()){H.nodes.length>0&&(H.nodes.sort(br),H.latest=H.nodes[0]);const Ae=[],Ve=new Set;if((Ft=H.latest)!=null&&Ft.runId){const He=Le.get(H.latest.runId);He&&!Ve.has(He.id)&&(Ae.push(He),Ve.add(He.id))}for(const He of H.nodes){if(!He.runId)continue;const Ge=Le.get(He.runId);Ge&&!Ve.has(Ge.id)&&(Ae.push(Ge),Ve.add(Ge.id))}const Je=mt(H.agentId);if(Je)for(const He of tt.get(Je)??[])Ve.has(He.id)||(Ae.push(He),Ve.add(He.id));Ae.sort((He,Ge)=>zn(Ge.lastEventAt??Ge.lastHeartbeatAt)-zn(He.lastEventAt??He.lastHeartbeatAt)),H.runtime=Ae[0]??null,H.runtimeActiveCount=Ae.filter(He=>yf(He)).length}const je=Array.from(J.values()).sort((H,Ae)=>{const Ve=yr(H),Je=yr(Ae);if(Ve!==Je)return Ve?-1:1;if(Ve&&Je){const He=H.nodes.length>0||(H.runtimeActiveCount??0)>0,Ge=Ae.nodes.length>0||(Ae.runtimeActiveCount??0)>0;if(He!==Ge)return He?-1:1;if(He&&Ge){if(H.latest&&Ae.latest)return br(H.latest,Ae.latest);if(H.latest&&!Ae.latest)return-1;if(!H.latest&&Ae.latest)return 1}const Ke=Cn(H.agentId,H.agentName),gt=Cn(Ae.agentId,Ae.agentName),Lt=Ue.get(mt((Ke==null?void 0:Ke.agentId)??H.agentId))??999,bt=Ue.get(mt((gt==null?void 0:gt.agentId)??Ae.agentId))??999;if(Lt!==bt)return Lt-bt}return H.latest&&Ae.latest?br(H.latest,Ae.latest):H.latest&&!Ae.latest?-1:!H.latest&&Ae.latest?1:H.agentName.localeCompare(Ae.agentName)}),Q=Jl(a),Ee=Q.id==="live",nt=Q.minutes===null||Ee?null:Date.now()-Q.minutes*6e4,Te=[],lt=[];let ht=0,Rt=0;for(const H of je){const Ae=(H.runtimeActiveCount??0)>0,Ve=yr(H);if(H.nodes.length===0){const Ke=li(H.catalogAgent);(Ve||Ee&&(Ke||Ae))&&Te.push(H);continue}if(Ee){const Ke=H.nodes.filter(bt=>Oa(Sn(bt))),gt=H.nodes.filter(bt=>!Oa(Sn(bt))),Lt=li(H.catalogAgent);if(Ke.length===0){Ve||Lt||Ae?Te.push({...H,nodes:[],latest:null}):(ht+=1,Rt+=H.nodes.length,lt.push(H));continue}Rt+=gt.length,gt.length>0&&lt.push({...H,nodes:gt,latest:gt[0]??null}),Te.push({...H,nodes:Ke,latest:Ke[0]??null});continue}if(nt===null){Te.push(H);continue}const Je=H.nodes.filter(Ke=>al(Sn(Ke))?!0:zn(Ke.updatedAt??Ke.lastEventAt??Ke.startedAt)>=nt),He=li(H.catalogAgent);if(Je.length===0){Ve||He||Ae?Te.push({...H,nodes:[],latest:null}):(ht+=1,Rt+=H.nodes.length,lt.push(H));continue}const Ge=H.nodes.filter(Ke=>al(Sn(Ke))?!1:zn(Ke.updatedAt??Ke.lastEventAt??Ke.startedAt)<nt);Rt+=Ge.length,Ge.length>0&&lt.push({...H,nodes:Ge,latest:Ge[0]}),Te.push({...H,nodes:Je,latest:Je[0]})}return{agents:Te.slice(0,xr),hiddenGroupCount:Math.max(0,Te.length-xr),filteredOutGroupsByDate:ht,filteredOutSessionsByDate:Rt,visibleSessionCount:Te.slice(0,xr).reduce((H,Ae)=>H+Ae.nodes.length,0),archivedGroups:lt,sessionCountInScope:q.length}},[a,t.nodes,de,x,b]);o.useEffect(()=>{f(!1),X(0)},[a]);const G=o.useMemo(()=>ne.reduce((q,_e)=>q+_e.nodes.length,0),[ne]),R=o.useMemo(()=>ae.filter(q=>q.nodes.length>0).map(q=>q.groupKey),[ae]),{activeAgents:z,idleOrgxAgents:B,activeAgentCount:K}=o.useMemo(()=>{const q=[],_e=[];for(const be of ae)be.nodes.length>0||(be.runtimeActiveCount??0)>0||li(be.catalogAgent)?q.push(be):yr(be)?_e.push(be):q.push(be);return{activeAgents:q,idleOrgxAgents:_e,activeAgentCount:q.filter(be=>be.nodes.length>0||(be.runtimeActiveCount??0)>0||li(be.catalogAgent)).length}},[ae]),re=o.useMemo(()=>{if(R.length===0)return{allCollapsed:!1,allExpanded:!0};let q=0;for(const _e of R)I.has(_e)&&(q+=1);return{allCollapsed:q===R.length,allExpanded:q===0}},[I,R]),ge=o.useMemo(()=>{const q=[];for(const _e of ne)for(const be of _e.nodes)q.push({node:be,agentName:_e.agentName});return q.sort((_e,be)=>br(_e.node,be.node)),q.slice(0,(T+1)*df)},[ne,T]),Se=q=>{y(_e=>{const be=new Set(_e);return be.has(q)?be.delete(q):be.add(q),be})},oe=()=>{y(()=>re.allCollapsed?new Set:new Set(R))},ye=o.useMemo(()=>Z?ae.find(q=>q.groupKey===Z)??null:null,[ae,Z]),me=o.useMemo(()=>(ye==null?void 0:ye.nodes)??[],[ye]),O=o.useMemo(()=>{if(!ye)return[];const q=mt(ye.agentName),_e=mt(ye.agentId),be=Cn(ye.agentId,ye.agentName);return we.filter(Le=>{const tt=mt(Le.agentName),at=mt(Le.agentId),J=Cn(Le.agentId,Le.agentName);return q!==null&&tt===q||_e!==null&&at===_e||be!==null&&J!==null&&mt(be.agentId)===mt(J.agentId)})},[we,ye]),U=Ce===0,Y=de.length>0,ce=o.useRef(null),[qe,We]=o.useState(0),[Fe,L]=o.useState(0),ct=o.useCallback(q=>{const _e=q.currentTarget.scrollTop;We(be=>Math.abs(be-_e)<1?be:_e)},[]);o.useEffect(()=>{const q=ce.current;if(!q)return;const _e=()=>{const be=q.clientHeight,Le=q.scrollTop;L(tt=>tt===be?tt:be),We(tt=>Math.abs(tt-Le)<1?tt:Le)};if(_e(),typeof ResizeObserver<"u"){const be=new ResizeObserver(()=>_e());return be.observe(q),()=>be.disconnect()}return window.addEventListener("resize",_e),()=>window.removeEventListener("resize",_e)},[z.length]);const{visibleAgentGroups:Me,topVirtualSpacerPx:Qe,bottomVirtualSpacerPx:St,virtualizationEnabled:zt}=o.useMemo(()=>{if(!(z.length>sf&&Fe>0))return{visibleAgentGroups:z,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const _e=z.map(je=>{const Ee=I.has(je.groupKey)?0:Math.min(je.nodes.length,il);let nt=rf;return Ee>0&&(nt+=of+Ee*af,je.nodes.length>Ee&&(nt+=20)),nt+lf}),be=new Array(_e.length+1).fill(0);for(let je=0;je<_e.length;je+=1)be[je+1]=be[je]+_e[je];const Le=be[be.length-1],tt=Math.max(0,qe-rl),at=qe+Fe+rl;let J=0;for(;J<z.length&&be[J+1]<tt;)J+=1;let Ue=J;for(;Ue<z.length&&be[Ue]<at;)Ue+=1;return Ue<=J&&(Ue=Math.min(z.length,J+1)),{visibleAgentGroups:z.slice(J,Ue),topVirtualSpacerPx:be[J],bottomVirtualSpacerPx:Math.max(0,Le-be[Ue]),virtualizationEnabled:!0}},[z,I,qe,Fe]);return n.jsxs(Vs,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(Xp,{open:j,onClose:()=>w(!1),onLaunched:()=>{E.refetch(),u==null||u()}}),n.jsx(nf,{open:Z!==null,onClose:()=>W(null),agentName:(ye==null?void 0:ye.agentName)??"",catalogAgent:(ye==null?void 0:ye.catalogAgent)??null,sessions:me,activity:O,onSelectSession:r,onRefresh:()=>E.refetch()}),n.jsx("div",{className:"border-b border-subtle px-4 py-3.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"min-w-0 truncate text-heading font-semibold text-white",children:"Agents"}),n.jsxs("span",{className:"chip flex-shrink-0 text-caption tabular-nums",children:[K," active"]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:oe,disabled:R.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:re.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:re.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>w(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:ce,onScroll:ct,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[ae.length===0&&!U&&n.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-xl border border-subtle bg-white/[0.02] px-3 py-6 text-center",children:[n.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-faint",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx("p",{className:"text-body text-secondary",children:"No sessions match the selected activity window."})]}),ae.length===0&&U&&!d&&n.jsx(Qr,{icon:"agents",headline:"No active sessions yet",description:"Start a session to see agent conversations here."}),c&&l&&n.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-[#0AD4C4]/[0.08] px-3 py-1.5 text-caption text-[#0AD4C4]",children:[n.jsxs("span",{children:["Filtered: ",c]}),n.jsx("button",{type:"button",onClick:()=>l(null),className:"text-micro underline underline-offset-2",children:"Clear"})]}),n.jsxs("div",{className:"space-y-1.5",children:[zt&&Qe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Qe}}),Me.map(q=>{var bt;const _e=q.groupKey,be=I.has(_e),Le=q.latest,tt=Le?Sn(Le):null,at=(h==null?void 0:h.activeRunId)!=null&&(Le==null?void 0:Le.runId)!=null&&h.activeRunId===Le.runId,J=at&&(h==null?void 0:h.state)==="running"?"running":tt,Ue=at&&(h==null?void 0:h.state)==="running"&&h.activeWorkstreamTitle?`Working on ${h.activeWorkstreamTitle}`:null,je=q.nodes.length>0,Q=q.nodes.length===1,Ee=li(q.catalogAgent),nt=q.runtime??null,Te=(q.runtimeActiveCount??0)>0,lt=!je&&Te&&nt!==null,ht=je||lt,Rt=Le?i===Le.id:!1,Ft=q.agentName||((bt=q.catalogAgent)==null?void 0:bt.name)||q.agentId||"OrgX",H=Cn(q.agentId,Ft),Ae=(H==null?void 0:H.agentName)??gf(Ft),Ve=(H==null?void 0:H.role)??Gi(Ae),Je=js(q.agentId,Ae,nt==null?void 0:nt.displayName,Le==null?void 0:Le.runtimeProvider,Le==null?void 0:Le.runtimeClient),He=H===null&&(Je.id==="codex"||Je.id==="openai"||Je.id==="anthropic"||Je.id==="openclaw"),Ge=Ve?`${Ft} — ${Ve}`:Ft,Ke=be?[]:je?q.nodes.slice(0,il):[],gt=Math.max(0,je?q.nodes.length-Ke.length:0),Lt=mt(c)===mt(Ae)||mt(c)===mt(Ge);return n.jsxs(he.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:ue("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",Rt&&"border-white/20 bg-white/[0.05]",Lt&&"border-[#0AD4C4]/30",!je&&!Ee&&!Te&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{Q?r(q.nodes[0].id):lt?Se(_e):!je&&Ee?W(_e):l?l(Lt?null:Ae):Le&&r(Le.id)},className:"flex flex-1 items-start gap-2.5 rounded-lg px-1 py-0.5 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsxs("div",{className:"relative flex-shrink-0",children:[He?n.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-strong bg-white/[0.03]",children:n.jsx(hi,{provider:Je.id,size:"sm",showRing:!1})}):n.jsx(vc,{running:q.nodes.filter(Ct=>{const Et=Sn(Ct);return Et==="running"||Et==="handoff"||Et==="review"}).length,blocked:q.nodes.filter(Ct=>{const Et=Sn(Ct);return Et==="blocked"||Et==="failed"}).length,paused:q.nodes.filter(Ct=>{const Et=Sn(Ct);return Et==="paused"||Et==="cancelled"}).length,size:36,children:n.jsx(en,{name:Ae,size:"sm",hint:`${q.agentId??""} ${Ae}`})}),H&&n.jsx("span",{className:"absolute -bottom-1 -left-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-[#08090D] bg-[#08090D]",children:n.jsx("img",{src:"/orgx/live/brand/orgx-logo.png",alt:"","aria-hidden":"true",className:"h-3 w-3 rounded-full object-contain",loading:"lazy"})}),Le&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:zs(J??Le.status),borderColor:M.cardBg}}),!Le&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Ee?zs("running"):"rgba(255,255,255,0.2)",borderColor:M.cardBg}})]}),n.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[n.jsx("div",{className:"flex min-w-0 items-baseline",title:Ve?`${Ft} — ${Ve}`:Ft,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[Ae,Ve&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Ve]})]})}),Ue&&n.jsx("p",{className:"truncate text-micro text-teal-400",title:Ue,children:Ue}),n.jsx("div",{className:"flex items-center gap-1.5",children:je?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const Ct={};for(const Et of q.nodes){const Vt=Sn(Et);Ct[Vt]=(Ct[Vt]??0)+1}return Object.entries(Ct).map(([Et,Vt])=>`${Vt} ${Et}`).join(" · ")})(),children:(()=>{const Ct={};for(const Vt of q.nodes){const Qt=Sn(Vt);Ct[Qt]=(Ct[Qt]??0)+1}const Et=q.nodes.length;return Object.entries(Ct).map(([Vt,Qt])=>n.jsx("span",{style:{width:`${Qt/Et*100}%`,backgroundColor:zs(Vt)}},Vt))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:q.nodes.length})]}):Ee||Te?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("span",{className:"h-1.5 w-full",style:{backgroundColor:zs("running")}})}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:Math.max(1,q.runtimeActiveCount??0)})]}):n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]"}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-muted",style:{fontVariantNumeric:"tabular-nums"},children:"0"})]})})]})]}),n.jsx("button",{type:"button",onClick:()=>W(_e),"aria-label":`View ${Ae} details`,className:"flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-white/[0.05] hover:text-primary",children:n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 16v-4"}),n.jsx("path",{d:"M12 8h.01"})]})}),n.jsx("button",{type:"button",onClick:()=>{ht&&Se(_e)},disabled:!ht,"aria-label":ht?be?"Expand sessions":"Collapse sessions":"No sessions to expand",className:ue("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",ht?"hover:bg-white/[0.05] hover:text-primary":"cursor-default opacity-35"),children:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ue("transition-transform",ht&&!be?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(It,{initial:!1,children:ht&&!be&&n.jsx(he.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden border-t border-subtle",children:n.jsxs("div",{className:"max-h-[500px] space-y-1.5 overflow-y-auto p-2",children:[(()=>{const Ct=new Map,Et=[];for(const ot of Ke){const dt=Sn(ot);if(dt==="blocked"||dt==="paused"||dt==="failed"){const rn=`${dt}:${ot.blockerReason??""}`,an=Ct.get(rn)??[];an.push(ot),Ct.set(rn,an)}else Et.push(ot)}const Vt=[];for(const[ot,dt]of Ct)dt.length>3?Vt.push({status:ot.split(":")[0],nodes:dt}):Et.push(...dt);const Qt=(ot,dt)=>{const rn=i===ot.id,an=Sn(ot),ln=js(ot.agentName,ot.title,ot.lastEventSummary,ot);return n.jsx(he.button,{onClick:()=>r(ot.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(dt*.015,.12)},className:ue("w-full rounded-lg px-2.5 py-2 text-left transition-colors",rn?"bg-white/[0.09]":"bg-white/[0.02] hover:bg-white/[0.05]"),children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(hi,{provider:ln.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:ot.title,children:ot.title}),n.jsxs("div",{className:"flex items-center gap-1.5 text-micro text-secondary",children:[n.jsx("span",{className:"font-semibold uppercase tracking-[0.08em]",style:{color:ln.accent},children:ln.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:an}),n.jsx("span",{title:Fr(ot.updatedAt??ot.lastEventAt??ot.startedAt??Date.now()),children:Pt(ot.updatedAt??ot.lastEventAt??ot.startedAt??Date.now())})]}),ot.progress!==null&&n.jsx("div",{className:"mt-1 h-0.5 rounded-full bg-white/[0.08]",children:n.jsx("div",{className:"h-0.5 rounded-full",style:{width:`${Math.round(ot.progress)}%`,background:`linear-gradient(90deg, ${M.lime}, ${M.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:zs(an)},"aria-label":an,title:an})]})},ot.id)};return n.jsxs(n.Fragment,{children:[Et.map((ot,dt)=>Qt(ot,dt)),Vt.map(ot=>n.jsx(vf,{status:ot.status,nodes:ot.nodes,onSelectSession:r,selectedSessionId:i},`cg-${ot.status}-${ot.nodes.length}`))]})})(),gt>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",gt," older sessions hidden"]})]})})})]},_e)}),zt&&St>0&&n.jsx("div",{"aria-hidden":"true",style:{height:St}})]}),B.length>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02]",children:[n.jsxs("button",{onClick:()=>D(q=>!q),className:"flex w-full items-center gap-2 px-3 py-2 text-left text-caption text-secondary transition-colors hover:bg-white/[0.03]",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ue("transition-transform",ke?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[B.length," idle agent",B.length===1?"":"s"]})]}),n.jsx(It,{initial:!1,children:ke&&n.jsx(he.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden border-t border-subtle",children:n.jsx("div",{className:"space-y-1 p-2",children:B.map(q=>{const _e=Cn(q.agentId,q.agentName),be=(_e==null?void 0:_e.agentName)??q.agentName,Le=(_e==null?void 0:_e.role)??Gi(be);return n.jsxs("button",{type:"button",onClick:()=>W(q.groupKey),className:"flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left opacity-55 transition-colors hover:bg-white/[0.05] hover:opacity-75",children:[n.jsxs("div",{className:"relative flex-shrink-0",children:[n.jsx(en,{name:be,size:"sm",hint:`${q.agentId??""} ${be}`}),_e&&n.jsx("span",{className:"absolute -bottom-1 -left-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-[#08090D] bg-[#08090D]",children:n.jsx("img",{src:"/orgx/live/brand/orgx-logo.png",alt:"","aria-hidden":"true",className:"h-3 w-3 rounded-full object-contain",loading:"lazy"})})]}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsxs("p",{className:"truncate text-caption font-medium text-secondary",children:[be,Le&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Le]})]})}),n.jsx("span",{className:"text-micro text-muted",children:"Idle"})]},q.groupKey)})})})})]}),ze>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",xr," most recent agent groups (",ze," older groups omitted)."]}),d&&p!=="connected"&&!Y&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsx("p",{className:"px-3 pt-2 pb-1.5 text-micro uppercase tracking-[0.1em] text-muted",children:"OrgX Agent Roster"}),n.jsx("div",{className:"space-y-1 px-2 pb-2",children:uf.map(q=>n.jsxs("div",{className:"flex items-center gap-2.5 rounded-lg px-2 py-1.5 opacity-55",children:[n.jsx("div",{className:"flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-white/[0.08] bg-white/[0.03]",children:n.jsx("span",{className:"text-micro font-semibold text-secondary",children:q.name.charAt(0)})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-caption font-medium text-secondary",children:q.name}),n.jsx("p",{className:"text-micro text-muted",children:q.role})]}),n.jsx("button",{onClick:d,className:"rounded-md border border-lime/25 bg-lime/10 px-2 py-0.5 text-micro font-semibold text-lime transition-colors hover:bg-lime/20",children:"Connect"})]},q.id))})]}),le>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{f(q=>!q),N&&X(0)},className:"flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ue("transition-transform",N?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[G," archived session",G===1?"":"s",pe>0?` across ${pe} agent${pe===1?"":"s"}`:""]})]}),n.jsx(It,{initial:!1,children:N&&n.jsx(he.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsxs("div",{className:"space-y-1.5 border-t border-subtle p-2",children:[ge.map(({node:q,agentName:_e})=>{const be=Sn(q),Le=q.runtimeProvider?{id:bf(q.runtimeProvider)}:js(q.agentName,q.title,q.lastEventSummary,q);return n.jsxs("button",{onClick:()=>r(q.id),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left opacity-60 transition-colors hover:bg-white/[0.05] hover:opacity-80",children:[n.jsx(hi,{provider:Le.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"truncate text-caption font-medium text-primary",children:_e}),n.jsx("span",{className:"text-micro text-muted",title:Fr(q.updatedAt??q.lastEventAt??q.startedAt??Date.now()),children:Pt(q.updatedAt??q.lastEventAt??q.startedAt??Date.now())})]}),n.jsx("p",{className:"truncate text-micro text-secondary",children:q.title}),n.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:be})]})]},q.id)}),ge.length<G&&n.jsxs("button",{onClick:()=>X(q=>q+1),className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-1.5 text-micro text-secondary transition-colors hover:bg-white/[0.05]",children:["Load more (",G-ge.length," remaining)"]})]})})})]})]})]})}),kf=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),If=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),Nf=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),jf=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Af=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function ci(e){return e?nn(e):""}function ya(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function _f(e){return e.some(t=>kf.has(t))}function Sf(e){return e.some(t=>If.has(t))}function Cf(e){return e.some(t=>Nf.has(t))}function Tf(e){return e.some(t=>jf.has(t))}function Mf(e){return e.some(t=>Af.has(t))}function ds(e,t,s){const i=e==="in_progress"?"In progress":e==="needs_attention"?"Needs attention":e==="completed"?"Completed":e==="failed"?"Failed":"Update",r=(s==null?void 0:s.tone)??(e==="completed"?"positive":e==="failed"?"critical":e==="needs_attention"?"warning":"neutral"),a=e==="completed"||e==="failed",l=e==="needs_attention"||e==="failed";return{status:e,label:i,sentence:t,nextAction:(s==null?void 0:s.nextAction)??null,tone:r,isTerminal:a,isActionRequired:l}}function Ef(e){const t=ci(e.sessionStatus),s=ci(e.sessionPhase),i=ci(e.sessionState),r=ci(e.sliceStatus),a=ci(e.activityStatus),l=ci(e.stopReason),c=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,i,r,a,l].filter(T=>T.length>0),u=ya(e.blockingDecisionCount),p=ya(e.nonBlockingDecisionCount),x=ya(e.blockerCount),b=c==="run_failed",h=c==="run_completed"||c==="milestone_completed"||c==="decision_resolved",I=b||_f(d),y=Sf(d)||c==="decision_requested"||u>0||e.decisionRequired===!0,j=Cf(d)||x>0,w=h||Tf(d),N=Mf(d)||c==="run_started";if(I)return ds("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(w&&!y&&!I&&x===0&&!e.blockerReason)return p>0?ds("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):ds("completed","Execution completed successfully.",{tone:"positive"});if(y||j)return u>0||e.decisionRequired===!0||c==="decision_requested"?ds("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):ds("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:j?"critical":"warning"});if(w)return p>0?ds("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):ds("completed","Execution completed successfully.",{tone:"positive"});if(N){const T=p>0?`Running with ${p} optional decision${p===1?"":"s"} available.`:"Running.";return ds("in_progress",T,{tone:"neutral"})}return ds("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const ba=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Rf(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Us(e,t){const s=[];let i=0,r=0;ba.lastIndex=0;for(let a=ba.exec(e);a;a=ba.exec(e)){const[l]=a,c=a.index;c>i&&s.push(e.slice(i,c));const d=`${t}-${r++}`,u=a[1],p=a[2],x=a[3],b=a[4],h=a[5],I=a[6],y=a[7];u&&p&&Rf(p)?s.push(n.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-[#D8FFA1] underline decoration-white/35 underline-offset-2 transition hover:text-[#ECFFC6]",children:u},d)):x?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:x},d)):b||h?s.push(n.jsx("strong",{className:"font-semibold text-white",children:b??h},d)):I||y?s.push(n.jsx("em",{className:"italic text-bright",children:I??y},d)):s.push(l),i=c+l.length}return i<e.length&&s.push(e.slice(i)),s}function Lf(e,t){const s=e.split(`
204
+ `),i=[];return s.forEach((r,a)=>{i.push(...Us(r,`${t}-line-${a}`)),a<s.length-1&&i.push(n.jsx("br",{},`${t}-br-${a}`))}),i}function Dr(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Df(e){const t=Dr(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function $f(e){const t=e.trim(),s=t.startsWith(":"),i=t.endsWith(":");return s&&i?"center":i?"right":"left"}function Pf(e){const t=e.replace(/\r\n/g,`
205
+ `).split(`
206
+ `),s=[];let i=0;for(;i<t.length;){const r=t[i]??"",a=r.trim();if(!a){i+=1;continue}const l=r.includes("|"),c=t[i+1]??"";if(l&&c.includes("|")&&Df(c)){const b=Dr(r),I=Dr(c).map(j=>$f(j));i+=2;const y=[];for(;i<t.length;){const j=t[i]??"";if(!j.trim()||!j.includes("|"))break;y.push(Dr(j)),i+=1}s.push(n.jsx("div",{className:"overflow-x-auto rounded-xl border border-white/[0.1] bg-black/25",children:n.jsxs("table",{className:"min-w-full border-collapse text-left",children:[n.jsx("thead",{children:n.jsx("tr",{className:"border-b border-white/[0.08] bg-white/[0.03]",children:b.map((j,w)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:I[w]??"left"},children:Us(j,`tbl-h-${i}-${w}`)},`tbl-h-${w}`))})}),n.jsx("tbody",{children:y.map((j,w)=>n.jsx("tr",{className:w<y.length-1?"border-b border-subtle":void 0,children:b.map((N,f)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:I[f]??"left"},children:Us(j[f]??"",`tbl-r-${i}-${w}-${f}`)},`tbl-r-${w}-c-${f}`))},`tbl-r-${w}`))})]})},`tbl-${i}`));continue}if(a.startsWith("```")){const b=a.slice(3).trim(),h=[];for(i+=1;i<t.length&&!(t[i]??"").trim().startsWith("```");)h.push(t[i]??""),i+=1;i<t.length&&(i+=1),s.push(n.jsxs("div",{className:"rounded-xl border border-white/[0.1] bg-black/40 p-3",children:[b&&n.jsx("p",{className:"mb-1 text-micro uppercase tracking-[0.12em] text-muted",children:b}),n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:n.jsx("code",{children:h.join(`
207
+ `)})})]},`code-${i}`));continue}const d=a.match(/^(#{1,3})\s+(.+)$/);if(d){const b=d[1].length,h=d[2],I=b===1?"text-title font-semibold":b===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:ue("tracking-[-0.01em] text-white",I),children:Us(h,`h-${i}`)},`h-${i}`)),i+=1;continue}if(r.match(/^\s*[-*]\s+(.+)$/)){const b=[];for(;i<t.length;){const I=(t[i]??"").match(/^\s*[-*]\s+(.+)$/);if(!I)break;b.push(I[1]),i+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:b.map((h,I)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:Us(h,`ul-${i}-${I}`)},`ul-${i}-${I}`))},`ul-${i}`));continue}if(r.match(/^\s*\d+\.\s+(.+)$/)){const b=[];for(;i<t.length;){const I=(t[i]??"").match(/^\s*\d+\.\s+(.+)$/);if(!I)break;b.push(I[1]),i+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:b.map((h,I)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:Us(h,`ol-${i}-${I}`)},`ol-${i}-${I}`))},`ol-${i}`));continue}const x=[];for(;i<t.length;){const b=t[i]??"",h=b.trim();if(!h||/^(#{1,3})\s+/.test(h)||/^\s*[-*]\s+/.test(b)||/^\s*\d+\.\s+/.test(b)||h.startsWith("```"))break;x.push(b),i+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Lf(x.join(`
208
+ `),`p-${i}`)},`p-${i}`))}return s}function zi({text:e,mode:t="inline",className:s}){const i=e.replace(/\r\n/g,`
209
+ `);return i.trim()?t==="inline"?n.jsx("span",{className:s,children:Us(i,"inline")}):n.jsx("div",{className:ue("space-y-2",s),children:Pf(i)}):null}function kc(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ff(e){if(!e)return;const t=kc(e.metadata);return t?{...e,...t}:e}const Ic={run_started:{icon:"play",label:"Run started",color:M.teal},run_completed:{icon:"check_circle",label:"Run completed",color:M.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:M.red},artifact_created:{icon:"file",label:"Artifact",color:M.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:M.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:M.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:M.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:M.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:M.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:M.red},milestone_completed:{icon:"flag",label:"Milestone",color:M.cyan},delegation:{icon:"workflow",label:"Delegation",color:M.iris}};function Jn(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function qa(e){return e?e.toLowerCase():""}function Of(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,Jn(t,["source","event","eventType","artifact_type","action","kind"]),Jn(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function qf(e,t){const s=qa(Jn(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:M.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:M.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:M.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:M.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:M.cyan}:Ic.artifact_created}function Bf(e){const t=Ff(kc(e.metadata)),s=Of(e,t),i=qa(Jn(t,["source"])),r=qa(Jn(t,["action"])),a=Jn(t,["event","event_name","eventName"]);if(a==="auto_continue_started"||a==="auto_continue_stopped"||a==="autopilot_transition"||a==="autopilot_slice_result"||a==="autopilot_slice_finished"){if(a==="auto_continue_started"||a==="autopilot_transition"&&Jn(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:M.teal};if(a==="auto_continue_stopped"){const c=Jn(t,["stop_reason"]);return c==="error"||c==="blocked"?{icon:"infinity",label:"Needs attention",color:M.red}:c==="budget_exhausted"?{icon:"infinity",label:"Paused",color:M.amber}:{icon:"infinity",label:"Paused",color:M.amber}}if(a==="autopilot_transition"){const c=Jn(t,["new_state"]);return c==="blocked"||c==="error"?{icon:"infinity",label:"Needs attention",color:M.red}:{icon:"infinity",label:"In progress",color:M.teal}}const l=Jn(t,["parsed_status","status"]);return l==="completed"||l==="success"?{icon:"check_circle",label:"Completed",color:M.lime}:l==="blocked"||l==="needs_decision"?{icon:"infinity",label:"Needs attention",color:M.amber}:{icon:"infinity",label:"In progress",color:M.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:M.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:M.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:M.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:M.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:M.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:M.iris};if(i==="local_openclaw")return{icon:"terminal",label:"Local",color:M.teal};if(e.type==="artifact_created")return qf(t,s);if(e.type==="decision_resolved")return r==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:M.red}:{icon:"shield_check",label:"Decision approved",color:M.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Started",color:M.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:M.teal}}return Ic[e.type]??{icon:"message",label:"Activity",color:M.textMuted}}function zf({icon:e,size:t=14,className:s}){const i={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",className:s};switch(e){case"play":return n.jsx("svg",{...i,children:n.jsx("path",{d:"m8 6 10 6-10 6z"})});case"check_circle":return n.jsxs("svg",{...i,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m8.5 12 2.5 2.5 4.5-5"})]});case"alert_triangle":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"m12 3 9 16H3z"}),n.jsx("path",{d:"M12 9v4"}),n.jsx("path",{d:"M12 17h.01"})]});case"file":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),n.jsx("path",{d:"M14 2v5h5"})]});case"file_code":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),n.jsx("path",{d:"M14 2v5h5"}),n.jsx("path",{d:"m10 13-2 2 2 2"}),n.jsx("path",{d:"m14 13 2 2-2 2"})]});case"git_commit":return n.jsxs("svg",{...i,children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M3 12h6M15 12h6"})]});case"shield":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"M12 9v4"}),n.jsx("path",{d:"M12 16h.01"})]});case"shield_check":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"shield_x":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m10 10 4 4M14 10l-4 4"})]});case"handoff":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M7 8h6a3 3 0 1 1 0 6H8"}),n.jsx("path",{d:"m10 14-3 3-3-3"}),n.jsx("path",{d:"M17 10h-4"})]});case"handoff_claimed":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M8.5 12.5 12 9l3.5 3.5"}),n.jsx("path",{d:"M6 14h12"}),n.jsx("path",{d:"M7 18h10"})]});case"sparkles":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"m12 3 1.5 3.5L17 8l-3.5 1.5L12 13l-1.5-3.5L7 8l3.5-1.5z"}),n.jsx("path",{d:"m5 14 .8 1.8L8 16.6l-2.2.8L5 19l-.8-1.6L2 16.6l2.2-.8z"}),n.jsx("path",{d:"m19 14 .8 1.8 2.2.8-2.2.8L19 19l-.8-1.6-2.2-.8 2.2-.8z"})]});case"octagon_x":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"m10.2 3-5.8 3.3v11.4L10.2 21h3.6l5.8-3.3V6.3L13.8 3z"}),n.jsx("path",{d:"m9 9 6 6M15 9l-6 6"})]});case"flag":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1"})]});case"workflow":return n.jsx(ac,{size:t,className:s,strokeWidth:1.8});case"memory_sync":return n.jsxs("svg",{...i,children:[n.jsx("ellipse",{cx:"12",cy:"5.5",rx:"6.5",ry:"2.5"}),n.jsx("path",{d:"M5.5 5.5v6c0 1.4 2.9 2.5 6.5 2.5s6.5-1.1 6.5-2.5v-6"}),n.jsx("path",{d:"m8 17-2 2 2 2"}),n.jsx("path",{d:"M16 17l2 2-2 2"})]});case"heartbeat":return n.jsx("svg",{...i,children:n.jsx("path",{d:"M3 12h4l2-4 3 8 2-4h7"})});case"checkpoint":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3v6"}),n.jsx("path",{d:"M8 5h8"}),n.jsx("path",{d:"M7 11h10v10H7z"}),n.jsx("path",{d:"M9 14h6"})]});case"quality_gate":return n.jsxs("svg",{...i,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"route":return n.jsxs("svg",{...i,children:[n.jsx("circle",{cx:"6",cy:"6",r:"2"}),n.jsx("circle",{cx:"18",cy:"18",r:"2"}),n.jsx("path",{d:"M8 6h4a4 4 0 0 1 4 4v6"}),n.jsx("path",{d:"M16 6h2"})]});case"terminal":return n.jsxs("svg",{...i,children:[n.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),n.jsx("path",{d:"m7 9 3 3-3 3"}),n.jsx("path",{d:"M13 15h4"})]});case"compass":return n.jsxs("svg",{...i,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m10 10 6-2-2 6-6 2z"})]});case"infinity":return n.jsx("svg",{...i,children:n.jsx("path",{d:"M18.178 8c5.096 0 5.096 8 0 8-5.095 0-7.133-8-12.739-8-4.585 0-4.585 8 0 8 5.606 0 7.644-8 12.74-8z"})});case"message":default:return n.jsx("svg",{...i,children:n.jsx("path",{d:"M21 12a8 8 0 0 1-8 8H7l-4 2 1.5-4A8 8 0 1 1 21 12z"})})}}function Ur(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ba(e){if(!e)return;const t=Ur(e.metadata);return t?{...e,...t}:e}function Uf(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function Wf(e){let t=0;for(const s of e){const i=Ba(Ur(s.metadata)),r=i==null?void 0:i.costTotal;typeof r=="number"&&(t+=r)}return t<=0?null:t<.01?"<$0.01":`$${t.toFixed(2)}`}const Hf=o.memo(function({items:t,session:s,agentName:i,onBack:r,onOpenItem:a}){const[l,c]=o.useState(!1),d=o.useMemo(()=>[...t].sort((h,I)=>Date.parse(h.timestamp)-Date.parse(I.timestamp)),[t]),u=o.useMemo(()=>Wf(d),[d]),p=o.useMemo(()=>{if(d.length<2)return null;const h=Date.parse(d[0].timestamp),y=Date.parse(d[d.length-1].timestamp)-h;return y<6e4?`${Math.round(y/1e3)}s`:y<36e5?`${Math.round(y/6e4)}m`:`${(y/36e5).toFixed(1)}h`},[d]),x=o.useMemo(()=>{let h=null,I=null,y=null,j=null,w=null;for(const f of d){const T=Ba(Ur(f.metadata));if(T&&(!h&&typeof T.domain=="string"&&(h=T.domain),!I&&typeof T.provider=="string"&&(I=T.provider),!y&&typeof T.model=="string"&&(y=T.model),!j&&typeof T.spawn_guard_model_tier=="string"&&(j=T.spawn_guard_model_tier),!w&&typeof T.kickoff_context_hash=="string"&&(w=T.kickoff_context_hash),h&&(I||y)&&j&&w))break}return!(h||I||y||j||w)?null:{domain:h,provider:I,model:y,modelTier:j,kickoffContextHash:w}},[d]),b=(s==null?void 0:s.title)??i??"Session";return n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-3",children:[n.jsxs("button",{onClick:r,className:"mb-2 flex items-center gap-1.5 text-caption text-secondary transition-colors hover:text-primary",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})}),"Back to timeline"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:M.lime,boxShadow:`0 0 12px ${M.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:st(b)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-micro text-secondary",children:[i&&n.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-subtle px-1 py-0.5",children:[n.jsx(en,{name:i,hint:(s==null?void 0:s.id)??(s==null?void 0:s.runId)??null,size:"xs"}),n.jsx("span",{children:i})]}),n.jsxs("span",{children:[d.length," turn",d.length!==1?"s":""]}),p&&n.jsx("span",{children:p}),u&&n.jsx("span",{className:"text-muted",children:u}),(x==null?void 0:x.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:st(x.domain)}),(s==null?void 0:s.status)&&n.jsx("span",{className:"rounded-full px-1.5 py-0.5 text-micro uppercase tracking-wider",style:{backgroundColor:s.status==="running"?`${M.lime}20`:s.status==="failed"?`${M.red}20`:`${M.teal}20`,color:s.status==="running"?M.lime:s.status==="failed"?M.red:M.teal},children:s.status}),x&&(x.provider||x.model||x.modelTier||x.kickoffContextHash)&&n.jsxs("button",{type:"button",onClick:()=>c(h=>!h),className:"inline-flex items-center gap-1 text-micro text-muted transition-colors hover:text-secondary",children:[n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:`transition-transform duration-150 ${l?"rotate-180":""}`,children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),"Info"]})]}),l&&x&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(x.provider||x.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[x.provider?`${st(x.provider)} · `:"",x.model?Hi(x.model):"—"]}),x.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",st(x.modelTier)]}),x.kickoffContextHash&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 font-mono text-secondary",children:["kickoff ",x.kickoffContextHash.slice(0,8),"…"]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:[n.jsx(It,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${M.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((h,I)=>{var W;const y=Bf(h),j=y.color,w=(W=Ba(Ur(h.metadata)))==null?void 0:W.model,N=typeof w=="string"?Hi(w):null,f=st(h.title??""),T=h.type==="run_failed",X=h.type==="artifact_created",Z=h.type==="decision_requested"||h.type==="decision_resolved";return n.jsxs(he.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:I*.02},onClick:()=>a==null?void 0:a(h),className:"group relative flex w-full items-start gap-2.5 rounded-lg py-1.5 pl-0 pr-2 text-left transition-colors hover:bg-white/[0.02] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/35 focus-visible:ring-offset-1 focus-visible:ring-offset-[#02040A]",children:[n.jsx("span",{className:"relative z-10 mt-1.5 flex h-[15px] w-[15px] flex-shrink-0 items-center justify-center rounded-full text-[8px]",style:{backgroundColor:`${j}20`,color:j,border:`1px solid ${j}40`},children:n.jsx(zf,{icon:y.icon,size:8,className:"opacity-95"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:`text-body leading-snug ${T?"text-red-400":Z?"text-amber-300":X?"text-cyan-300":"text-bright"}`,children:f}),h.summary&&h.summary!==f&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:st(h.summary)})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-0.5 pt-0.5",children:[n.jsx("span",{className:"text-micro text-muted",title:Fr(h.timestamp),children:Uf(h.timestamp)}),N&&n.jsx("span",{className:"text-micro text-faint",children:N})]})]},h.id)})})]})}),d.length===0&&n.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-center",children:[n.jsx("p",{className:"text-body text-secondary",children:"No activity in this session yet."}),n.jsx("p",{className:"text-caption text-muted animate-pulse",children:"Activity may take a moment to appear."})]}),d.length>0&&n.jsxs("div",{className:"mt-4 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2 text-micro text-muted",children:[d.length," turn",d.length!==1?"s":"",p?` over ${p}`:"",u?` · ${u}`:""," · ",n.jsx("span",{title:Fr(d[d.length-1].timestamp),children:Pt(d[d.length-1].timestamp)})]})]})]})});function Kf({completedCount:e,decisionsCount:t,blockerCount:s,visible:i,onDismiss:r}){if(!(e>0||t>0||s>0))return null;const l=[];return e>0&&l.push(`${e} task${e===1?"":"s"} completed`),t>0&&l.push(`${t} need${t===1?"s":""} decisions`),s>0&&l.push(`${s} new blocker${s===1?"":"s"}`),n.jsx(It,{children:i&&n.jsx(he.div,{initial:{opacity:0,height:0,marginBottom:0},animate:{opacity:1,height:"auto",marginBottom:12},exit:{opacity:0,height:0,marginBottom:0},transition:{duration:.3,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{className:"rounded-xl px-4 py-3",style:{backgroundColor:`${M.teal}08`,border:`1px solid ${M.teal}20`},children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"While you were away"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:l.join(" · ")})]}),n.jsx("button",{onClick:r,className:"flex-shrink-0 rounded-md px-2.5 py-1 text-caption font-medium text-secondary transition-colors hover:bg-white/[0.06] hover:text-white",children:"Got it"})]})})})})}const Vf={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}},qi={pr:"#BFFF00",commit:"#BFFF00",test:"#67e8f9",doc:"#0AD4C4",artifact:"#F5B700"};function ol(e){if(!e)return"#67e8f9";const t=e.toLowerCase();return t.includes("code")||t.includes("pull")||t.includes("commit")||t.includes("pr")?qi.pr:t.includes("doc")||t.includes("spec")?qi.doc:t.includes("test")?qi.test:qi.artifact}const Gf={running:"#BFFF00",blocked:"#FF6B88",queued:"rgba(255,255,255,0.5)",completed:"rgba(191,255,0,0.5)",idle:"rgba(255,255,255,0.3)"};function Xf({renderKey:e,displayTitle:t,headline:s,contextLabel:i,detailText:r,displayAgentName:a,railColor:l,statusColor:c,userStateLabel:d,userStateWhy:u,relativeTime:p,timeLabel:x,isRecent:b,enableMotion:h,onOpen:I,ariaLabel:y,artifactSnippet:j,evidenceChips:w,actorCategory:N,queuePosition:f}){const T=(w==null?void 0:w.slice(0,2))??[],X=((w==null?void 0:w.length)??0)-T.length,Z="group w-full rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3 text-left transition-colors hover:border-strong hover:bg-white/[0.05] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/45 cv-auto",W=N==="system",ke=n.jsxs("div",{className:ue("flex items-start gap-3",W&&"opacity-55"),children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(en,{name:N==="user"?"You":a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:ue("absolute inset-y-0 left-0 w-[2px] rounded-full",b&&!W&&"pulse-soft"),style:{backgroundColor:l,boxShadow:W?"none":`0 0 14px ${l}66`}}),n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:ue("truncate text-caption",W?"text-muted italic":"text-secondary"),title:i,children:W?`OrgX · ${i}`:i}),n.jsx("p",{className:ue("mt-0.5 line-clamp-1 break-words text-body font-semibold leading-snug",W?"text-secondary":"text-bright"),children:s||t})]}),n.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[n.jsx("span",{className:"text-caption text-secondary",children:x}),n.jsx("span",{className:"text-micro text-muted",children:p})]})]}),j?n.jsxs("div",{className:"mt-2 flex items-center gap-2 rounded-lg border px-2.5 py-1.5",style:{borderColor:`${ol(j.typeBadge)}33`,backgroundColor:`${ol(j.typeBadge)}0A`},children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0 opacity-60",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsxs("span",{className:"min-w-0 flex-1 truncate text-caption",children:[j.typeBadge&&n.jsxs("span",{className:"mr-1.5 text-micro font-semibold uppercase tracking-wider opacity-70",children:["[",j.typeBadge,"]"]}),n.jsx("span",{className:"font-semibold text-bright",children:j.title??j.label}),j.preview&&!j.title&&n.jsx("span",{className:"ml-1.5 opacity-60",children:j.preview})]}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0 opacity-40",children:n.jsx("path",{d:"m9 18 6-6-6-6"})})]}):r?n.jsx("div",{className:"mt-1.5 line-clamp-2 text-caption leading-relaxed text-secondary",children:n.jsx(zi,{mode:"inline",text:r})}):null,T.length>0&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[T.map(D=>{const E=qi[D.kind];return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro font-semibold uppercase tracking-wider",style:{color:E,backgroundColor:`${E}14`,border:`1px solid ${E}30`},children:[D.kind==="pr"&&"PR",D.kind==="commit"&&"Commit",D.kind==="test"&&"Tests",D.kind==="doc"&&"Doc",D.kind==="artifact"&&"Artifact",n.jsx("span",{className:"font-normal normal-case tracking-normal",style:{color:`${E}CC`},children:D.label})]},`${D.kind}-${D.label}`)}),X>0&&n.jsxs("span",{className:"text-[10px] text-muted",children:["+",X," more"]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-semibold tracking-[0.01em]",style:{borderColor:`${c??l}55`,backgroundColor:`${c??l}1A`,color:c??l},title:u,children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:c??l}}),d]}),n.jsx("span",{className:"inline-flex max-w-[220px] items-center gap-1 rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",title:a,children:n.jsx("span",{className:"truncate",children:a})}),f&&(()=>{const D=Gf[f.state]??"rgba(255,255,255,0.3)";return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-semibold tracking-[0.01em]",style:{borderColor:`${D}55`,backgroundColor:`${D}1A`,color:D},children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:D}}),f.state==="running"?"Active":`#${f.rank}`]})})()]})]})]});return h?n.jsx(he.button,{type:"button",variants:Vf,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:I,className:Z,"aria-label":y,children:ke},e):n.jsx("button",{type:"button",onClick:I,className:ue(Z,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":y,children:ke},e)}function Qf({open:e,onClose:t,children:s}){return n.jsx(Xr,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function Yf(e){const t=e.metadata??{},s=e.phase??e.state??t.phase??"",i=e.state??"",r=t.event??t.event_name??"";if(s==="completed"||r==="auto_continue_started"||i==="completed")return"teal";if(s==="blocked"||i==="blocked"||i==="error"||r==="auto_continue_stopped"){const a=t.stop_reason??"";return a==="error"||a==="blocked"?"red":a==="budget_exhausted"||a==="stopped"?"amber":s==="blocked"||i==="error"?"red":"amber"}return e.decisionRequired||i==="needs_input"?"amber":"neutral"}const Jf={teal:{border:"border-[#0AD4C4]/20",bg:"bg-[#0AD4C4]/[0.04]",dot:"bg-[#0AD4C4]",label:"text-[#7AEDE5]"},amber:{border:"border-[#F5B700]/20",bg:"bg-[#F5B700]/[0.04]",dot:"bg-[#F5B700]",label:"text-[#FFE7A8]"},red:{border:"border-[#FF6B6B]/20",bg:"bg-[#FF6B6B]/[0.04]",dot:"bg-[#FF6B6B]",label:"text-[#FFA8A8]"},neutral:{border:"border-white/[0.04]",bg:"bg-white/[0.02]",dot:"bg-white/40",label:"text-secondary"}};function Zf({item:e,className:t}){var u,p,x;const s=o.useMemo(()=>hd(e),[e]),i=Yf(e),r=Jf[i],a=typeof((u=e.metadata)==null?void 0:u.agent_name)=="string"?e.metadata.agent_name:typeof((p=e.metadata)==null?void 0:p.agentName)=="string"?e.metadata.agentName:e.agentName??"OrgX",l=((x=e.type)==null?void 0:x.replace(/_/g," "))??"activity",d=s.taskDescription||s.outcomeDescription||s.nextStep?null:`${a} recorded a ${l}`;return n.jsxs("div",{className:`rounded-lg border ${r.border} ${r.bg} p-6 space-y-5 ${t??""}`,children:[(s.taskDescription||d)&&n.jsx(va,{label:"Task",value:s.taskDescription??d,styles:r}),s.outcomeDescription&&n.jsx(va,{label:"Outcome",value:s.outcomeDescription,styles:r}),s.nextStep&&n.jsx(va,{label:"Next step",value:s.nextStep,styles:r})]})}function va({label:e,value:t,styles:s}){return n.jsx("div",{className:"flex items-start gap-4",children:n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:`text-micro font-semibold uppercase tracking-wider ${s.label}`,children:e}),n.jsx("p",{className:"text-body leading-relaxed text-primary mt-1",children:t})]})})}const ll=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),eh=[{id:"eli",name:"Eli",handle:"eli",domain:"engineering",domainLabel:"Engineering",role:"Engineering"},{id:"dana",name:"Dana",handle:"dana",domain:"design",domainLabel:"Product Design",role:"Product Design"},{id:"mark",name:"Mark",handle:"mark",domain:"marketing",domainLabel:"Marketing",role:"Marketing"},{id:"sage",name:"Sage",handle:"sage",domain:"sales",domainLabel:"Sales",role:"Sales"},{id:"orion",name:"Orion",handle:"orion",domain:"operations",domainLabel:"Operations",role:"Operations"},{id:"pace",name:"Pace",handle:"pace",domain:"engineering",domainLabel:"Engineering",role:"Engineering"}],Di=[{id:"auto",label:"Auto (best available)",shortLabel:"Auto",accent:"#8F9AB7",icon:"auto"},{id:"anthropic",label:"Claude Code",shortLabel:"Claude",accent:"#F5B700",icon:"anthropic"},{id:"openai",label:"Codex",shortLabel:"Codex",accent:"#10B981",icon:"openai"}],cl={type:"spring",stiffness:400,damping:25},dl={scale:.985};function yn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function th(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?"Unknown size":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function $i(e,t){const s=(e??"").trim().toLowerCase();return s.includes("unknown api endpoint")?"Chat API unavailable in current runtime. Restart the plugin so /orgx/api/chat/* routes are active.":s.includes("network error")||s.includes("failed to fetch")?t==="load"?"Could not load thread details. Check connection and retry.":"Connection lost while sending. Draft is preserved.":s?Bt(Xt(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function nh(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function sh(e,t){return t==="all"?!0:t==="completed"?e.status==="completed":t==="in_progress"?e.status==="queued"||e.status==="running":t==="needs_attention"?e.status==="blocked"||e.status==="failed":!0}function Wr(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function gi(e){return e==="running"?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":e==="completed"?"border-teal/30 bg-teal/[0.12] text-teal-100":e==="blocked"||e==="failed"?"border-rose-400/30 bg-rose-400/[0.12] text-rose-100":e==="queued"?"border-white/[0.18] bg-white/[0.08] text-primary":"border-white/[0.12] bg-white/[0.04] text-secondary"}function Nc(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function ih(e){return e==="agent"?"assistant":e}function rh(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function ah(e,t){return t.map(s=>({id:s.id,role:ih(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function jc(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function xi(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function $r(e){const t=xi(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const i=xi(t.latestMessage),r=xi(t.latestLaunch);return{id:s,commandCenterId:typeof t.commandCenterId=="string"?t.commandCenterId:null,initiativeId:typeof t.initiativeId=="string"?t.initiativeId:null,initiativeTitle:typeof t.initiativeTitle=="string"?t.initiativeTitle:null,workstreamId:typeof t.workstreamId=="string"?t.workstreamId:null,taskId:typeof t.taskId=="string"?t.taskId:null,title:typeof t.title=="string"&&t.title.trim().length>0?t.title:"Untitled thread",summary:typeof t.summary=="string"?t.summary:null,status:t.status==="queued"||t.status==="running"||t.status==="blocked"||t.status==="completed"||t.status==="failed"||t.status==="message_only"?t.status:"message_only",assigneeId:typeof t.assigneeId=="string"?t.assigneeId:null,assigneeName:typeof t.assigneeName=="string"?t.assigneeName:null,watcherIds:Array.isArray(t.watcherIds)?t.watcherIds.filter(a=>typeof a=="string"):[],watcherNames:Array.isArray(t.watcherNames)?t.watcherNames.filter(a=>typeof a=="string"):[],messageCount:typeof t.messageCount=="number"?Math.max(0,Math.floor(t.messageCount)):0,launchCount:typeof t.launchCount=="number"?Math.max(0,Math.floor(t.launchCount)):0,lastMessageAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:null,lastLaunchAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:null,lastActivityAt:typeof t.lastActivityAt=="string"&&t.lastActivityAt.length>0?t.lastActivityAt:new Date().toISOString(),lastSnippet:typeof t.lastSnippet=="string"?t.lastSnippet:null,createdAt:typeof t.createdAt=="string"?t.createdAt:new Date().toISOString(),updatedAt:typeof t.updatedAt=="string"?t.updatedAt:new Date().toISOString(),latestMessage:i?{id:typeof i.id=="string"?i.id:`msg_${s}`,threadId:typeof i.threadId=="string"?i.threadId:s,role:i.role==="agent"||i.role==="system"?i.role:"user",body:typeof i.body=="string"?i.body:"",senderId:typeof i.senderId=="string"?i.senderId:null,senderName:typeof i.senderName=="string"?i.senderName:null,createdAt:typeof i.createdAt=="string"?i.createdAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:new Date().toISOString(),updatedAt:typeof i.updatedAt=="string"?i.updatedAt:typeof t.lastMessageAt=="string"?t.lastMessageAt:new Date().toISOString(),attachments:Array.isArray(i.attachments)?i.attachments.filter(a=>!!a&&typeof a=="object"):[],metadata:i.metadata&&typeof i.metadata=="object"?i.metadata:{}}:null,latestLaunch:r?{id:typeof r.id=="string"?r.id:`launch_${s}`,threadId:typeof r.threadId=="string"?r.threadId:s,messageId:typeof r.messageId=="string"?r.messageId:typeof t.lastMessageAt=="string"?`msg_${t.lastMessageAt}`:`msg_${s}`,assigneeId:typeof r.assigneeId=="string"?r.assigneeId:null,assigneeName:typeof r.assigneeName=="string"?r.assigneeName:null,watcherIds:Array.isArray(r.watcherIds)?r.watcherIds.filter(a=>typeof a=="string"):[],watcherNames:Array.isArray(r.watcherNames)?r.watcherNames.filter(a=>typeof a=="string"):[],executionMode:r.executionMode==="cloud"||r.executionMode==="hybrid"?r.executionMode:"local_queue",provider:typeof r.provider=="string"?r.provider:null,runId:typeof r.runId=="string"?r.runId:null,status:r.status==="queued"||r.status==="running"||r.status==="blocked"||r.status==="completed"||r.status==="failed"||r.status==="requested"?r.status:"requested",blockedReason:typeof r.blockedReason=="string"?r.blockedReason:null,warnings:Array.isArray(r.warnings)?r.warnings.filter(a=>typeof a=="string"):[],requestedAt:typeof r.requestedAt=="string"?r.requestedAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:new Date().toISOString(),updatedAt:typeof r.updatedAt=="string"?r.updatedAt:typeof t.lastLaunchAt=="string"?t.lastLaunchAt:new Date().toISOString(),metadata:r.metadata&&typeof r.metadata=="object"?r.metadata:{}}:null}}function oh(e){const t=xi(e);if(!t)return null;const s=$r({...t,latestMessage:Array.isArray(t.messages)?t.messages[t.messages.length-1]:null,latestLaunch:Array.isArray(t.launches)?t.launches[0]:null});if(!s)return null;const i=Array.isArray(t.messages)?t.messages.map(a=>xi(a)).filter(a=>!!a).map(a=>{const l=a.role==="agent"||a.role==="system"?a.role:"user";return{id:typeof a.id=="string"?a.id:`msg_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,role:l,body:typeof a.body=="string"?a.body:"",senderId:typeof a.senderId=="string"?a.senderId:null,senderName:typeof a.senderName=="string"?a.senderName:null,createdAt:typeof a.createdAt=="string"?a.createdAt:s.createdAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,attachments:Array.isArray(a.attachments)?a.attachments.filter(c=>!!c&&typeof c=="object"):[],metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[],r=Array.isArray(t.launches)?t.launches.map(a=>xi(a)).filter(a=>!!a).map(a=>{const l=a.executionMode==="cloud"||a.executionMode==="hybrid"?a.executionMode:"local_queue",c=a.status==="queued"||a.status==="running"||a.status==="blocked"||a.status==="completed"||a.status==="failed"||a.status==="requested"?a.status:"requested";return{id:typeof a.id=="string"?a.id:`launch_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,messageId:typeof a.messageId=="string"?a.messageId:"",assigneeId:typeof a.assigneeId=="string"?a.assigneeId:null,assigneeName:typeof a.assigneeName=="string"?a.assigneeName:null,watcherIds:Array.isArray(a.watcherIds)?a.watcherIds.filter(d=>typeof d=="string"):[],watcherNames:Array.isArray(a.watcherNames)?a.watcherNames.filter(d=>typeof d=="string"):[],executionMode:l,provider:typeof a.provider=="string"?a.provider:null,runId:typeof a.runId=="string"?a.runId:null,status:c,blockedReason:typeof a.blockedReason=="string"?a.blockedReason:null,warnings:Array.isArray(a.warnings)?a.warnings.filter(d=>typeof d=="string"):[],requestedAt:typeof a.requestedAt=="string"?a.requestedAt:s.updatedAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[];return{...s,messages:i.sort((a,l)=>yn(a.createdAt)-yn(l.createdAt)),launches:r.sort((a,l)=>yn(l.requestedAt)-yn(a.requestedAt))}}function lh(e,t,s){const i=yn(e.lastActivityAt);if(!i)return!1;if(t==="custom"){const a=yn(s.startIso),l=yn(s.endIso);return!(a&&i<a||l&&i>l)}const r=Qi(t,Date.now());return r?i>=r:!0}async function Pi(e,t){try{const s=await fetch(e,t),i=await s.json().catch(()=>null);return s.ok?{ok:!0,status:s.status,data:i,error:null}:{ok:!1,status:s.status,data:null,error:(i&&typeof i.error=="string"?i.error:null)??`Request failed (${s.status})`}}catch(s){return{ok:!1,status:0,data:null,error:s instanceof Error?s.message:"Network error"}}}function wa(e,t){const s=new Map;for(const i of e)s.set(i.id,i);return s.set(t.id,t),Array.from(s.values()).sort((i,r)=>yn(r.lastActivityAt??r.updatedAt)-yn(i.lastActivityAt??i.updatedAt))}function ch(e,t){const s=new Map;for(const i of e)s.set(i.id,i);for(const i of t)s.set(i.id,i);return Array.from(s.values()).sort((i,r)=>yn(r.lastActivityAt??r.updatedAt)-yn(i.lastActivityAt??i.updatedAt))}const Ac=o.createContext(null),_c=o.createContext(null);function to(){const e=o.useContext(Ac);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function no(){const e=o.useContext(_c);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function dh({children:e,sessions:t,initiatives:s,workspaceId:i,query:r,statusFilter:a,sortOrder:l,timeFilterId:c,customTimeRange:d,snapshot:u,onRequestRefresh:p}){const[x,b]=o.useState((u==null?void 0:u.threads)??[]),[h,I]=o.useState(null),[y,j]=o.useState(null),[w,N]=o.useState(!1),[f,T]=o.useState(null),[X,Z]=o.useState("resting"),[W,ke]=o.useState(""),[D,E]=o.useState(!1),[de,ie]=o.useState(!1),[we,ae]=o.useState(null),[ze,pe]=o.useState(null),[le,te]=o.useState([]),[ne,Ce]=o.useState(""),[G,R]=o.useState([]),[z,B]=o.useState(""),[K,re]=o.useState(null),[ge,Se]=o.useState(""),[oe,ye]=o.useState(!1),[me,O]=o.useState(""),[U,Y]=o.useState([]),[ce,qe]=o.useState(!1),[We,Fe]=o.useState("auto"),[L,ct]=o.useState(!1),[Me,Qe]=o.useState(!1),[St,zt]=o.useState(!1),Mt=o.useRef(null),q=o.useRef(null),_e=o.useRef(null),be=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&b($=>ch($,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{h&&b($=>$.sort((xe,ve)=>yn(ve.lastActivityAt)-yn(xe.lastActivityAt)))},[h]);const{data:Le}=Za({enabled:!0,refetchInterval:8e3}),tt=o.useMemo(()=>{var xe,ve;const $=new Map;for(const De of eh)$.set(De.id,{id:De.id,name:De.name,handle:De.handle,domain:De.domain,domainLabel:De.domainLabel,role:De.role,status:"idle",currentTask:null,isSystem:!1});if(Le!=null&&Le.agents)for(const De of Le.agents){const Nt=$.get(De.id);Nt?(Nt.status=De.status==="running"?"running":(xe=De.blockers)!=null&&xe.length?"blocked":"idle",Nt.currentTask=De.currentTask??null):$.set(De.id,{id:De.id,name:De.name,handle:De.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:De.status==="running"?"running":(ve=De.blockers)!=null&&ve.length?"blocked":"idle",currentTask:De.currentTask??null,isSystem:ll.has(De.id)})}for(const De of t){const Nt=(De.agentId??"").trim(),xt=(De.agentName??"").trim();!Nt||!xt||$.has(Nt)||$.set(Nt,{id:Nt,name:xt,handle:Nt,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:ll.has(Nt)})}return Array.from($.values()).filter(De=>!De.isSystem).sort((De,Nt)=>De.name.localeCompare(Nt.name))},[Le,t]),at=o.useMemo(()=>s.map($=>({id:$.id,name:$.name})).sort(($,xe)=>$.name.localeCompare(xe.name)),[s]),J=o.useMemo(()=>tt.find($=>$.id===ne)??null,[tt,ne]),Ue=o.useMemo(()=>{const $=new Set(G);return tt.filter(xe=>$.has(xe.id))},[tt,G]),je=o.useMemo(()=>at.find($=>$.id===z)??null,[at,z]);o.useEffect(()=>{ne&&R($=>$.filter(xe=>xe!==ne))},[ne]);const Q=o.useMemo(()=>tt.slice(0,8),[tt]),Ee=o.useMemo(()=>{const $=ge.trim().toLowerCase();return $?tt.filter(xe=>xe.name.toLowerCase().includes($)||xe.handle.toLowerCase().includes($)||xe.domain.toLowerCase().includes($)||xe.role.toLowerCase().includes($)):tt},[tt,ge]),nt=o.useMemo(()=>{const $=me.trim().toLowerCase();return $?at.filter(xe=>xe.name.toLowerCase().includes($)):at},[at,me]),Te=o.useMemo(()=>{const $=r.trim().toLowerCase(),xe=x.filter(ve=>!sh(ve,a)||!lh(ve,c,d)?!1:$.length===0?!0:nh(ve).includes($));return xe.sort((ve,De)=>{const Nt=yn(De.lastActivityAt)-yn(ve.lastActivityAt);return l==="newest"?Nt:-Nt}),xe},[d,r,l,a,x,c]),lt=o.useMemo(()=>{if(!h||Te.some(xe=>xe.id===h))return Te;const $=x.find(xe=>xe.id===h);return $?[$,...Te]:Te},[h,Te,x]),ht=o.useMemo(()=>x.find($=>$.id===h)??null,[h,x]),Rt=o.useMemo(()=>le.filter($=>$.status!=="ready").length,[le]),H=W.trim().length>0&&!D,Ae=o.useMemo(()=>Rt>0?`${Rt} attachment(s) still processing.`:"Press Enter to send.",[Rt]),Ve=o.useMemo(()=>D?"Sending…":de?"Launching…":"Send",[de,D]),Je=o.useMemo(()=>new id({api:"/orgx/api/chat/usechat"}),[]),{messages:He,setMessages:Ge,sendMessage:Ke,status:gt,error:Lt,clearError:bt}=rd({id:`orgx-chat-guidance-${i??"global"}`,transport:Je,onError:$=>{ae($i(($==null?void 0:$.message)??null,"send"))}});o.useEffect(()=>{if(!y){Ge([]);return}Ge(ah(y.id,y.messages))},[y,Ge]);const Ct=o.useMemo(()=>{const $=[...He].reverse().find(ve=>ve.role==="assistant");if(!$)return null;const xe=rh($);return xe.length>0?xe:null},[He]),Et=o.useRef(null);o.useEffect(()=>{if(gt!=="ready"&&gt!=="error"||!Ct)return;const $=[...He].reverse().find(xe=>xe.role==="assistant");!$||$.id===Et.current||(Et.current=$.id,Y(xe=>[...xe,{id:`guidance_${$.id}`,role:"agent",body:Ct,timestamp:new Date().toISOString()}]))},[gt,Ct,He]);const Vt=o.useCallback(()=>{ke(""),te([]),Qe(!1),zt(!1),ae(null),pe(null)},[]),Qt=o.useCallback($=>{Y(xe=>[...xe,{...$,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),ot=o.useCallback(()=>Y([]),[]),dt=o.useCallback(()=>qe($=>!$),[]),rn=o.useMemo(()=>Di.find($=>$.id===We)??Di[0],[We]),an=o.useCallback(()=>{Fe($=>{const xe=Di.findIndex(ve=>ve.id===$);return Di[(xe+1)%Di.length].id})},[]),ln=o.useCallback(async()=>{typeof p=="function"&&await p()},[p]),Dt=o.useCallback(async $=>{var De;N(!0),T(null);const xe=await Pi(`/orgx/api/chat/threads/${encodeURIComponent($)}`);if(!xe.ok||!((De=xe.data)!=null&&De.thread))return N(!1),T($i(xe.error,"load")),null;const ve=oh(xe.data.thread);return ve?(j(ve),N(!1),ve):(N(!1),T("Thread detail payload was invalid."),null)},[]),Ot=o.useCallback(async($,xe)=>{xe&&(_e.current=xe),I($),await Dt($),requestAnimationFrame(()=>{var ve;return(ve=q.current)==null?void 0:ve.focus()})},[Dt]),Hn=o.useCallback(()=>{var $;I(null),j(null),T(null),N(!1),($=_e.current)==null||$.focus()},[]),Gt=o.useCallback($=>{window.setTimeout(()=>{te(xe=>xe.map(ve=>ve.id===$?{...ve,status:"indexing",updatedAt:new Date().toISOString()}:ve))},80),window.setTimeout(()=>{te(xe=>xe.map(ve=>{var xt;if(ve.id!==$)return ve;const De=((xt=ve.mimeType)==null?void 0:xt.toLowerCase())==="application/x-msdownload"||ve.name.toLowerCase().endsWith(".exe"),Nt=(ve.sizeBytes??0)>25*1024*1024;return De?{...ve,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:Nt?{...ve,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...ve,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Pn=o.useCallback($=>{if(!$||$.length===0)return;const xe=new Date().toISOString(),ve=Array.from($).map(De=>({id:`draft_att_${crypto.randomUUID()}`,name:De.name,mimeType:De.type||null,sizeBytes:Number.isFinite(De.size)?De.size:null,status:"preparing",error:null,masked:!1,createdAt:xe,updatedAt:xe}));te(De=>De.concat(ve)),ve.forEach(De=>Gt(De.id)),vs("chat_attachment_state_changed",{count:ve.length,state:"preparing"})},[Gt]),fs=o.useCallback($=>{te(xe=>xe.map(ve=>ve.id===$?{...ve,status:"preparing",error:null,updatedAt:new Date().toISOString()}:ve)),Gt($),vs("chat_attachment_state_changed",{state:"retry"})},[Gt]),Qs=o.useCallback($=>{Ce(xe=>xe===$?"":$),R(xe=>xe.filter(ve=>ve!==$)),re(null),Se("")},[]),Ss=o.useCallback($=>{R(xe=>xe.includes($)?xe.filter(ve=>ve!==$):xe.concat($))},[]),Kn=o.useCallback(()=>{ye(!1),O(""),re($=>$==="assignee"?null:"assignee"),Se("")},[]),fn=o.useCallback(()=>{ye(!1),O(""),re($=>$==="watcher"?null:"watcher"),Se("")},[]),on=o.useCallback(()=>{re(null),Se(""),ye($=>!$),O("")},[]),mn=o.useCallback(async($,xe)=>{var xt;ct(!0);const ve=at.find(pt=>pt.id===xe)??null,De=await Pi("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:$,project_id:i??void 0,initiativeId:(ve==null?void 0:ve.id)??null,initiativeTitle:(ve==null?void 0:ve.name)??null,relinked:!0})});if(ct(!1),!De.ok||!((xt=De.data)!=null&&xt.thread)){T(De.error??"Scope link failed.");return}const Nt=$r(De.data.thread);Nt&&b(pt=>wa(pt,Nt)),await Dt($),await ln(),vs("chat_thread_linked_initiative",{threadId:$,initiativeId:(ve==null?void 0:ve.id)??null})},[at,Dt,ln,i]),bn=o.useCallback(async $=>{bt(),await Ke({text:$.prompt},{body:{threadId:$.thread.id,project_id:i??void 0,initiativeId:$.thread.initiativeId??(je==null?void 0:je.id)??void 0,initiativeTitle:$.thread.initiativeTitle??(je==null?void 0:je.name)??void 0,assigneeId:(J==null?void 0:J.id)??$.thread.assigneeId??void 0,assigneeName:(J==null?void 0:J.name)??$.thread.assigneeName??void 0,watcherIds:Ue.map(xe=>xe.id),watcherNames:Ue.map(xe=>xe.name)}}),await ln(),await Dt($.thread.id)},[bt,Dt,ln,J==null?void 0:J.id,J==null?void 0:J.name,je==null?void 0:je.id,je==null?void 0:je.name,Ue,Ke,i]),Zn=o.useCallback(async()=>{var Nt,xt;const $=W.trim();if(!$)return ae("Write a message before sending."),{thread:null,messageId:null};ae(null),pe(null),E(!0);const xe=await Pi("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:h??void 0,project_id:i??void 0,initiativeId:(je==null?void 0:je.id)??(y==null?void 0:y.initiativeId)??void 0,initiativeTitle:(je==null?void 0:je.name)??(y==null?void 0:y.initiativeTitle)??void 0,assigneeId:(J==null?void 0:J.id)??(y==null?void 0:y.assigneeId)??void 0,assigneeName:(J==null?void 0:J.name)??(y==null?void 0:y.assigneeName)??void 0,watcherIds:Ue.map(pt=>pt.id),watcherNames:Ue.map(pt=>pt.name),body:$,attachments:le.map(pt=>({id:pt.id,name:pt.name,mimeType:pt.mimeType,sizeBytes:pt.sizeBytes,status:pt.status,error:pt.error,masked:pt.masked}))})});if(E(!1),!xe.ok||!((Nt=xe.data)!=null&&Nt.thread))return ae($i(xe.error,"send")),vs("chat_message_send_failed",{reason:xe.error??"unknown"}),{thread:null,messageId:null};const ve=$r(xe.data.thread);if(!ve)return ae("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};b(pt=>wa(pt,ve)),Qt({role:"user",body:$}),We!=="auto"&&J&&Qt({role:"system",body:`Routing to ${J.name} via ${rn.label}`}),vs("chat_message_sent",{threadId:ve.id,watcherCount:ve.watcherIds.length}),await ln();const De=xe.data.message&&typeof xe.data.message.id=="string"?xe.data.message.id:((xt=ve.latestMessage)==null?void 0:xt.id)??null;return I(ve.id),await Dt(ve.id),bn({thread:ve,prompt:$}).catch(pt=>{Qt({role:"error",body:$i(pt instanceof Error?pt.message:String(pt??""),"send")})}),Vt(),Z("reviewing"),{thread:ve,messageId:De}},[y==null?void 0:y.assigneeId,y==null?void 0:y.assigneeName,y==null?void 0:y.initiativeId,y==null?void 0:y.initiativeTitle,h,W,le,Dt,ln,Vt,bn,J==null?void 0:J.id,J==null?void 0:J.name,je==null?void 0:je.id,je==null?void 0:je.name,We,rn,Ue,i]),Cs=o.useCallback(async($,xe)=>{var cn,Yt,ss,$t,Ms,Es,jt;if(!xe){Qt({role:"error",body:"Send a message first to launch."});return}if(!J){Qt({role:"error",body:"Pick an agent with @ before launching."});return}if(Rt>0&&!St){Qe(!0),Qt({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}ie(!0),ae(null),pe(null);const ve=await Pi("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:J.id,message:W.trim().length>0?W.trim():$.lastSnippet??$.title,initiativeId:$.initiativeId??(je==null?void 0:je.id)??void 0,initiativeTitle:$.initiativeTitle??(je==null?void 0:je.name)??void 0,workstreamId:$.workstreamId??void 0,taskId:$.taskId??void 0,provider:We!=="auto"?We:void 0})}),De=((cn=ve.data)==null?void 0:cn.sessionId)??((Yt=ve.data)==null?void 0:Yt.runId)??null,Nt=ve.ok&&De?"running":ve.ok?"queued":"blocked",xt=ve.ok?null:ve.error??"Launch request failed before queueing.",pt=await Pi("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:$.id,messageId:xe,assigneeId:J.id,assigneeName:J.name,watcherIds:Ue.map(vn=>vn.id),watcherNames:Ue.map(vn=>vn.name),executionMode:"local_queue",provider:((ss=ve.data)==null?void 0:ss.provider)??(We!=="auto"?We:"openclaw"),runId:De??void 0,status:Nt,blockedReason:xt??void 0,warnings:Rt>0?[`${Rt} attachment(s) were not ready at launch.`]:[]})});if(ie(!1),zt(!1),Qe(!1),!pt.ok||!(($t=pt.data)!=null&&$t.thread)){ae(pt.error?$i(pt.error,"launch"):xt??"Launch state could not be persisted. Message remained saved."),vs("chat_launch_failed",{threadId:$.id,reason:pt.error??xt??"unknown"});return}const In=$r(pt.data.thread);if(In&&b(vn=>wa(vn,In)),await Dt($.id),await ln(),!ve.ok){ae(`Launch blocked: ${xt??"Set assignee and retry."}`),vs("chat_launch_blocked",{threadId:$.id,reason:xt??"unknown"});return}const ts=((Ms=ve.data)==null?void 0:Ms.provider)==="anthropic"?"Claude Code":((Es=ve.data)==null?void 0:Es.provider)==="openai"?"Codex":rn.shortLabel,ns=(jt=ve.data)!=null&&jt.model?` (${ve.data.model})`:"";pe(De?`Launch started via ${ts}${ns}. Thread timeline now tracks execution state.`:`Launch queued locally via ${ts}. Run starts when a worker is available.`),vs(De?"chat_launch_started":"chat_launch_queued",{threadId:$.id,runId:De,assigneeId:J.id})},[W,St,Dt,ln,J,je==null?void 0:je.id,je==null?void 0:je.name,We,rn,Ue,Rt]),es=o.useCallback(async()=>{var xe;const $=await Zn();(xe=$.thread)!=null&&xe.id&&await Ot($.thread.id)},[Ot,Zn]),Ts=o.useCallback(async()=>{const $=await Zn();$.thread&&(await Cs($.thread,$.messageId),await Ot($.thread.id))},[Cs,Ot,Zn]),hs=o.useCallback(async()=>{if(H){if(J){await Ts();return}await es()}},[H,Ts,es,J]),hn=o.useMemo(()=>({threads:x,activeThreadId:h,activeThread:y,activeThreadSummary:ht,displayedThreads:lt,composerMode:X,draft:W,draftAttachments:le,sending:D,launching:de,composerError:we,composerNotice:ze,selectedAssigneeId:ne,selectedAssignee:J,selectedWatcherIds:G,selectedWatchers:Ue,selectedInitiativeId:z,selectedInitiative:je,agentOptions:tt,quickAssigneeOptions:Q,initiativeOptions:at,agentPickerMode:K,agentPickerQuery:ge,filteredAgentOptions:Ee,scopePickerOpen:oe,scopePickerQuery:me,filteredInitiativeOptions:nt,panelLoading:w,panelError:f,scopeSaving:L,launchWarningOpen:Me,launchWarningAccepted:St,unresolvedAttachmentCount:Rt,canSend:H,composerGuidance:Ae,primaryActionLabel:Ve,guidanceStatus:gt,guidancePreview:Ct,guidanceError:Lt??null,inlineMessages:U,threadSidebarOpen:ce,workspaceId:i,selectedProvider:We,selectedProviderDef:rn}),[x,h,y,ht,lt,X,W,le,D,de,we,ze,ne,J,G,Ue,z,je,tt,Q,at,K,ge,Ee,oe,me,nt,w,f,L,Me,St,Rt,H,Ae,Ve,gt,Ct,Lt,U,ce,i,We,rn]),Ys=o.useMemo(()=>({setDraft:ke,setComposerMode:Z,setDraftAttachments:te,selectAssignee:Qs,toggleWatcher:Ss,setSelectedInitiativeId:B,toggleAssigneePicker:Kn,toggleWatcherPicker:fn,toggleScopePicker:on,setAgentPickerQuery:Se,setScopePickerQuery:O,setAgentPickerMode:re,setScopePickerOpen:ye,handlePrimaryAction:hs,handleFilesAdded:Pn,handleRetryAttachment:fs,openThreadPanel:Ot,closeThreadPanel:Hn,loadThreadDetail:Dt,applyScopeLink:mn,resetComposer:Vt,setComposerError:ae,setComposerNotice:pe,setLaunchWarningAccepted:zt,pushInlineMessage:Qt,clearInlineMessages:ot,toggleThreadSidebar:dt,setSelectedProvider:Fe,cycleProvider:an,fileInputRef:Mt,panelHeadingRef:q,composerShellRef:be}),[Qs,Ss,Kn,fn,on,hs,Pn,fs,Ot,Hn,Dt,mn,Vt,Qt,ot,dt,an]);return n.jsx(Ac.Provider,{value:hn,children:n.jsx(_c.Provider,{value:Ys,children:e})})}const uh={type:"spring",stiffness:500,damping:35,mass:.5};function mh({messages:e,isStreaming:t,collapsed:s,onClick:i}){var c;const r=ps(),a=o.useRef(null);o.useEffect(()=>{const d=a.current;d&&d.scrollTo({top:d.scrollHeight,behavior:"smooth"})},[e.length,(c=e[e.length-1])==null?void 0:c.body]);const l=s?e.slice(-2):e;return l.length===0?null:n.jsx(he.div,{initial:r?!1:{opacity:0,height:0},animate:r?{}:{opacity:1,height:"auto"},exit:r?{}:{opacity:0,height:0},transition:r?void 0:{duration:.25,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{ref:a,onClick:i,role:i?"button":void 0,tabIndex:i?0:void 0,className:ue("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",i&&"cursor-pointer"),children:n.jsx(It,{initial:!1,children:l.map(d=>n.jsx(he.div,{initial:r?!1:{opacity:0,y:8,scale:.97},animate:r?{}:{opacity:1,y:0,scale:1},transition:r?void 0:uh,className:ue("flex",d.role==="user"?"justify-end":"justify-start",d.role==="system"&&"justify-center"),children:d.role==="system"?n.jsx("p",{className:"text-micro italic text-muted",children:d.body}):n.jsxs("div",{className:ue("max-w-[85%] rounded-2xl px-3 py-2",d.role==="user"&&"bg-lime/[0.1]",d.role==="agent"&&"bg-white/[0.05]",d.role==="error"&&"bg-rose-400/[0.1]"),children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:ue("text-micro font-medium",d.role==="user"&&"text-[#E1FFB2]/80",d.role==="agent"&&"text-secondary",d.role==="error"&&"text-rose-200"),children:d.role==="user"?"You":d.role==="error"?"Error":"Agent"}),n.jsx("time",{className:"text-[10px] text-muted/60",dateTime:d.timestamp,children:Pt(d.timestamp)})]}),n.jsxs("p",{className:ue("mt-0.5 whitespace-pre-wrap text-caption leading-relaxed",d.role==="user"&&"text-primary",d.role==="agent"&&"text-primary",d.role==="error"&&"text-rose-100"),children:[d.body,t&&d===l[l.length-1]&&d.role==="agent"&&n.jsx("span",{className:"ml-0.5 inline-block h-[14px] w-[2px] translate-y-[2px] rounded-full bg-white/50",style:{animation:"pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite"}})]})]})},d.id))})})})}function ul({open:e,onClose:t}){const s=ps(),{displayedThreads:i,activeThreadId:r,activeThread:a,activeThreadSummary:l,panelLoading:c,panelError:d,scopeSaving:u,initiativeOptions:p}=to(),{openThreadPanel:x,closeThreadPanel:b,loadThreadDetail:h,applyScopeLink:I,panelHeadingRef:y}=no(),j=(a==null?void 0:a.id)??(l==null?void 0:l.id)??null,w=o.useCallback((f,T)=>{x(f,T)},[x]),N=o.useCallback(()=>{b(),t()},[b,t]);return n.jsx(It,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(he.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:N,className:"fixed inset-0 z-[24] bg-black/30"}),n.jsxs(he.section,{initial:s?!1:{y:"100%"},animate:s?{}:{y:0},exit:s?{}:{y:"100%"},transition:s?void 0:{duration:sn.durationEntrance/1e3,ease:sn.easingEntrance},"aria-label":"Thread history","data-testid":"thread-drawer",className:"fixed bottom-0 left-0 right-0 z-25 flex max-h-[min(60vh,480px)] flex-col rounded-t-[22px] border-t border-white/[0.14] bg-[#0A0E16]/95 shadow-[0_-12px_40px_rgba(0,0,0,0.4)] backdrop-blur-xl",style:{paddingBottom:"max(12px, env(safe-area-inset-bottom))"},children:[n.jsx("div",{className:"flex justify-center py-2",children:n.jsx("div",{className:"h-1 w-10 rounded-full bg-white/[0.16]"})}),n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Threads"}),n.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:i.length})]}),n.jsx("button",{type:"button",onClick:N,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread drawer",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsxs("div",{className:ue("grid min-h-0 flex-1 overflow-hidden",r&&"lg:grid-cols-[minmax(260px,0.8fr)_minmax(0,1.2fr)]"),children:[n.jsx("div",{className:"min-h-0 overflow-y-auto px-3 pb-3",children:i.length===0?n.jsx(Qr,{icon:"inbox",headline:"No threads yet",description:"Send a message to start a conversation thread.",className:"py-6"}):n.jsx("div",{className:"space-y-1.5",children:i.map(f=>n.jsxs("button",{type:"button",onClick:T=>w(f.id,T.currentTarget),className:ue("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",r===f.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:f.lastSnippet?`"${f.lastSnippet.length>40?f.lastSnippet.slice(0,40)+"...":f.lastSnippet}"`:f.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:f.lastActivityAt,children:Pt(f.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[f.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",f.assigneeName]}),n.jsx("span",{children:f.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:ue("rounded-full border px-1.5 py-0 text-[10px] font-semibold",gi(f.status)),children:Wr(f.status)})]})]},f.id))})}),n.jsx(It,{initial:!1,children:r&&n.jsxs(he.div,{initial:s?!1:{opacity:0,x:12},animate:s?{}:{opacity:1,x:0},exit:s?{}:{opacity:0,x:12},transition:s?void 0:{duration:sn.durationStandard/1e3,ease:sn.easingStandard},className:"hidden min-h-0 flex-col overflow-hidden border-l border-white/[0.08] lg:flex",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2",children:[n.jsx("h4",{ref:y,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(a==null?void 0:a.title)??(l==null?void 0:l.title)??"Thread"}),n.jsx("span",{className:ue("rounded-full border px-2 py-0.5 text-micro font-semibold",gi((l==null?void 0:l.status)??"message_only")),children:Wr((l==null?void 0:l.status)??"message_only")})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:c?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):d?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:d}),j&&n.jsx("button",{type:"button",onClick:()=>void h(j),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):a&&a.messages.length>0?n.jsx("div",{className:"space-y-2",children:a.messages.map(f=>n.jsx("article",{className:ue("flex",f.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:ue("max-w-[90%] rounded-xl border px-2.5 py-1.5",f.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":f.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:f.senderName??Nc(f.role)}),n.jsx("time",{dateTime:f.createdAt,children:Pt(f.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:f.body})]})},f.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),a&&a.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[a.launches.length," launch",a.launches.length===1?"":"es"]}),a.launches.slice(0,2).map(f=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:ue("rounded-full border px-1.5 py-0 text-[10px] font-semibold",gi(jc(f.status))),children:f.status}),n.jsx("span",{children:f.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:f.requestedAt,children:Pt(f.requestedAt)})]},f.id))]})]})})]})]})]})})}function ml(){const e=ps(),{displayedThreads:t,activeThreadId:s,activeThread:i,activeThreadSummary:r,panelLoading:a,panelError:l,scopeSaving:c,initiativeOptions:d,threadSidebarOpen:u}=to(),{openThreadPanel:p,closeThreadPanel:x,loadThreadDetail:b,applyScopeLink:h,setComposerMode:I,toggleThreadSidebar:y,panelHeadingRef:j}=no(),w=(i==null?void 0:i.id)??(r==null?void 0:r.id)??null,N=o.useCallback(()=>{y()},[y]);return u?n.jsx(It,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(he.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:N,className:"fixed inset-0 z-[24] bg-black/30"},"sidebar-backdrop"),n.jsxs(he.section,{initial:e?!1:{x:"-100%"},animate:e?{}:{x:0},exit:e?{}:{x:"-100%"},transition:e?void 0:{duration:sn.durationEntrance/1e3,ease:sn.easingEntrance},"aria-label":"Thread sidebar","data-testid":"thread-sidebar",className:"fixed inset-y-0 left-0 z-25 flex w-[380px] max-w-[85vw] flex-col border-r border-white/[0.14] bg-[#0A0E16]/95 shadow-[12px_0_40px_rgba(0,0,0,0.4)] backdrop-blur-xl",children:[n.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-white/[0.08] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Threads"}),n.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:t.length})]}),n.jsx("button",{type:"button",onClick:N,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread sidebar",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-3",children:t.length===0?n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-caption text-secondary",children:[n.jsx("p",{className:"text-primary",children:"No threads yet."}),n.jsx("p",{className:"mt-0.5",children:"Send a message to start one."}),n.jsx(he.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:dl,transition:cl,onClick:()=>{N(),I("focused"),requestAnimationFrame(()=>{const f=document.getElementById("chat-dock-input");f instanceof HTMLTextAreaElement&&f.focus()})},className:"mt-2 inline-flex min-h-[34px] items-center rounded-full border border-lime/30 bg-lime/[0.12] px-2.5 text-micro font-semibold text-[#E1FFB2] hover:bg-lime/[0.18]",children:"Start thread"})]}):n.jsx("div",{className:"space-y-1.5",children:t.map((f,T)=>n.jsxs(he.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:cl,delay:e?0:Math.min(T*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:dl,onClick:X=>void p(f.id,X.currentTarget),className:ue("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===f.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:f.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:f.lastActivityAt,children:Pt(f.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:f.lastSnippet??f.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[f.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(en,{name:f.assigneeName,hint:f.assigneeName,size:"xs"}),n.jsx("span",{children:f.assigneeName})]}),n.jsx("span",{children:f.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:ue("rounded-full border px-1.5 py-0 text-[10px] font-semibold",gi(f.status)),children:Wr(f.status)})]})]},f.id))})}),n.jsx(It,{initial:!1,children:s&&n.jsxs(he.div,{initial:e?!1:{opacity:0,y:12},animate:e?{}:{opacity:1,y:0},exit:e?{}:{opacity:0,y:12},transition:e?void 0:{duration:sn.durationStandard/1e3,ease:sn.easingStandard},className:"flex min-h-0 max-h-[50%] flex-col border-t border-white/[0.08]",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2",children:[n.jsx("h4",{ref:j,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(i==null?void 0:i.title)??(r==null?void 0:r.title)??"Thread"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:ue("rounded-full border px-2 py-0.5 text-micro font-semibold",gi((r==null?void 0:r.status)??"message_only")),children:Wr((r==null?void 0:r.status)??"message_only")}),n.jsx("button",{type:"button",onClick:x,className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-micro text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread detail",children:"×"})]})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:a?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):l?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:l}),w&&n.jsx("button",{type:"button",onClick:()=>void b(w),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):i&&i.messages.length>0?n.jsx("div",{className:"space-y-2",children:i.messages.map(f=>n.jsx("article",{className:ue("flex",f.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:ue("max-w-[90%] rounded-xl border px-2.5 py-1.5",f.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":f.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:f.senderName??Nc(f.role)}),n.jsx("time",{dateTime:f.createdAt,children:Pt(f.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:f.body})]})},f.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),i&&i.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[i.launches.length," launch",i.launches.length===1?"":"es"]}),i.launches.slice(0,2).map(f=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:ue("rounded-full border px-1.5 py-0 text-[10px] font-semibold",gi(jc(f.status))),children:f.status}),n.jsx("span",{children:f.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:f.requestedAt,children:Pt(f.requestedAt)})]},f.id))]})]})})]},"sidebar-panel")]})}):null}const ph={type:"spring",stiffness:500,damping:30,mass:.5};function fh({open:e,agents:t,query:s,activeIndex:i,onSelect:r}){const a=ps(),l=o.useRef(null);o.useEffect(()=>{if(!e||!l.current)return;const u=l.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[i,e]);const c=s.length>0?t.filter(u=>{const p=s.toLowerCase();return u.name.toLowerCase().includes(p)||u.handle.toLowerCase().includes(p)||u.domain.toLowerCase().includes(p)||u.role.toLowerCase().includes(p)}):t;if(!e||c.length===0)return null;const d=c.slice(0,6);return n.jsx(It,{children:n.jsx(he.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:ph,className:ue("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Agent suggestions",children:n.jsx("div",{ref:l,className:"space-y-px",children:d.map((u,p)=>{const x=p===i;return n.jsxs("button",{type:"button",role:"option","aria-selected":x,"data-active":x,onClick:()=>r(u),onMouseDown:b=>b.preventDefault(),className:ue("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",x?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(en,{name:u.name,hint:u.name,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"truncate text-caption font-medium",children:u.name}),u.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime","aria-label":"Running"})]}),n.jsx("span",{className:"text-micro text-muted",children:u.domainLabel})]})]},u.id)})})})})}const hh={type:"spring",stiffness:500,damping:30,mass:.5};function gh({open:e,initiatives:t,query:s,activeIndex:i,onSelect:r}){const a=ps(),l=o.useRef(null);o.useEffect(()=>{if(!e||!l.current)return;const u=l.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[i,e]);const c=s.length>0?t.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())):t;if(!e)return null;const d=c.slice(0,6);return n.jsx(It,{children:n.jsx(he.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:hh,className:ue("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Initiative scope suggestions",children:n.jsxs("div",{ref:l,className:"space-y-px",children:[n.jsx("button",{type:"button",role:"option","aria-selected":i===0,"data-active":i===0,onClick:()=>r(null),onMouseDown:u=>u.preventDefault(),className:ue("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",i===0?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:"Unscoped"}),d.map((u,p)=>{const x=p+1===i;return n.jsx("button",{type:"button",role:"option","aria-selected":x,"data-active":x,onClick:()=>r(u),onMouseDown:b=>b.preventDefault(),className:ue("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",x?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:n.jsx("span",{className:"truncate",children:u.name})},u.id)})]})})})}function xh({open:e,mode:t,agents:s,quickAgents:i,query:r,selectedAssigneeId:a,selectedWatcherIds:l,onQueryChange:c,onSelectAssignee:d,onToggleWatcher:u,onClose:p,onSwitchMode:x,anchorRef:b}){const h=ps();return n.jsx(It,{children:e&&n.jsxs(he.div,{initial:h?!1:{opacity:0,scale:.95,y:8},animate:h?{}:{opacity:1,scale:1,y:0},exit:h?{}:{opacity:0,scale:.95,y:8},transition:h?void 0:sn.easingBounce,className:"absolute bottom-[calc(100%+8px)] left-0 z-30 w-[320px] rounded-xl border border-white/[0.14] bg-[#0A0E16]/98 p-2.5 shadow-[0_20px_44px_rgba(0,0,0,0.45)] backdrop-blur-xl",children:[n.jsx("div",{className:"absolute -bottom-[6px] left-4 h-0 w-0 border-l-[6px] border-r-[6px] border-t-[6px] border-l-transparent border-r-transparent border-t-white/[0.14]","aria-hidden":!0}),n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsxs("div",{className:"flex gap-1",children:[n.jsx("button",{type:"button",onClick:()=>x("assignee"),className:ue("rounded-full px-2 py-0.5 text-micro",t==="assignee"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Assignee"}),n.jsx("button",{type:"button",onClick:()=>x("watcher"),className:ue("rounded-full px-2 py-0.5 text-micro",t==="watcher"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Watchers"})]}),n.jsx("button",{type:"button",onClick:p,className:"h-7 rounded-full border border-white/[0.12] bg-white/[0.03] px-2 text-micro text-secondary hover:bg-white/[0.08] hover:text-primary",children:"Close"})]}),i.length>0&&t==="assignee"&&n.jsx("div",{className:"mb-2 flex items-center gap-1.5 overflow-x-auto border-b border-white/[0.06] pb-2 scrollbar-none",children:i.map(I=>{const y=a===I.id;return n.jsx("button",{type:"button",onClick:()=>d(I.id),title:I.name,className:ue("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",y?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":y,"aria-label":`Select ${I.name} as assignee`,children:n.jsx(en,{name:I.name,hint:I.name,size:"xs"})},I.id)})}),n.jsx("input",{value:r,onChange:I=>c(I.target.value),placeholder:"Search agents...",className:"mb-2 h-9 w-full rounded-lg border border-white/[0.12] bg-black/35 px-2.5 text-caption text-primary outline-none focus:border-lime/35",autoFocus:!0}),n.jsx("div",{className:"max-h-[240px] space-y-1 overflow-y-auto",children:s.map(I=>{const y=a===I.id,j=l.includes(I.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(I.id);return}y||u(I.id)},className:ue("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",y?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":j?"border-teal/30 bg-teal/[0.12] text-teal-100":"border-white/[0.1] bg-white/[0.02] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsxs("span",{className:"inline-flex items-center gap-2",children:[n.jsx(en,{name:I.name,hint:I.name,size:"xs"}),n.jsx("span",{children:I.name})]}),n.jsx("span",{className:"text-micro",children:y?"Assignee":j?"Watcher":"Select"})]},I.id)})})]})})}const pl=24,fl=200;function hl(e){return e?e.startsWith("application/pdf")?"#EF4444":e.startsWith("image/")?"#A78BFA":e.includes("spreadsheet")||e.includes("csv")?"#22C55E":e.includes("presentation")?"#F97316":"#8F9AB7":"#8F9AB7"}function yh(e,t){var i;if(e!=null&&e.startsWith("application/pdf"))return"PDF";if(e!=null&&e.startsWith("image/"))return"Image";if(e!=null&&e.includes("spreadsheet")||e!=null&&e.includes("csv"))return"Sheet";if(e!=null&&e.includes("presentation"))return"Slides";const s=(i=t.split(".").pop())==null?void 0:i.toUpperCase();return s&&s.length<=5?s:"File"}function gl({icon:e,className:t}){return e==="anthropic"?n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",className:t,children:n.jsx("path",{d:"M16.5 2.3L12 21.7l-1.7-6.5L3.8 13l6.5-1.7L12 4.8l1.7 6.5 6.5 1.7-6.5 1.7L12 21.7"})}):e==="openai"?n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M12 2a7 7 0 0 1 7 7c0 2.38-1.19 4.47-3 5.74V17a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2.26C6.19 13.47 5 11.38 5 9a7 7 0 0 1 7-7z"}),n.jsx("line",{x1:"10",y1:"21",x2:"14",y2:"21"})]}):n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M12 2l2.4 7.2L22 12l-7.6 2.8L12 22l-2.4-7.2L2 12l7.6-2.8z"})})}const za="orgx-chat-dock-collapsed";function bh(){try{return localStorage.getItem(za)==="1"}catch{return!1}}function vh(){const e=to(),t=no(),s=ps(),i=o.useRef(null),r=o.useRef(null),[a,l]=o.useState(bh),c=o.useCallback(()=>{l(Q=>{const Ee=!Q;try{localStorage.setItem(za,Ee?"1":"0")}catch{}return Ee})},[]),[d,u]=o.useState(!1),[p,x]=o.useState(!1),b=o.useRef(null),[h,I]=o.useState(!1),[y,j]=o.useState(""),[w,N]=o.useState(0),[f,T]=o.useState(-1),[X,Z]=o.useState(!1),[W,ke]=o.useState(""),[D,E]=o.useState(0),[de,ie]=o.useState(-1),{composerMode:we,draft:ae,draftAttachments:ze,sending:pe,launching:le,selectedAssigneeId:te,selectedAssignee:ne,selectedWatcherIds:Ce,selectedInitiative:G,agentOptions:R,quickAssigneeOptions:z,agentPickerMode:B,agentPickerQuery:K,filteredAgentOptions:re,initiativeOptions:ge,canSend:Se,activeThreadId:oe,guidanceStatus:ye,inlineMessages:me,displayedThreads:O,launchWarningOpen:U,launchWarningAccepted:Y,selectedProvider:ce,selectedProviderDef:qe}=e,We=ae.trim(),Fe=me.length>0;We.length>0;const L=o.useCallback(()=>{const Q=i.current;if(!Q)return;Q.style.height="0";const Ee=Math.min(Math.max(Q.scrollHeight,pl),fl);Q.style.height=`${Ee}px`},[]);o.useLayoutEffect(()=>{L()},[ae,L]);const ct=o.useMemo(()=>{if(!h)return R;const Q=y.toLowerCase();return Q?R.filter(Ee=>Ee.name.toLowerCase().includes(Q)||Ee.handle.toLowerCase().includes(Q)||Ee.domain.toLowerCase().includes(Q)||Ee.role.toLowerCase().includes(Q)):R},[R,h,y]),Me=o.useMemo(()=>{if(!X)return ge;const Q=W.toLowerCase();return Q?ge.filter(Ee=>Ee.name.toLowerCase().includes(Q)):ge},[ge,X,W]);o.useEffect(()=>{if(b.current&&clearTimeout(b.current),me.length<=2){x(!1);return}return x(!1),b.current=window.setTimeout(()=>{x(!0)},5e3),()=>{b.current&&clearTimeout(b.current)}},[me.length]),o.useEffect(()=>{const Q=Ee=>{if((Ee.metaKey||Ee.ctrlKey)&&Ee.key==="k"){if(Ee.preventDefault(),a){l(!1);try{localStorage.setItem(za,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var nt;return(nt=i.current)==null?void 0:nt.focus()})}};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[t,a]);const Qe=o.useCallback(()=>{we==="resting"&&t.setComposerMode("focused")},[we,t]),St=o.useCallback(()=>{window.setTimeout(()=>{We.length===0&&!Fe&&!h&&!X&&ze.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),I(!1),Z(!1))},100)},[We,Fe,h,X,ze.length,t]),zt=o.useCallback(Q=>{const Ee=Q.target.value,nt=Q.target.selectionStart??Ee.length;t.setDraft(Ee),(we==="resting"||we==="focused")&&t.setComposerMode("composing");const Te=Ee.slice(0,nt),lt=Te.match(/@(\w*)$/);if(lt){I(!0),j(lt[1]),N(0),T(nt-lt[0].length),Z(!1);return}const ht=Te.match(/#(\w*)$/);if(ht){Z(!0),ke(ht[1]),E(0),ie(nt-ht[0].length),I(!1);return}h&&I(!1),X&&Z(!1)},[we,t,h,X]),Mt=o.useCallback(Q=>{var lt;const Ee=ae.slice(0,f),nt=ae.slice(((lt=i.current)==null?void 0:lt.selectionStart)??ae.length),Te=`${Ee}@${Q.name} ${nt}`;t.setDraft(Te),t.selectAssignee(Q.id),I(!1),j(""),requestAnimationFrame(()=>{if(i.current){const ht=Ee.length+Q.name.length+2;i.current.setSelectionRange(ht,ht),i.current.focus()}})},[ae,f,t]),q=o.useCallback(Q=>{var Te;const Ee=ae.slice(0,de),nt=ae.slice(((Te=i.current)==null?void 0:Te.selectionStart)??ae.length);if(Q){const lt=`${Ee}#${Q.name} ${nt}`;t.setDraft(lt),t.setSelectedInitiativeId(Q.id),requestAnimationFrame(()=>{if(i.current){const ht=Ee.length+Q.name.length+2;i.current.setSelectionRange(ht,ht),i.current.focus()}})}else{const lt=`${Ee}${nt}`;t.setDraft(lt),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{i.current&&(i.current.setSelectionRange(Ee.length,Ee.length),i.current.focus())})}Z(!1),ke("")},[ae,de,t]),_e=o.useCallback(Q=>{if(h&&ct.length>0){if(Q.key==="ArrowDown"){Q.preventDefault(),N(Ee=>(Ee+1)%ct.length);return}if(Q.key==="ArrowUp"){Q.preventDefault(),N(Ee=>(Ee-1+ct.length)%ct.length);return}if(Q.key==="Enter"||Q.key==="Tab"){Q.preventDefault(),Mt(ct[w]);return}if(Q.key==="Escape"){Q.preventDefault(),I(!1);return}}if(X){const Ee=Me.length+1;if(Q.key==="ArrowDown"){Q.preventDefault(),E(nt=>(nt+1)%Ee);return}if(Q.key==="ArrowUp"){Q.preventDefault(),E(nt=>(nt-1+Ee)%Ee);return}if(Q.key==="Enter"||Q.key==="Tab"){Q.preventDefault(),q(D===0?null:Me[D-1]);return}if(Q.key==="Escape"){Q.preventDefault(),Z(!1);return}}if(Q.key==="Enter"&&!Q.shiftKey){Q.preventDefault(),t.handlePrimaryAction();return}Q.key==="Escape"&&(Q.preventDefault(),B?t.setAgentPickerMode(null):Fe?t.clearInlineMessages():(t.setComposerMode("resting"),Q.target.blur()))},[t,B,Fe,h,ct,w,Mt,X,Me,D,q]),be=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),Le=pe||le?n.jsx("svg",{className:"h-4 w-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"52",strokeDashoffset:"16",strokeLinecap:"round"})}):n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),n.jsx("polyline",{points:"5 12 12 5 19 12"})]}),tt=(we==="reviewing"||Fe)&&me.length>0,at=ye==="submitted"||ye==="streaming",J=o.useRef(me.length),[Ue,je]=o.useState(0);return o.useEffect(()=>{if(!a){J.current=me.length,je(0);return}const Q=me.length-J.current;Q>0&&je(Q)},[a,me.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(ul,{open:d,onClose:()=>u(!1)}),n.jsx(ml,{}),n.jsx("div",{className:"sticky bottom-0 z-20 flex justify-end px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:n.jsxs(he.button,{type:"button",onClick:()=>{c(),requestAnimationFrame(()=>{var Q;return(Q=i.current)==null?void 0:Q.focus()})},initial:s?!1:{scale:.8,opacity:0},animate:s?{}:{scale:1,opacity:1},whileHover:s?void 0:{scale:1.08},whileTap:s?void 0:{scale:.92},transition:{type:"spring",stiffness:500,damping:28},className:ue("relative inline-flex h-12 w-12 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16]/90 text-primary backdrop-blur-xl","shadow-[0_8px_32px_rgba(0,0,0,0.4),inset_0_1px_0_rgba(255,255,255,0.05)]","hover:border-white/[0.22] hover:bg-[#0A0E16]"),"aria-label":"Open chat",children:[n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx(It,{children:Ue>0&&n.jsx(he.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:ue("absolute -right-1 -top-1 flex h-5 min-w-[20px] items-center justify-center rounded-full","bg-lime px-1 text-[10px] font-bold text-[#0A0E16]"),children:Ue>9?"9+":Ue},"unread")}),oe&&Ue===0&&n.jsx("span",{className:"absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full border-2 border-[#0A0E16] bg-lime"})]})})]}):n.jsxs(n.Fragment,{children:[n.jsx(ul,{open:d,onClose:()=>u(!1)}),n.jsx(ml,{}),n.jsxs("div",{ref:Q=>{t.composerShellRef.current=Q},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(It,{children:U&&n.jsxs(he.div,{initial:s?!1:{opacity:0,y:4},animate:s?{}:{opacity:1,y:0},exit:s?{}:{opacity:0},transition:{duration:.15},className:"mb-2 rounded-lg border border-amber-300/35 bg-amber-300/[0.12] px-2.5 py-2 text-caption text-amber-100",children:[n.jsx("p",{children:"Launch includes non-ready attachments. Continue anyway?"}),n.jsxs("label",{className:"mt-1.5 flex items-center gap-2",children:[n.jsx("input",{type:"checkbox",checked:Y,onChange:Q=>t.setLaunchWarningAccepted(Q.target.checked)}),n.jsx("span",{children:"I understand unresolved attachment extraction may reduce context quality."})]})]},"launch-warning")}),n.jsx("div",{className:"relative",children:n.jsx(xh,{open:B!==null,mode:B??"assignee",agents:re,quickAgents:z,query:K,selectedAssigneeId:te,selectedWatcherIds:Ce,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:r})}),n.jsxs(he.section,{"data-testid":"chat-dock","data-state":we,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:sn.durationEntrance/1e3,ease:sn.easingEntrance},className:ue("group/dock relative rounded-[22px] border border-white/[0.12] bg-[#0A0E16]/80 px-3 py-2.5 backdrop-blur-xl","shadow-[inset_0_1px_0_rgba(255,255,255,0.035),0_14px_34px_rgba(0,0,0,0.36)]","transition-[border-color] duration-200",we!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:c,className:ue("absolute -right-1 -top-1 z-10 flex h-6 w-6 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16] text-secondary","opacity-0 transition-opacity duration-200","hover:bg-white/[0.08] hover:text-primary","group-hover/dock:opacity-100"),"aria-label":"Minimize chat",title:"Minimize to icon",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}),n.jsx("input",{ref:Q=>{t.fileInputRef.current=Q},type:"file",multiple:!0,className:"hidden",onChange:Q=>{t.handleFilesAdded(Q.target.files),Q.currentTarget.value=""}}),n.jsx(It,{children:tt&&n.jsx(mh,{messages:me,isStreaming:at,collapsed:p,onClick:be})}),n.jsxs("div",{className:"relative",children:[n.jsx(fh,{open:h,agents:ct,query:y,activeIndex:w,anchorRect:null,onSelect:Mt,onClose:()=>I(!1)}),n.jsx(gh,{open:X,initiatives:Me,query:W,activeIndex:D,onSelect:q,onClose:()=>Z(!1)})]}),n.jsx(It,{initial:!1,children:ze.length>0&&n.jsx(he.div,{initial:s?!1:{opacity:0,height:0},animate:s?{}:{opacity:1,height:"auto"},exit:s?{}:{opacity:0,height:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"mb-2 overflow-hidden",children:n.jsx("div",{className:"flex flex-wrap items-start gap-2","aria-live":"polite",children:ze.map(Q=>n.jsxs("div",{className:ue("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",Q.status==="failed"?"border-rose-400/30 bg-rose-400/[0.08]":"border-white/[0.1] bg-white/[0.04]"),children:[n.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:`${hl(Q.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:hl(Q.mimeType),strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"max-w-[180px] truncate text-caption font-medium text-primary",children:Q.name}),n.jsxs("p",{className:"text-micro text-muted",children:[yh(Q.mimeType,Q.name),Q.sizeBytes?` · ${th(Q.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments(Ee=>Ee.filter(nt=>nt.id!==Q.id)),className:ue("absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full","border border-white/[0.16] bg-[#0A0E16] text-[10px] text-secondary","opacity-0 transition-opacity duration-150 group-hover:opacity-100","hover:bg-white/[0.1] hover:text-primary"),"aria-label":`Remove ${Q.name}`,children:"×"}),Q.status!=="ready"&&Q.status!=="failed"&&n.jsx("div",{className:"absolute bottom-0.5 left-3 right-3 h-0.5 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("div",{className:"h-full w-1/2 animate-pulse rounded-full bg-white/[0.2]"})}),Q.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(Q.id),className:"ml-1 rounded-md border border-rose-300/20 bg-rose-400/[0.12] px-1.5 py-0.5 text-micro text-rose-200 hover:bg-rose-400/[0.2]",children:"Retry"})]},Q.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var Q;return(Q=t.fileInputRef.current)==null?void 0:Q.click()},className:ue("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","border border-white/[0.12] bg-transparent text-secondary","transition-colors duration-150","hover:bg-white/[0.06] hover:text-primary"),"aria-label":"Add files and more",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsxs(he.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:ue("mb-0.5 inline-flex h-7 flex-shrink-0 items-center gap-1.5 rounded-full px-2","border text-micro font-medium","transition-all duration-200",ce==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":ce==="openai"?"border-emerald-400/30 bg-emerald-400/[0.08] text-emerald-300":"border-white/[0.12] bg-white/[0.04] text-muted"),title:`Provider: ${qe.label}. Click to switch.`,"aria-label":`Current provider: ${qe.label}. Click to cycle.`,children:[n.jsx(gl,{icon:qe.icon}),n.jsx("span",{children:qe.shortLabel})]}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"chat-dock-input",className:"sr-only",children:"Chat composer"}),n.jsx("textarea",{ref:i,id:"chat-dock-input",value:ae,onFocus:Qe,onBlur:St,onChange:zt,onKeyDown:_e,placeholder:"Ask anything",rows:1,className:ue("w-full resize-none border-none bg-transparent py-1 text-[13px] leading-[22px] text-primary","placeholder:text-muted/60 focus:outline-none"),style:{minHeight:pl,maxHeight:fl,overflowY:"auto"},"aria-expanded":we!=="resting"})]}),O.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:ue("mb-0.5 inline-flex h-7 min-w-[28px] flex-shrink-0 items-center justify-center gap-1 rounded-full px-1.5","text-micro text-muted transition-colors duration-150","hover:bg-white/[0.06] hover:text-secondary"),"aria-label":`${O.length} thread${O.length===1?"":"s"}`,children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),O.length]}),n.jsx(he.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!Se,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:ue("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",Se?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:ne?`Send to ${ne.name} via ${qe.shortLabel}`:`Send via ${qe.shortLabel}`,"aria-label":ne?`Send to ${ne.name} via ${qe.shortLabel}`:`Send message via ${qe.shortLabel}`,children:Le})]}),n.jsx(It,{children:(ne||G)&&we!=="resting"&&n.jsxs(he.div,{initial:s?!1:{opacity:0},animate:s?{}:{opacity:1},exit:s?{}:{opacity:0},transition:{duration:.15},className:"mt-1.5 flex items-center gap-2 px-10",children:[ne&&n.jsxs("button",{ref:Q=>{r.current=Q},type:"button",onClick:t.toggleWatcherPicker,className:ue("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-micro","text-[#E1FFB2]/80 transition-colors duration-150 hover:bg-lime/[0.08]"),children:[n.jsx(en,{name:ne.name,hint:ne.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",ne.name]}),ne.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),G&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",G.name]}),ce!=="auto"&&n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro",style:{color:qe.accent},children:[n.jsx(gl,{icon:qe.icon}),qe.shortLabel]})]})})]})]})]})}const xl={completed:M.lime,needs_attention:M.amber,in_progress:M.teal,blocked:M.red,unknown:"rgba(255,255,255,0.4)"};function yl({workstreamTitle:e,items:t,firstTimestamp:s,lastTimestamp:i,onExpandItem:r}){const[a,l]=o.useState(!1),c=t.reduce((p,x)=>(p[x.status]=(p[x.status]??0)+1,p),{}),d=new Date(s).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),u=new Date(i).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsxs("button",{type:"button",onClick:()=>l(p=>!p),className:"flex w-full items-start justify-between gap-3 text-left",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-micro",style:{color:M.teal,opacity:.8},children:"∞"}),n.jsxs("p",{className:"text-body font-semibold text-bright",children:["Autopilot ran ",t.length," sessions in “",e,"”"]})]}),n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-caption text-secondary",children:[c.completed&&c.completed>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:M.lime}}),c.completed," completed"]}),c.needs_attention&&c.needs_attention>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:M.amber}}),c.needs_attention," needs attention"]}),c.in_progress&&c.in_progress>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full status-breathe",style:{backgroundColor:M.teal}}),c.in_progress," in progress"]}),c.blocked&&c.blocked>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:M.red}}),c.blocked," blocked"]})]}),n.jsxs("p",{className:"mt-1 text-micro text-muted tabular-nums",children:[d," — ",u]})]}),n.jsx("span",{className:"mt-1.5 text-micro text-muted",children:a?"Hide":"Show details"})]}),n.jsx(It,{children:a&&n.jsx(he.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:n.jsx("div",{className:"mt-3 space-y-1.5 border-t border-white/[0.06] pt-3",children:t.map((p,x)=>n.jsxs(he.button,{type:"button",initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{delay:x*.04,duration:.15},onClick:()=>r==null?void 0:r(x),className:"flex w-full items-center gap-2 rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2 text-left hover:bg-white/[0.05]",children:[n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full",style:{backgroundColor:xl[p.status]??xl.unknown}}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-caption text-primary",children:p.title}),n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:Pt(p.timestamp)})]},`burst-${x}`))})})})]})}const ka=50,wh=50,Fi=20,bl=3600,vl=12e3,vr={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"},wl=["live","24h","7d","all"];function kl(e){if(e==="custom"||e==="all")return null;const t=wl.indexOf(e);return t<0?null:wl[t+1]??null}function Il(e,t){if(e.size!==t.size)return!1;for(const[s,i]of e){const r=t.get(s);if(!r)return!1;for(const a of Object.keys(i))if(i[a]!==r[a])return!1}return!0}function kh(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function Nl(e){return e==="codex"||e==="openai"||e==="anthropic"||e==="openclaw"}function ms(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function wr(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function kr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Ia(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function jl(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function tn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function so(e){if(!e)return;let t={...e},s=tn(t.metadata),i=0;for(;s&&i<4;)t={...t,...s},s=tn(s.metadata),i+=1;return t}function rt(e){const t=tn(e==null?void 0:e.metadata);return so(t)}function Ih(e){const t=so(e);if(!t)return"";const s=[];for(const[i,r]of Object.entries(t))typeof r=="string"&&(i.toLowerCase().includes("type")||i.toLowerCase().includes("kind")||i.toLowerCase().includes("summary")||i.toLowerCase().includes("message")||i.toLowerCase().includes("artifact")||i.toLowerCase().includes("decision")||i.toLowerCase().includes("run")||i.toLowerCase().includes("title")||i.toLowerCase().includes("task")||i.toLowerCase().includes("workstream")||i.toLowerCase().includes("milestone"))&&s.push(r);return s.join(" ")}function ui(e){if(e.runId)return e.runId;const t=rt(e);if(!t)return null;const s=["runId","run_id","sliceRunId","slice_run_id","sessionId","session_id","agentRunId"];for(const i of s){const r=t[i];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function fi(e){const t=rt(e);if(!t)return{agentId:null,agentName:null};const s=(typeof t.agent_id=="string"&&t.agent_id.trim().length>0?t.agent_id.trim():null)??(typeof t.agentId=="string"&&t.agentId.trim().length>0?t.agentId.trim():null)??(typeof e.agentId=="string"&&e.agentId.trim().length>0?e.agentId.trim():null),i=(typeof t.agent_name=="string"&&t.agent_name.trim().length>0?t.agent_name.trim():null)??(typeof t.agentName=="string"&&t.agentName.trim().length>0?t.agentName.trim():null)??(typeof e.agentName=="string"&&e.agentName.trim().length>0?e.agentName.trim():null);return{agentId:s,agentName:i}}function Al(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const Nh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,jh=/^[0-9a-f]{20,}$/i,Sc=/^\d+$/,Cc=/^(user|usr|clerk)_[a-z0-9]+$/i;function wn(e){if(!e)return null;const t=e.trim();return!t||Nh.test(t)||jh.test(t)||Sc.test(t)||Cc.test(t)?null:t}const Ah=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function _h(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return Ah.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function _l(e,t,s){if(!e)return null;let i=null;for(const a of t){const l=wn(Al(e[a]));if(l){i=l;break}}let r=null;for(const a of s){const l=wn(Al(e[a]));if(l){r=l;break}}return!i&&!r?null:{id:i,name:r,label:r??i??"OrgX"}}function Sh(e,t){var s,i;if(!e||!t)return!1;if(e.id&&t.id){const r=e.id.trim().toLowerCase(),a=t.id.trim().toLowerCase();if(r===a){const l=((s=e.name)==null?void 0:s.trim().toLowerCase())??null,c=((i=t.name)==null?void 0:i.trim().toLowerCase())??null;return l&&c&&l!==c?!1:["unknown","system","agent","none","null","undefined"].includes(r)?!!(l&&c&&l===c):!0}}return!e.name||!t.name?!1:e.name.trim().toLowerCase()===t.name.trim().toLowerCase()}function Sl(e){const t=rt(e),s=fi(e),i=Xi(e),r=wn(s.agentId),a=wn(s.agentName),l=wn(e.requesterAgentId??null),c=wn(e.requesterAgentName??null),u=(l||c?{id:l,name:c,label:c??l??"OrgX"}:null)??_l(t,["requested_by_agent_id","requestedByAgentId","requester_agent_id","requesterAgentId","runner_agent_id","runnerAgentId"],["requested_by_agent_name","requestedByAgentName","requester_agent_name","requesterAgentName","requester_name","requesterName","runner_agent_name","runnerAgentName"])??null,p=wn(e.executorAgentId??null),x=wn(e.executorAgentName??null),h=(p||x?{id:p,name:x,label:x??p??"Agent"}:null)??_l(t,["executed_by_agent_id","executedByAgentId","executor_agent_id","executorAgentId","delegated_to_agent_id","delegatedToAgentId","handoff_to_agent_id","handoffToAgentId","agent_id","agentId"],["executed_by_agent_name","executedByAgentName","executor_agent_name","executorAgentName","delegated_to_agent_name","delegatedToAgentName","handoff_to_agent_name","handoffToAgentName","agent_name","agentName"])??(r||a?{id:r,name:a,label:a??r??"Agent"}:null);return u&&h?Sh(u,h)?{requester:u,executor:h,mode:"single",primaryLabel:h.label,subtitle:h.label}:{requester:u,executor:h,mode:"handoff",primaryLabel:h.label,subtitle:`${u.label} handed off to ${h.label}`}:u&&!h?{requester:u,executor:null,mode:"requested",primaryLabel:u.label,subtitle:`${u.label} requested a run`}:!u&&h?{requester:null,executor:h,mode:"single",primaryLabel:h.label,subtitle:h.label}:i.isSystem?{requester:null,executor:null,mode:"system",primaryLabel:"OrgX",subtitle:"OrgX"}:{requester:null,executor:null,mode:"system",primaryLabel:wn(e.agentName??null)??wn(e.agentId??null)??"OrgX",subtitle:wn(e.agentName??null)??wn(e.agentId??null)??"OrgX"}}function Cl(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}const Ch=new Set(["autopilot_slice_dispatched","auto_continue_started","auto_continue_stopped","autopilot_transition","orchestrator_selection","orchestrator_dispatch"]),Th=new Set(["heartbeat","spawn_guard_blocked","spawn_guard_rate_limited"]);function Mh(e,t){var a;if(e.requesterAgentId==="main"||e.agentId==="main")return"user";const s=rt(e),i=fe(s,["event","event_name","eventName"])??"";return(fe(s,["source"])??"")==="user"?"user":Ch.has(i)||(a=t.primaryLabel)!=null&&a.toLowerCase().includes("xandy")?"orchestrator":t.mode==="system"||Th.has(i)?"system":"agent"}const Eh={user:M.lime,system:"rgba(255,255,255,0.15)",orchestrator:M.iris,agent:""};function Rh(e){switch(e){case"user":return"You";case"system":return"OrgX";case"orchestrator":return"Xandy";case"agent":return""}}function mi(e){const t=rt(e);if(!t)return null;const s=["workstreamId","workstream_id"];for(const r of s){const a=t[r];if(typeof a=="string"&&a.trim().length>0)return a.trim()}const i=t.orgx_context;if(i&&typeof i=="object"&&!Array.isArray(i)){const r=i,a=r.workstreamId??r.workstream_id;if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function Ir(e){const t=rt(e);if(!t)return null;const s=["artifact_id","artifactId","work_artifact_id"];for(const i of s){const r=t[i];if(typeof r=="string"&&r.length>0)return r}return null}const Tl=new Map([["autopilot_slice_artifact_buffered","artifact"],["decision_buffered","decision"],["auto_continue_spawn_guard_blocked","decision"],["auto_continue_spawn_guard_rate_limited","decision"],["agent_launch_spawn_guard_blocked","decision"],["agent_launch_spawn_guard_rate_limited","decision"],["agent_restart_spawn_guard_blocked","decision"],["agent_restart_spawn_guard_rate_limited","decision"],["next_up_fallback_spawn_guard_blocked","decision"],["next_up_fallback_spawn_guard_rate_limited","decision"],["autopilot_slice_mcp_handshake_failed","decision"],["autopilot_slice_timeout","decision"],["autopilot_slice_log_stall","decision"],["autopilot_autofix_scheduled","decision"],["autopilot_autofix_executed","message"],["autopilot_autofix_skipped","message"]]);function Nr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function Tc(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="boolean")return i;if(typeof i=="string"){const r=i.trim().toLowerCase();if(r==="true")return!0;if(r==="false")return!1}}return null}function Hs(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="number"&&Number.isFinite(i))return Math.max(0,i);if(typeof i=="string"){const r=Number(i);if(Number.isFinite(r))return Math.max(0,r)}}return null}function Lh(e){if(!e)return null;const t=e.event;if(typeof t!="string")return null;const s=t.trim().toLowerCase();return s.length>0?s:null}function Dh(e){const t=rt(e),s=Nr(e.kind)??Nr(t==null?void 0:t.activity_bucket)??Nr(t==null?void 0:t.activityBucket)??Nr(t==null?void 0:t.bucket);if(s)return s;if(e.type==="artifact_created")return"artifact";if(e.type==="decision_requested"||e.type==="decision_resolved")return"decision";const i=Lh(t),r=e.decisionRequired===!0||Tc(t,["decision_required","decisionRequired"])===!0,a=Hs(t,["artifacts","artifact_count","artifactCount"])??0,l=Hs(t,["decisions","decision_count","decisionCount"])??0,c=Hs(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Hs(t,["non_blocking_decisions","nonBlockingDecisions","non_blocking_decision_count","nonBlockingDecisionCount"])??0;if(i==="autopilot_slice_result")return r||c>0?"decision":a>0?"artifact":l>0||d>0?"decision":"message";if(i==="auto_continue_stopped"){const p=$n(fe(t,["stop_reason","stopReason"])??"");if(p==="blocked"||p==="error")return"decision"}return i&&Tl.has(i)?Tl.get(i):typeof(t==null?void 0:t.artifact_id)=="string"||typeof(t==null?void 0:t.artifactId)=="string"||typeof(t==null?void 0:t.work_artifact_id)=="string"||a>0?"artifact":r||l>0||c>0||d>0?"decision":"message"}function $h(e,t){if(e.type==="run_completed"||e.type==="milestone_completed"||e.type==="decision_resolved")return!0;const s=fe(t,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]);if(Yi(s))return!0;const i=fe(t,["stop_reason","stopReason"]);if($n(i)==="completed")return!0;const r=t?Mc(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]):null,a=e.decisionRequired===!0||Tc(t,["decision_required","decisionRequired"])===!0,l=Hs(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0;return r!==null&&r>=100&&!a&&l===0}function Ui(e){return{run_started:"Run started",run_completed:"Run completed",run_failed:"Run failed",artifact_created:"Artifact created",decision_requested:"Decision requested",decision_resolved:"Decision resolved",handoff_requested:"Handoff requested",handoff_claimed:"Handoff claimed",handoff_fulfilled:"Handoff fulfilled",blocker_created:"Blocker created",milestone_completed:"Milestone completed",delegation:"Delegation"}[e]}function Ph(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"unknown";const s=new Date(t.getFullYear(),t.getMonth(),t.getDate());return String(s.getTime())}function Fh(e){const t=Number(e);if(!Number.isFinite(t))return"Unknown day";const s=new Date(t),i=new Date,r=new Date(i.getFullYear(),i.getMonth(),i.getDate()),a=new Date(r);return a.setDate(r.getDate()-1),s.getTime()===r.getTime()?"Today":s.getTime()===a.getTime()?"Yesterday":s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:s.getFullYear()===i.getFullYear()?void 0:"numeric"})}function Na(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function ja(e){return e==="completed"?M.lime:e==="needs_input"?M.amber:e==="issue"?M.red:M.teal}function Oh(e,t){var s;return t.status==="failed"?{state:"issue",why:t.sentence}:t.status==="needs_attention"?{state:(((s=t.nextAction)==null?void 0:s.toLowerCase())??"").includes("decision")?"needs_input":"issue",why:t.sentence}:t.status==="in_progress"?{state:"in_progress",why:t.sentence}:t.status==="completed"?{state:"completed",why:t.sentence}:e==="artifact"?{state:"completed",why:"Produced an artifact output."}:{state:"update",why:t.sentence}}function Ml(e){let t="Workstream";const s=e.allItems.map(i=>{const r=rt(i.item),a=fe(r,["workstream_title","workstreamTitle","dispatch_workstream_title"]);a&&(t=a);const c=fe(r,["task_title","taskTitle","dispatch_task_title"])??Xi(i.item).title;let d="unknown";return i.userState==="completed"?d="completed":i.userState==="needs_input"||i.userState==="issue"?d="needs_attention":i.userState==="in_progress"&&(d="in_progress"),{title:c,status:d,timestamp:i.item.timestamp}});return{workstreamTitle:t,items:s}}function El(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function As(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number(e);if(Number.isFinite(t))return t}return null}function kn(e){const t=As(e);if(t!==null)return Math.max(0,Math.round(t));if(Array.isArray(e))return e.length;if(e&&typeof e=="object"&&!Array.isArray(e)){const s=e,i=As(s.count??s.total??s.size);if(i!==null)return Math.max(0,Math.round(i))}return null}function qh(e){const t=As(e);if(t===null)return null;const s=t>0&&t<=1?t*100:t;return Math.max(0,Math.min(100,Math.round(s)))}function Mc(e,t){for(const s of t){const i=qh(e[s]);if(i!==null)return i}return null}function jr(e,t){const s=[],i=new Set,r=a=>{if(typeof a!="string")return;const l=a.trim();!l||i.has(l)||(i.add(l),s.push(l))};for(const a of t){const l=e[a];if(Array.isArray(l)){for(const c of l)r(c);continue}r(l)}return s}function Ec(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=jr(e,["blocking_decision_ids","blockingDecisionIds"]),s=jr(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),i=jr(e,["decision_id","decisionId","decision_ids","decisionIds"]),r=new Set([...i,...t,...s]),a=e.decisions_needed??e.decisionsNeeded;if(Array.isArray(a))for(const l of a){if(!l||typeof l!="object"||Array.isArray(l))continue;const c=l,d=jr(c,["id","decision_id","decisionId"]),u=c.blocking!==!1;for(const p of d)r.add(p),u?t.includes(p)||t.push(p):s.includes(p)||s.push(p)}return{decisionIds:Array.from(r),blockingDecisionIds:t,nonBlockingDecisionIds:s}}function Rc(e){if(!e)return null;const t=rt(e);if(!t)return null;const s=typeof t.event=="string"&&t.event.trim().length>0?t.event.trim():null,i=s??"",r=i.startsWith("autopilot_slice")&&!i.includes("artifact")||i.startsWith("autopilot_autofix");if(!s||!r&&s!=="auto_continue_started"&&s!=="auto_continue_stopped"&&s!=="next_up_manual_dispatch_started")return null;const a=fi(e),l=(typeof t.requested_by_agent_id=="string"&&t.requested_by_agent_id.trim().length>0?t.requested_by_agent_id.trim():null)??(typeof t.requestedByAgentId=="string"&&t.requestedByAgentId.trim().length>0?t.requestedByAgentId.trim():null)??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null)??a.agentId,c=(typeof t.requested_by_agent_name=="string"&&t.requested_by_agent_name.trim().length>0?t.requested_by_agent_name.trim():null)??(typeof t.requestedByAgentName=="string"&&t.requestedByAgentName.trim().length>0?t.requestedByAgentName.trim():null)??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??a.agentName,d=(typeof t.source_client=="string"&&t.source_client.trim().length>0?t.source_client.trim():null)??(typeof t.sourceClient=="string"&&t.sourceClient.trim().length>0?t.sourceClient.trim():null)??(typeof e.runtimeClient=="string"&&e.runtimeClient.trim().length>0?e.runtimeClient.trim():null),u=t.required_skills??t.requiredSkills,p=Array.isArray(u)?u.filter(Y=>typeof Y=="string"&&Y.trim().length>0):[],x=Yh(p),b=t.task_ids??t.taskIds,h=Array.isArray(b)?b.filter(Y=>typeof Y=="string"&&Y.trim().length>0):[],I=t.milestone_ids??t.milestoneIds,y=Array.isArray(I)?I.filter(Y=>typeof Y=="string"&&Y.trim().length>0):[],j=fe(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),w=fe(t,["initiative_title","initiativeTitle"]),N=fe(t,["initiative_status","initiativeStatus"]),f=mi(e),T=fe(t,["workstream_title","workstreamTitle"]),X=fe(t,["workstream_status","workstreamStatus"]),Z=fe(t,["task_title","taskTitle"]),W=fe(t,["milestone_title","milestoneTitle"]),ke=fe(t,["domain"]),D=fe(t,["phase","slice_phase","slicePhase"]),E=fe(t,["next_step","nextStep"]),de=Mc(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),ie=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,we=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,ae=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,ze=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,pe=typeof t.error=="string"?t.error:null,le=kn(t.artifacts??t.artifact_count??t.artifactCount),te=kn(t.decisions??t.decision_count??t.decisionCount),ne=Ec(t),Ce=t.decisions_needed??t.decisionsNeeded;let G=kn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),R=kn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((G===null||R===null)&&Array.isArray(Ce)){let Y=0,ce=0;for(const qe of Ce){if(!qe||typeof qe!="object"||Array.isArray(qe))continue;qe.blocking===!1?ce+=1:Y+=1}G===null&&(G=Y),R===null&&(R=ce)}G===null&&te!==null&&e.decisionRequired===!0&&(G=te>0?te:1),R===null&&te!==null&&G!==null&&(R=Math.max(0,te-G)),G===null&&te!==null&&R!==null&&(G=Math.max(0,te-R));const z=kn(t.status_updates_applied??t.statusUpdatesApplied),B=kn(t.task_updates??t.taskUpdates),K=kn(t.milestone_updates??t.milestoneUpdates),re=z??(B!==null||K!==null?(B??0)+(K??0):null),ge=kn(t.status_updates_buffered??t.statusUpdatesBuffered),Se=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,oe=As(t.token_budget??t.tokenBudget),ye=As(t.tokens_used??t.tokensUsed),me=a.agentId??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null),O=a.agentName??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??x,U=x&&!a.agentName?null:me;return{event:s,agentId:U,agentName:O,requesterAgentId:l,requesterAgentName:c,dispatcherClient:d,initiativeId:j,domain:ke,phase:D,progressPct:de,nextStep:E,requiredSkills:p,initiativeStatus:N,initiativeTitle:w,workstreamId:f,workstreamStatus:X,workstreamTitle:T,taskTitle:Z,milestoneTitle:W,taskIds:h,milestoneIds:y,parsedStatus:ie,hasOutput:we,artifacts:le,decisions:te,blockingDecisions:G,nonBlockingDecisions:R,decisionIds:ne.decisionIds,blockingDecisionIds:ne.blockingDecisionIds,nonBlockingDecisionIds:ne.nonBlockingDecisionIds,statusUpdatesApplied:re,statusUpdatesBuffered:ge,stopReason:Se,tokenBudget:oe,tokensUsed:ye,logPath:ae,outputPath:ze,error:pe}}function Pr(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function Bh(e){const t=so(e);if(!t)return null;const s=t,i=s.orgx_provenance,r=i&&typeof i=="object"&&!Array.isArray(i)?i:null,a=r!=null&&r.skill_pack&&typeof r.skill_pack=="object"&&!Array.isArray(r.skill_pack)?r.skill_pack:null,l=(typeof s.orgx_plugin_version=="string"?s.orgx_plugin_version:null)??(typeof(r==null?void 0:r.plugin_version)=="string"?r.plugin_version:null),c=(typeof s.skill_pack_name=="string"?s.skill_pack_name:null)??(typeof(a==null?void 0:a.name)=="string"?a.name:null),d=(typeof s.skill_pack_version=="string"?s.skill_pack_version:null)??(typeof(a==null?void 0:a.version)=="string"?a.version:null),u=(typeof s.skill_pack_checksum=="string"?s.skill_pack_checksum:null)??(typeof(a==null?void 0:a.checksum)=="string"?a.checksum:null),p=(typeof s.skill_pack_source=="string"?s.skill_pack_source:null)??(typeof(a==null?void 0:a.source)=="string"?a.source:null),x=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,b=typeof s.kickoff_context_source=="string"?s.kickoff_context_source:null,h=typeof s.spawn_guard_model_tier=="string"?s.spawn_guard_model_tier:null,I=typeof s.provider=="string"?s.provider:null,y=typeof s.model=="string"?s.model:null,j=typeof s.domain=="string"?s.domain:null,w=s.required_skills??s.requiredSkills,N=Array.isArray(w)?w.filter(T=>typeof T=="string"&&T.trim().length>0):[];return!!l||!!(c||d||u)||!!x||!!(h||I||y||j)||N.length>0?{pluginVersion:l,skillPack:c||d||u||p?{name:c,version:d,checksum:u,source:p}:null,kickoffContextHash:x,kickoffContextSource:b,modelTier:h,provider:I,model:y,domain:j,requiredSkills:N}:null}function Lc(e){if(!e)return null;const t=rt(e);if(!t||typeof t!="object")return null;const s=["artifact","artifacts","output","outputs","result","results","payload","toolOutput","toolOutputs","toolResult","toolResults"];for(const i of s){const r=t[i];if(r!=null)return{source:i,value:r}}return e.type==="artifact_created"?{source:"metadata",value:t}:null}function Hr(e){if(!e)return"Artifact";const t=e.toLowerCase();return t.includes("pull_request")||t.includes("pr")?"Pull Request":t.includes("document")||t.includes("doc")||t.includes("spec")?"Document":t.includes("code")||t.includes("implementation")?"Code":t.includes("test")?"Tests":t.includes("design")?"Design":t.includes("config")?"Config":t.includes("decision")?"Decision":st(e)}function zh(e){const t=rt(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),i=Lc(e);if(!i&&!s)return null;const r=fe(t,["artifact_type","artifactType","atomic_unit_type"]),a=fe(t,["artifact_title","title","name"]),l=fe(t,["url","pr_url","commit_url"]),c=Hr(r);let d=c;r||(e.type==="artifact_created"?d="Created artifact":(i==null?void 0:i.source)==="toolOutput"||(i==null?void 0:i.source)==="toolOutputs"?d="Tool output":(i==null?void 0:i.source)==="toolResult"||(i==null?void 0:i.source)==="toolResults"?d="Result":(i==null?void 0:i.source)==="output"||(i==null?void 0:i.source)==="outputs"?d="Output":s?d="Registered artifact":d="Artifact");let u="";if(a)u=a;else if(i){const p=i.value;if(typeof p=="string")u=p.length>80?p.slice(0,80)+"…":p;else if(Array.isArray(p))u=`${p.length} item${p.length===1?"":"s"}`;else if(p&&typeof p=="object"){const x=Object.keys(p);u=x.length<=4?x.join(", "):`${x.length} fields`}}return{label:d,preview:u,hasRegisteredId:s,title:a,typeBadge:c,url:l}}function Uh(e){const t=rt(e);if(!t)return[];const s=[],i=t.outcomes&&typeof t.outcomes=="object"?t.outcomes:null,r=fe(t,["pr_url"])??(i?fe(i,["pr_url"]):null),a=fe(t,["pr_number"])??(i?fe(i,["pr_number"]):null);(a||r)&&s.push({kind:"pr",label:a?`#${a}`:"linked",url:r});const l=fe(t,["commit_sha"])??(i?fe(i,["commit_sha"]):null),c=fe(t,["commit_url"])??(i?fe(i,["commit_url"]):null);(l||c)&&s.push({kind:"commit",label:l?l.slice(0,7):"linked",url:c});const d=i==null?void 0:i.tests;if(d&&typeof d=="object"){const x=d,b=typeof x.passed=="number"?x.passed:null,h=typeof x.failed=="number"?x.failed:null;if(b!==null||h!==null){const I=[];b!==null&&I.push(`${b} passed`),h!==null&&h>0&&I.push(`${h} failed`),s.push({kind:"test",label:I.join(", ")})}}const u=typeof t.task_updates=="number"?t.task_updates:i&&typeof i.task_updates=="number"?i.task_updates:null;u&&u>0&&s.push({kind:"artifact",label:`${u} task${u===1?"":"s"} updated`});const p=Array.isArray(t.artifacts)?t.artifacts:null;if(p&&p.length>0&&s.length<2){const x=p[0],b=x&&typeof x=="object"&&typeof x.title=="string"?x.title:null;s.push({kind:"doc",label:b??`${p.length} artifact${p.length===1?"":"s"}`})}return s}function Yr(e){if(!e)return[];const t=tn(e.result),s=[e,t].filter(l=>!!l),i=[],r=new Set,a=(l,c)=>{if(Array.isArray(c))for(const d of c){const u=tn(d);if(!u)continue;const p=l==="Task"?["task_id","taskId","id"]:["milestone_id","milestoneId","id"],x=l==="Task"?["task_title","taskTitle","title","name"]:["milestone_title","milestoneTitle","title","name"],b=fe(u,p),h=fe(u,x)??(b&&!Wn(b)?b:null)??l,I=ks(h,b)??st(h),y=fe(u,["status","state"]),j=Kt(fe(u,["reason","summary","description","note"])),w=`${l}|${I.toLowerCase()}|${(y??"").toLowerCase()}|${(j??"").toLowerCase()}`;r.has(w)||(r.add(w),i.push({scope:l,label:I,status:y?st(y):null,reason:j}))}};for(const l of s)a("Task",l.task_updates??l.taskUpdates),a("Milestone",l.milestone_updates??l.milestoneUpdates);return i}function Wh(e){var c;const t=rt(e);if(!t)return null;const s=((c=fe(t,["event","event_name","eventName"]))==null?void 0:c.toLowerCase())??"",i=Yr(t),r=kn(t.status_updates_applied??t.statusUpdatesApplied),a=t.status_updates_buffered??t.statusUpdatesBuffered;if(s.includes("status_updates_buffered")||a===!0||typeof a=="number"&&a>0||typeof a=="string"&&["true","1","yes"].includes(a.trim().toLowerCase())){if(i.length>0){const d=i[0];return`Updates being applied: ${i.length} queued update${i.length===1?"":"s"} · ${d.label}${d.status?` → ${d.status}`:""}`}return r!==null&&r>0?`Updates being applied: ${r} status update${r===1?"":"s"} queued for sync`:"Updates being applied: status updates queued for sync"}return r!==null&&r>0?`Applied ${r} status update${r===1?"":"s"}`:null}function Hh(e){if(!e)return!1;const t=rt(e);if(!t)return!1;const s=tn(t.outcomes),i=tn(s==null?void 0:s.tests),r=Yr(t),a=kn(t.status_updates_applied??t.statusUpdatesApplied),l=t.status_updates_buffered??t.statusUpdatesBuffered,c=l===!0||typeof l=="number"&&l>0||typeof l=="string"&&["true","1","yes"].includes(l.trim().toLowerCase());return!!(s!=null&&s.pr_url||s!=null&&s.pr_number||s!=null&&s.commit_sha||s!=null&&s.commit_url||i||s!=null&&s.artifacts)||r.length>0||(a??0)>0||c}function Dc(e){const t=e.trim();return!t||/^[a-z]+:\/\//i.test(t)||/^data:/i.test(t)?!1:t.startsWith("/")||t.startsWith("~/")||/^[A-Za-z]:[\\/]/.test(t)||/^[.]{1,2}\//.test(t)?!0:t.includes("/")&&!/\s{2,}/.test(t)}function $c(e){const t=rt(e);if(!t)return[];const s=[],i=new Set,r=(l,c)=>{if(typeof c!="string")return;const d=c.trim();if(!d||!Dc(d))return;const u=`${l}:${d}`;i.has(u)||(i.add(u),s.push({key:l,path:d}))},a=(l,c="",d=0)=>{if(!(d>2))for(const[u,p]of Object.entries(l)){const x=c?`${c}.${u}`:u,b=u.toLowerCase();if(b.includes("path")||b==="url"||b==="uri"||b.endsWith("url")||b.endsWith("_file")||b.endsWith("file")||b.includes("artifact"))if(Array.isArray(p))for(const I of p)r(x,I);else r(x,p);p&&typeof p=="object"&&!Array.isArray(p)&&a(p,x,d+1)}};return a(t),s}function fe(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}const Kh=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,Vh=/\b[0-9a-f]{20,}\b/gi;function Pc(e){let t=e.replace(Kh,"").replace(Vh,"").replace(/\[workstream\b[^\]]*\]/gi,"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s{2,}/g," ").trim();return t=t.replace(/(?:\s*(?:>|\/)\s*){2,}/g," > ").replace(/^\s*(?:>|\/)\s*/g,"").replace(/\s*(?:>|\/)\s*$/g,"").replace(/\s{2,}/g," ").trim(),t}function Gh(e){return e.replace(/\bfor\s+slice\b/gi,"").replace(/\bfor\s+run\b/gi,"").replace(/\bwith\s+slice\b/gi,"").replace(/\s{2,}/g," ").replace(/\s*(?:-|:|>)\s*$/g,"").trim()}function ks(e,t){if(typeof e!="string")return null;const s=Pc(e.trim());if(!s)return null;const i=typeof t=="string"?t.trim().toLowerCase():"";if(i&&s.toLowerCase()===i||Wn(s))return null;const r=st(s).trim();return r.length>0?r:null}function Ar(e){for(const t of e){const s=ks(t.value,t.idHint);if(s)return s}return null}function Xh(e){if(!e)return{domainCurrent:null,domainMax:null,totalCurrent:null,totalMax:null};const t=e.match(/rate limit:\s*(\d+)\s*\/\s*(\d+)\s*domain(?:\s*,\s*(\d+)\s*\/\s*(\d+)\s*total)?/i);return t?{domainCurrent:Number.isFinite(Number(t[1]))?Number(t[1]):null,domainMax:Number.isFinite(Number(t[2]))?Number(t[2]):null,totalCurrent:Number.isFinite(Number(t[3]))?Number(t[3]):null,totalMax:Number.isFinite(Number(t[4]))?Number(t[4]):null}:{domainCurrent:null,domainMax:null,totalCurrent:null,totalMax:null}}function Qh(e,t){if(!e)return null;const s=rt(e);if(!s)return null;const i=fe(s,["event","event_name","eventName"]),r=tn(s.spawn_guard),a=tn(r==null?void 0:r.checks),l=tn((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),c=fe(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=Xh(c),u=As(l==null?void 0:l.current)??d.domainCurrent,p=As(l==null?void 0:l.max)??d.domainMax,x=d.totalCurrent,b=d.totalMax,h=typeof(l==null?void 0:l.passed)=="boolean"?l.passed:null,I=((i==null?void 0:i.includes("rate_limited"))??!1)||!!(c&&/rate limit/i.test(c))||h===!1;return!((i==null?void 0:i.includes("spawn_guard"))??!1)&&!I&&!r&&!c?null:{event:i,blockedReason:c,domain:fe(s,["domain"])??fe(r,["domain","task_domain"]),modelTier:fe(s,["spawn_guard_model_tier","model_tier"])??fe(r,["modelTier","model_tier"]),domainCurrent:u,domainMax:p,totalCurrent:x,totalMax:b,retryAt:fe(s,["next_retry_at","nextRetryAt"]),retryInMs:As(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:I}}function Yh(e){var i;if(e.length!==1)return null;const t=(i=e[0])==null?void 0:i.trim();if(!t)return null;const s={"orgx-marketing-agent":"OrgX Marketing","orgx-engineering-agent":"OrgX Engineering","orgx-design-agent":"OrgX Design","orgx-product-agent":"OrgX Product","orgx-sales-agent":"OrgX Sales","orgx-operations-agent":"OrgX Operations","orgx-orchestrator-agent":"OrgX Orchestrator"};if(s[t])return s[t];if(t.endsWith("-agent")){const r=t.replace(/^orgx-/,"").replace(/-agent$/,"").trim();return r.length===0?null:`OrgX ${st(r)}`}return null}function Jh(e){if(!e)return!1;const t=e.trim().toLowerCase();return t.startsWith("orgx ")?t==="orgx engineering"||t==="orgx product"||t==="orgx marketing"||t==="orgx sales"||t==="orgx operations"||t==="orgx design"||t==="orgx orchestrator":!1}function Aa(e,t,s){const i=typeof e=="string"&&e.trim().length>0?e.trim():null,r=typeof t=="string"&&t.trim().length>0?t.trim():null,a=r?(s==null?void 0:s.get(r))??null:null,l=i&&a&&Jh(i)?a:i??a;if(l)return ta(l);if(!r)return"OrgX";const c=r.toLowerCase();return c==="main"||c==="system"||c==="unknown"||c==="runtime"||c==="orgx"||c==="openclaw"||c==="null"||c==="undefined"?ta(r):Bi.test(r)||Zh.test(r)||Sc.test(r)||Cc.test(r)?"OrgX":ta(r)}const Bi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Zh=/^[0-9a-f]{20,}$/i,eg=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function Kr(e){const t=new Set;if(!e)return t;for(const a of[e.title,e.summary,e.description])if(typeof a=="string")for(const l of a.match(eg)??[]){const c=l.trim().toLowerCase();Bi.test(c)&&t.add(c)}typeof e.runId=="string"&&Bi.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=rt(e);if(!s)return t;const i=["run_id","runId","last_run_id","lastRunId","active_run_id","activeRunId","slice_id","sliceId","worker_run_id","workerRunId","correlation_id","correlationId","initiative_id","initiativeId","workstream_id","workstreamId","task_id","taskId","milestone_id","milestoneId","decision_id","decisionId","outbox_event_id","outboxEventId"],r=["task_ids","taskIds","milestone_ids","milestoneIds","decision_ids","decisionIds","blocking_decision_ids","blockingDecisionIds","non_blocking_decision_ids","nonBlockingDecisionIds","allowed_workstream_ids","allowedWorkstreamIds"];for(const a of i){const l=s[a];if(typeof l=="string"){const c=l.trim().toLowerCase();Bi.test(c)&&t.add(c)}}for(const a of r){const l=s[a];if(Array.isArray(l))for(const c of l){if(typeof c!="string")continue;const d=c.trim().toLowerCase();Bi.test(d)&&t.add(d)}}return t}function tg(e){if(!e)return[];const t=rt(e);return Ec(t).decisionIds}function ng(e,t,s){if(!e)return[];const i=rt(e),r=fe(i,["workstream_id","workstreamId"]),a=fe(i,["initiative_id","initiativeId"]),l=Kr(e);if(!r&&!a&&l.size===0)return[];const c=ms(e.timestamp),d=[];for(const b of t){if(b.id===e.id)continue;const h=rt(b);if(!h)continue;const I=fe(h,["workstream_id","workstreamId"]),y=fe(h,["initiative_id","initiativeId"]),j=Kr(b),w=l.size>0&&Array.from(l).some(W=>j.has(W)),N=!!r&&!!I&&r===I;if(!w&&!N&&!(!!a&&!!y&&a===y))continue;const T=$c(b).filter(W=>!s.has(W.path));if(T.length===0)continue;const X=Math.abs(ms(b.timestamp)-c);if(!w&&X>7200*1e3)continue;const Z=w?0:N?1:2;!w&&X>1200*1e3||d.push({priority:Z,delta:X,evidence:T})}if(d.length===0)return[];d.sort((b,h)=>b.priority!==h.priority?b.priority-h.priority:b.delta-h.delta);const u=[],p=new Set(s),x=d[0].priority;for(const b of d){if(b.priority!==x)break;for(const h of b.evidence)if(!p.has(h.path)&&(p.add(h.path),u.push({key:`related.${h.key}`,path:h.path}),u.length>=8))return u}return u}function sg(e,t){if(!e)return null;const s=rt(e),i=fe(s,["workstream_id","workstreamId"]),r=fe(s,["initiative_id","initiativeId"]),a=Kr(e);if(!i&&!r&&a.size===0)return null;const l=ms(e.timestamp),c=[];for(const u of t){if(u.id===e.id)continue;const p=Rc(u);if(!p)continue;const x=rt(u);if(!x)continue;const b=fe(x,["workstream_id","workstreamId"]),h=fe(x,["initiative_id","initiativeId"]),I=Kr(u),y=a.size>0&&Array.from(a).some(X=>I.has(X)),j=!!i&&!!b&&i===b;if(!y&&!j&&!(!!r&&!!h&&r===h))continue;const N=Math.abs(ms(u.timestamp)-l);if(!y&&N>1200*1e3)continue;const f=y?"shared_id":j?"workstream":"initiative",T=f==="shared_id"?0:f==="workstream"?1:2;c.push({priority:T,delta:N,relation:f,detail:p})}if(c.length===0)return null;c.sort((u,p)=>u.priority!==p.priority?u.priority-p.priority:u.delta-p.delta);const d=c[0];return{detail:d.detail,relation:d.relation}}function $n(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function Yi(e){const t=$n(e);return["done","complete","completed","stopped","success"].includes(t)}function ig(e){const t=$n(e.parsedStatus),s=$n(e.event);return t==="failed"||t==="error"||t==="timed_out"||t==="timeout"||t==="aborted"||s.includes("error")||s.includes("timeout")?"critical":t==="blocked"||e.stopReason==="blocked"?"warning":Yi(t)||e.stopReason==="completed"?"positive":"neutral"}function rg(e){if(Yi(e.parsedStatus)||e.stopReason==="completed")return 100;const t=$n(e.parsedStatus);if(t==="blocked"||t==="error"||t==="failed")return 100;const s=e.event;return s==="auto_continue_started"?3:s==="next_up_manual_dispatch_started"?8:s==="autopilot_slice_dispatched"?14:s==="autopilot_slice_status_updates_buffered"?72:s==="autopilot_slice_result"?92:s==="autopilot_autofix_scheduled"?6:s==="autopilot_autofix_executed"?18:s==="autopilot_autofix_skipped"||s==="auto_continue_stopped"?100:s.startsWith("autopilot_slice")?56:null}function Fc(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function ag(e,t){if(!e&&t===null)return null;const s=e?ig(e):"neutral",i=c=>c>=100&&(s==="warning"||s==="critical"),r="Reached a terminal blocked state. Resolve blockers to continue.";if((e==null?void 0:e.progressPct)!==null&&(e==null?void 0:e.progressPct)!==void 0){const c=Fc(e.progressPct)??0,d=i(c);return{pct:c,source:"metadata",label:d?r:"Progress",tone:s,terminalStop:d}}if(t!==null){const c=i(t);return{pct:t,source:"session",label:c?r:"Progress",tone:s,terminalStop:c}}if(!e)return null;const a=rg(e);if(a===null)return null;const l=i(a);return{pct:a,source:"lifecycle",label:l?r:"Progress",tone:s,terminalStop:l}}function og(e,t,s,i=null){var w;const r=rt(e),a=$n(fe(r,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),l=$n(e.state??e.phase??e.kind??e.type),c=$n((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??l),d=$n((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=fe(r,["blocked_reason","blockedReason","error","message"])??(t==null?void 0:t.error)??e.description??null,p=Math.max(0,(s==null?void 0:s.decisions)??(t==null?void 0:t.decisions)??0),x=Math.max(0,(s==null?void 0:s.blockingDecisions)??(t==null?void 0:t.blockingDecisions)??(e.decisionRequired===!0?Math.max(1,p):0)),b=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,p-x)),h=e.decisionRequired===!0||e.type==="decision_requested"||x>0||c==="needs_decision"&&b===0,I=e.type==="run_completed"||e.type==="milestone_completed"||Yi(c)||d==="completed",y=a.includes("spawn_guard_rate_limited")||!!(u&&/rate limit/i.test(u)),j=a.includes("spawn_guard_blocked");if(a==="auto_continue_started")return{label:"Autopilot on",summary:Kt(e.title)??"Autopilot is active and will continue dispatching work from the Next Up queue.",hint:"Watch Activity and Next Up for newly dispatched slices.",tone:"positive"};if(a==="auto_continue_stopped"){if(d==="budget_exhausted")return{label:"Paused",summary:"Paused — budget reached",hint:"Restart with a larger token budget or a narrower workstream scope.",tone:"warning"};if(d==="completed"){const N=typeof(r==null?void 0:r.tasks_completed)=="number"?r.tasks_completed:null;return{label:"All done",summary:N?`All queued work complete — ${N} task${N===1?"":"s"} finished`:"All queued work complete",hint:null,tone:"positive"}}if(d==="stopped")return{label:"Stopped",summary:Kt(e.title)??"Autopilot was stopped by request.",hint:"Start again to resume continuous dispatch.",tone:"neutral"};if(d==="blocked")return{label:h?"Needs decision":"Blocked",summary:Kt(e.title)??(h?"Autopilot is paused pending a decision.":"Autopilot is blocked and needs intervention."),hint:h?"Open the Decisions panel and approve the pending item to continue.":"Resolve the blocker, then restart autopilot.",tone:h?"warning":"critical"};if(d==="error")return{label:"Error",summary:Kt(e.title)??u??"Autopilot stopped because of an error.",hint:"Open evidence and logs, then retry or pause the workstream.",tone:"critical"}}if(a==="autopilot_transition"){const N=String((r==null?void 0:r.new_state)??"");return N==="running"?{label:"Resumed",summary:"Resumed — dispatching work",hint:"Autopilot is actively working through the queue.",tone:"positive"}:N==="blocked"||N==="error"?{label:"Paused",summary:"Paused — waiting for input",hint:"Review blockers and resolve to continue.",tone:"critical"}:null}if(y)return{label:"Rate limited",summary:"Rate limit reached — will retry in ~2 minutes",hint:"Adjust limits in settings or wait for the window to reset.",tone:"warning"};if(j)return{label:"Waiting on system",summary:u?Kt(u)??"Waiting for system capacity.":"Waiting for system capacity.",hint:"Capacity will become available automatically, or adjust limits in settings.",tone:"critical"};if(i){if(i.status==="completed")return{label:b>0?"Completed + follow-up":"Completed",summary:b>0?`Execution completed. ${b} non-blocking decision${b===1?"":"s"} were logged for optional follow-up.`:i.sentence,hint:i.nextAction,tone:"positive"};if(i.status==="failed")return{label:"Failed",summary:u?Kt(u)??i.sentence:i.sentence,hint:i.nextAction,tone:"critical"};if(i.status==="needs_attention"){const N=h||(((w=i.nextAction)==null?void 0:w.toLowerCase().includes("decision"))??!1);return{label:N?"Needs decision":"Needs attention",summary:i.sentence,hint:i.nextAction??(N?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:N?"warning":"critical"}}if(i.status==="in_progress")return{label:"In progress",summary:i.sentence,hint:null,tone:"neutral"}}return e.type==="run_failed"||e.type==="blocker_created"||c==="blocked"||c==="failed"||c==="error"||d==="blocked"||d==="error"?{label:h?"Waiting on you":"Blocked",summary:u?Kt(u)??"Execution is blocked.":h?"Blocked waiting on decision from you":"Paused after top queue item blocked",hint:h?"Resolve the pending decision in the Decisions panel to continue.":"Review blocker details, then retry or skip to continue.",tone:"critical"}:h?{label:"Needs decision",summary:"Execution paused pending approval or a human choice.",hint:"Review the Decisions panel and approve the pending item to continue.",tone:"warning"}:I&&b>0?{label:"Completed + follow-up",summary:`Execution completed. ${b} non-blocking decision${b===1?"":"s"} were logged for optional follow-up.`,hint:"Review the decision for optimization, but no approval is required to mark this slice complete.",tone:"positive"}:e.type==="decision_resolved"?{label:"Decision resolved",summary:"A pending decision was completed.",hint:null,tone:"positive"}:I?{label:"Completed",summary:"Execution completed successfully.",hint:null,tone:"positive"}:e.type==="run_started"||l==="running"||l==="in_progress"?{label:"In progress",summary:"Execution is actively running.",hint:null,tone:"neutral"}:null}function Oc(e){if(typeof e=="string")return n.jsx(zi,{mode:"block",text:e,className:"text-body leading-relaxed text-primary"});if(typeof e=="number"||typeof e=="boolean")return n.jsx("p",{className:"text-body text-primary",children:String(e)});if(Array.isArray(e))return n.jsx("div",{className:"space-y-1.5",children:e.map((t,s)=>n.jsx("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:Oc(t)},`artifact-list-${s}`))});if(e&&typeof e=="object"){const t=dg(e);if(t)return t;const s=Object.entries(e);return n.jsx("dl",{className:"space-y-1.5",children:s.map(([i,r])=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("dt",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:st(i)}),n.jsx("dd",{className:"mt-1 text-body text-primary",children:typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`${r.length} item${r.length===1?"":"s"}`:r&&typeof r=="object"?`${Object.keys(r).length} field${Object.keys(r).length===1?"":"s"}`:"—"})]},i))})}return n.jsx("p",{className:"text-body text-secondary",children:"No artifact payload."})}function lg(e){if(!e)return null;const t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^file:\/\//i.test(t)||!Dc(t)?null:Pr(t):null}function cg(e){const t=tn(e);if(!t)return null;const s=tn(t.result),i=tn(t.outcomes),r=[s,i,t].filter(D=>!!D),a=D=>{for(const E of r)for(const de of D){if(!(de in E))continue;const ie=E[de];if(ie!=null)return ie}return null},l=D=>{for(const E of r){const de=fe(E,D);if(de)return de}return null},c=Kt(l(["summary","user_summary","description","message"])),d=[],u=new Set,p=D=>{if(!D)return;const E=D.trim();if(!E)return;const de=E.toLowerCase();u.has(de)||(u.add(de),d.push(E))},x=(D,E)=>{if(Array.isArray(D))for(const de of D){const ie=tn(de);if(!ie)continue;const we=fe(ie,[`${E.toLowerCase()}_id`,`${E.toLowerCase()}Id`,"id"]),ae=fe(ie,[`${E.toLowerCase()}_title`,`${E.toLowerCase()}Title`,"title","name"])??(we&&!Wn(we)?we:null),ze=fe(ie,["status","state"]),pe=Kt(fe(ie,["reason","summary","description","note"])),le=ae?ks(ae,we)??st(ae):E,te=ze?st(ze):null,ne=[le];te&&ne.push(`→ ${te}`),pe&&ne.push(`· ${pe}`),p(ne.join(" "))}};for(const D of r)x(D.task_updates??D.taskUpdates,"Task"),x(D.milestone_updates??D.milestoneUpdates,"Milestone");const b=kn(a(["status_updates_applied","statusUpdatesApplied"]));b!==null&&b>0&&p(`${b} status update${b===1?"":"s"} applied`);const h=a(["status_updates_buffered","statusUpdatesBuffered"]),I=kn(h);(h===!0||I!==null&&I>0)&&p("Status updates buffered for sync");const j=[],w=new Set,N=D=>{const E=Kt(D);if(!E)return;const de=E.toLowerCase();w.has(de)||(w.add(de),j.push(E))};N(l(["next_step","nextStep"]));for(const D of r){const E=D.next_actions??D.nextActions;if(Array.isArray(E))for(const de of E)typeof de=="string"&&N(de)}const f=[],T=new Set,X=(D,E,de)=>{const ie=`${D.toLowerCase()}|${(E??"").toLowerCase()}|${de??""}`;T.has(ie)||(T.add(ie),f.push({title:D,type:E,url:de}))},Z=D=>{const E=Array.isArray(D)?D:D?[D]:[];for(const de of E){const ie=tn(de);if(!ie){if(typeof de=="string"&&de.trim().length>0){const pe=Kt(de)??st(de);pe&&X(pe,null,null)}continue}const we=fe(ie,["artifact_type","artifactType","type"]),ae=fe(ie,["url","source_pointer","sourcePointer","path"]),ze=fe(ie,["name","title","artifact_title","artifactTitle"])??(ae?Un(ae):Hr(we));X(st(ze),we,ae)}};for(const D of r)Z(D.artifacts??D.artifact);const W=l(["artifact_type","artifactType"]),ke=l(["url","artifact_url","artifactUrl"]);if(f.length===0&&(W||ke)){const D=ke?Un(ke):Hr(W);X(st(D),W,ke)}return!c&&d.length===0&&f.length===0&&j.length===0?null:{summary:c,updatesApplied:d,artifactsCreated:f,nextUp:j}}function dg(e){const t=cg(e);return t?n.jsxs("div",{className:"space-y-3",children:[t.summary&&n.jsxs("section",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-cyan-100/75",children:"What Changed"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-primary",children:t.summary})]}),t.updatesApplied.length>0&&n.jsxs("section",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-cyan-100/75",children:"Updates Applied"}),n.jsx("ul",{className:"mt-1.5 space-y-1.5",children:t.updatesApplied.slice(0,6).map(s=>n.jsxs("li",{className:"flex items-start gap-2 text-caption text-primary",children:[n.jsx("span",{className:"mt-1 h-1.5 w-1.5 rounded-full bg-cyan-300/70"}),n.jsx("span",{className:"leading-relaxed",children:s})]},s))})]}),t.artifactsCreated.length>0&&n.jsxs("section",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-cyan-100/75",children:"Artifacts Created"}),n.jsx("div",{className:"mt-1.5 space-y-1.5",children:t.artifactsCreated.slice(0,5).map(s=>{const i=lg(s.url);return n.jsxs("div",{className:"rounded-md border border-white/[0.07] bg-black/20 px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"text-caption font-medium leading-relaxed text-primary",children:s.title}),s.type&&n.jsx("span",{className:"rounded-full border border-cyan-300/30 bg-cyan-300/[0.10] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.06em] text-cyan-100/80",children:Hr(s.type)})]}),s.url&&(i?n.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"mt-1 inline-flex items-center gap-1 text-caption text-cyan-200/85 transition-colors hover:text-cyan-100",children:n.jsx("span",{className:"truncate",children:Un(s.url)})}):n.jsx("p",{className:"mt-1 truncate text-micro text-secondary",children:Un(s.url)}))]},`${s.title}|${s.url??""}`)})})]}),t.nextUp.length>0&&n.jsxs("section",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-2.5",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-cyan-100/75",children:"Next Up"}),n.jsx("ul",{className:"mt-1.5 space-y-1.5",children:t.nextUp.slice(0,4).map(s=>n.jsxs("li",{className:"flex items-start gap-2 text-caption text-primary",children:[n.jsx("span",{className:"mt-1 h-1.5 w-1.5 rounded-full bg-cyan-300/70"}),n.jsx("span",{className:"leading-relaxed",children:s})]},s))})]})]}):null}function Kt(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=Hi(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:st(t)}const ug=[/^User:\s*System:/i,/Exec failed/i,/SIGKILL/i,/SIGTERM/i,/stack trace/i,/Traceback \(most recent/i,/^\s*\{[\s"]/,/Error: /,/execution policy/i,/outbox replay/i,/changeset replayed/i];function mg(e){return ug.some(t=>t.test(e))}function qc(e){const t=rt(e);if(!t)return null;const s=fe(t,["user_summary","userSummary"]);if(s)return s;const i=fe(t,["task_title","taskTitle","dispatch_task_title"])??fe(t,["workstream_title","workstreamTitle","dispatch_workstream_title"]),r=fe(t,["event","event_name","eventName"]),a=fe(t,["parsed_status","status"]),l=fe(t,["stop_reason","stopReason"]),c=fe(t,["artifact_type","artifactType"]),d=fe(t,["artifact_title","title","name"]),u=fe(t,["agent_name","agentName","requested_by_agent_name"]);switch(r){case"autopilot_slice_dispatched":case"autopilot_slice_started":return`Working on ${i??"queued task"}`;case"autopilot_slice_status_updates_buffered":{const p=Yr(t);return p.length>0?`Applying ${p.length} status update${p.length===1?"":"s"}`:"Applying status updates"}case"autopilot_slice_result":case"autopilot_slice_finished":return a==="completed"||a==="success"?i?`Finished ${i}`:"Task completed":a==="blocked"||a==="needs_decision"?i?`Needs help with ${i}`:"Needs your input":i?`Worked on ${i}`:null;case"auto_continue_started":return"Autopilot started";case"auto_continue_stopped":return l==="budget_exhausted"?"Paused — budget reached":l==="completed"?"All queued work complete":l==="blocked"?"Paused — needs your input":l==="error"?"Paused — hit an error":"Autopilot paused";case"autopilot_transition":return null;case"autopilot_item_skipped":return`Skipped ${i??"blocked item"}, continuing`}if(e.type==="run_started")return i?`Started ${i}`:null;if(e.type==="run_completed")return i?`Completed ${i}`:null;if(e.type==="run_failed")return i?`Hit an issue with ${i}`:null;if(e.type==="artifact_created"){const p=c?st(c):"artifact";return d?`Created ${p}: ${d}`:`Created ${p}`}if(e.type==="artifact_updated")return d?`Updated ${d}`:"Updated artifact";if(e.type==="delegation"&&u&&i)return`${u} is handling ${i}`;if(r==="decision_needed"){const p=fe(t,["decision_title","decisionTitle","title"]);return p?`Decision needed: ${p}`:"Decision needed"}if(r==="decision_resolved"){const p=fe(t,["decision_title","decisionTitle","title"]);return p?`Decision resolved: ${p}`:"Decision resolved"}return r==="spawn_guard_blocked"||r==="spawn_guard_rate_limited"?"Waiting for capacity":null}function pg(e,t,s,i){const r=new Set(["header"]);return t&&r.add("artifact"),s&&r.add("outcome"),(e.includes("slice_result")||e.includes("slice_finished")||e.includes("run_completed"))&&(r.add("summary"),r.add("evidence"),r.add("structured_outcomes")),(i||e.includes("status_updates"))&&r.add("structured_outcomes"),(e.includes("blocked")||e.includes("needs_attention")||e.includes("needs_decision")||e.includes("failed"))&&r.add("action_needed"),(e.includes("autopilot")||e.includes("auto_continue"))&&(r.add("session"),r.add("scope")),e.includes("decision")&&r.add("action_needed"),e.includes("artifact")&&(r.add("artifact"),r.add("evidence")),r}function Xi(e){const t=qc(e);if(t)return{title:t,isSystem:!1};const s=e.title??"";if(!mg(s)){const i=Gh(st(Pc(s)));if(i&&i!=="Untitled session")return{title:i,isSystem:!1};const r=e.metadata,a=fd(r);return a!=="Activity event"?{title:a,isSystem:!1}:{title:st(Ui(e.type)),isSystem:!1}}return/Exec failed|SIGKILL|SIGTERM|Error: /i.test(s)?{title:"Execution failed",isSystem:!0}:/outbox replay|changeset replayed/i.test(s)?{title:"Changes synced",isSystem:!0}:/execution policy/i.test(s)?{title:"System directive",isSystem:!0}:{title:"System event",isSystem:!0}}const fg=new Set(["autopilot_transition","heartbeat","orchestrator_selection","orchestrator_dispatch","spawn_guard_blocked","spawn_guard_rate_limited","delegation_flow_started","delegation_flow_completed"]),hg=new Set(["changeset_replayed","changeset_applied","changeset.replayed","changeset.applied","outbox_replay_applied","outbox_replayed","sync_applied","sync.applied","sentinel_changeset_applied","sentinel_decision_applied","sentinel.changeset.applied","sentinel.decision.applied"]);function Wi(e){const t=rt(e);if(!t)return!1;const s=(typeof t.event=="string"&&t.event.trim().length>0?t.event.trim().toLowerCase():null)??(typeof t.event_name=="string"&&t.event_name.trim().length>0?t.event_name.trim().toLowerCase():null)??(typeof t.eventName=="string"&&t.eventName.trim().length>0?t.eventName.trim().toLowerCase():null),i=(typeof t.source_client=="string"?t.source_client:null)??(typeof t.sourceClient=="string"?t.sourceClient:null),r=(i==null?void 0:i.toLowerCase())??"",a=(typeof e.kind=="string"&&e.kind.trim().length>0?e.kind.trim().toLowerCase():null)??(typeof t.kind=="string"&&t.kind.trim().length>0?t.kind.trim().toLowerCase():null)??(typeof t.event_kind=="string"&&t.event_kind.trim().length>0?t.event_kind.trim().toLowerCase():null)??(typeof t.eventKind=="string"&&t.eventKind.trim().length>0?t.eventKind.trim().toLowerCase():null)??"",l=/(changeset[\._ ]?(applied|replayed)|sync[\._ ]?applied|sentinel[\._ ]?(changeset|decision)[\._ ]?applied)/i.test(a),c=t.replayed===!0,d=typeof t.changeset_id=="string"&&t.changeset_id.trim().length>0||typeof t.changesetId=="string"&&t.changesetId.trim().length>0,u=/changes synced|changeset replayed|changeset applied|outbox replay/i.test(`${e.title??""} ${e.summary??""} ${e.description??""}`);return!!(s&&hg.has(s)||l||c&&(d||u)||d&&(u||r.includes("outbox")||r.includes("replay"))||r.includes("outbox_replay")&&u)}function Rl(e){var d;if(!e||!Wi(e))return null;const t=rt(e),s=kn((t==null?void 0:t.applied_count)??(t==null?void 0:t.appliedCount)??(t==null?void 0:t.applied)??null),i=(typeof(t==null?void 0:t.idempotency_key)=="string"?t.idempotency_key:null)??(typeof(t==null?void 0:t.idempotencyKey)=="string"?t.idempotencyKey:null),r=((d=i==null?void 0:i.match(/sentinel:([a-z_]+):/i))==null?void 0:d[1])??null,a=fe(t,["entity_type","entityType"])??r??(e.type==="milestone_completed"?"milestone":null),l=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",c=a?` for ${st(a).toLowerCase()}`:"";return`${l}${c} were synced from local replay.`}function _a(e){if(!Wi(e))return null;const t=rt(e);if(!t)return null;const s=fe(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const i=fe(t,["event","event_name","eventName"])??"",r=fe(t,["changeset_id","changesetId"])??"",a=fe(t,["entity_type","entityType"])??"",l=fe(t,["entity_id","entityId"])??"",c=ui(e)??"",d=Xi(e).title.trim().toLowerCase();return`fallback:${i.toLowerCase()}:${r.toLowerCase()}:${a.toLowerCase()}:${l.toLowerCase()}:${c.toLowerCase()}:${d}`}function gg(e){if(!e)return null;const t=rt(e);if(!t||typeof t!="object")return null;const s=typeof t.source=="string"?t.source.trim():"",i=typeof t.turnId=="string"?t.turnId.trim():"";if(s!=="local_openclaw"||!i)return null;const r=typeof t.sessionKey=="string"&&t.sessionKey.trim().length>0?t.sessionKey.trim():null;return{turnId:i,sessionKey:r,runId:e.runId??null}}function Ll(e){return e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/_([^_\n]+)_/g,"$1")}const xg=[/^Autopilot dispatched slice for\s*/i,/^Orchestrator (selected|dispatched)\s*/i,/^Auto[-_]?continue.*?dispatching\s*/i,/^Slice (started|dispatched) for\s*/i];function Dl(e,t){const s=qc(e);if(s)return s;let r=(Kt(t??e.summary)??Kt(e.description)??st(e.title||Ui(e.type))).replace(/\r\n/g,`
210
+ `).replace(/```[\s\S]*?```/g," ").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s*[-*]\s+/gm,"").replace(/\s+/g," ").trim();for(const c of xg)r=r.replace(c,"");r=r.trim();const a=r.split(`
211
+ `).map(c=>Ll(c).trim()).filter(c=>c.length>0&&!/^\|?[:\-| ]+\|?$/.test(c));let l=a[0]??Ll(r);return l.length<24&&a.length>1&&(l=`${l} ${a[1]}`.trim()),l.length>108?`${l.slice(0,107).trimEnd()}…`:l}const yg=o.memo(function({activity:t,sessions:s,sliceRuns:i=[],initiatives:r=[],timelineNarrative:a=[],selectedRunIds:l,selectedSessionLabel:c=null,selectedWorkstreamId:d=null,selectedWorkstreamLabel:u=null,agentFilter:p=null,timeFilterId:x="live",onTimeFilterChange:b,customTimeRange:h={startIso:null,endIso:null},onCustomTimeRangeChange:I,hasMore:y=!1,isLoadingMore:j=!1,onLoadMore:w,onClearSelection:N,onClearWorkstreamFilter:f,onClearAgentFilter:T,onFocusRunId:X,onOpenDecision:Z,onResolveDecision:W,requestedActivityItemId:ke=null,onActivityItemRequestHandled:D,onPlayNextUp:E,onStartAutopilot:de,onPauseWorkstream:ie,onCreateInitiative:we,onOpenMissionControl:ae,onOpenSettings:ze,workspaceId:pe=null,chatSnapshot:le,onRefreshData:te,isLoading:ne=!1,onOpenNextUp:Ce,devMode:G=!1,nextUpQueue:R,autopilotState:z=null}){var ro;const B=ps(),{open:K}=bc(),re=o.useMemo(()=>{if(!R)return new Map;const m=new Map;for(let v=0;v<R.length;v++){const k=R[v];m.set(k.workstreamId,{rank:v+1,title:k.workstreamTitle,state:k.queueState})}return m},[R]),[ge,Se]=o.useState("all"),[oe,ye]=o.useState(!1),[me,O]=o.useState(""),[U,Y]=o.useState(new Set),[ce,qe]=o.useState({}),[We,Fe]=o.useState("oldest"),[L,ct]=o.useState(!1),[Me,Qe]=o.useState(!1),[St,zt]=o.useState(ka),[Mt,q]=o.useState(null),[_e,be]=o.useState(null),[Le,tt]=o.useState(!1),[at,J]=o.useState(1),[Ue,je]=o.useState("structured"),[Q,Ee]=o.useState(null),[nt,Te]=o.useState("feed"),[lt,ht]=o.useState(null),[Rt,Ft]=o.useState(null),[H,Ae]=o.useState(!1),[Ve,Je]=o.useState(null),[He,Ge]=o.useState(null),[Ke,gt]=o.useState(0),[Lt,bt]=o.useState(!1),[Ct,Et]=o.useState(null),[Vt,Qt]=o.useState(!1),ot=o.useRef(Date.now()),dt=o.useRef(null),rn=o.useRef(null),an=o.useRef(null),ln=o.useRef(null),Dt=o.useRef(null),[Ot,Hn]=o.useState(()=>wr(h.startIso)),[Gt,Pn]=o.useState(()=>wr(h.endIso)),[fs,Qs]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),Ss=o.useMemo(()=>Jl(x),[x]),Kn=o.useMemo(()=>wr(h.startIso),[h.startIso]),fn=o.useMemo(()=>wr(h.endIso),[h.endIso]),on=o.useMemo(()=>!Ot||!Gt?!1:Gt.getTime()>=Ot.getTime(),[Gt,Ot]),mn=o.useMemo(()=>x!=="custom"?Ss.label:Kn&&fn?`${kr(Kn)} - ${kr(fn)}`:"Custom range",[fn,Kn,x,Ss.label]);o.useEffect(()=>{Hn(Kn),Pn(fn)},[fn,Kn]),o.useEffect(()=>{if(typeof window>"u")return;const m=()=>Qs(window.innerWidth<=640);return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]),o.useEffect(()=>{const v=()=>{ot.current=Date.now()};window.addEventListener("pointerdown",v),window.addEventListener("keydown",v);const k=setInterval(()=>{Date.now()-ot.current>3e5&&Qt(!0)},3e4);return()=>{window.removeEventListener("pointerdown",v),window.removeEventListener("keydown",v),clearInterval(k)}},[]);const bn=o.useMemo(()=>{const m=s.filter(S=>S.status==="completed").length,v=s.filter(S=>S.status==="blocked"||S.status==="failed").length,k=t.filter(S=>{var ee;return S.type==="decision_requested"&&((ee=S.metadata)==null?void 0:ee.status)==="pending"}).length;return{completed:m,blocked:v,decisions:k}},[s,t]),Zn=o.useMemo(()=>{const m=new Map;for(const v of s)m.set(v.runId,v.title),m.set(v.id,v.title);return m},[s]),Cs=o.useMemo(()=>{const m=new Map;for(const v of s)v.status&&(m.set(v.runId,v.status),m.set(v.id,v.status));return m},[s]),es=o.useRef(new Map),Ts=o.useMemo(()=>{var v;const m=new Map;for(const k of s){const S={status:k.status??null,phase:k.phase??null,state:k.state??null,blockerCount:Array.isArray(k.blockers)?k.blockers.length:0,blockerReason:k.blockerReason??((v=k.blockerDiagnostics)==null?void 0:v.reason)??null};m.set(k.runId,S),m.set(k.id,S)}return Il(es.current,m)?es.current:(es.current=m,m)},[s]),hs=o.useRef(new Map),hn=o.useMemo(()=>{const m=new Map;for(const v of i){const k={status:v.status??null,blockingDecisions:Math.max(0,v.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(v.decisionCount??0)-(v.blockingDecisionCount??0)),updatedEpoch:ms(v.updatedAt??v.lastEventAt??v.startedAt??null)},S=[v.runId,v.sliceRunId].filter(ee=>typeof ee=="string"&&ee.trim().length>0).map(ee=>ee.trim());for(const ee of S){const $e=m.get(ee);(!$e||k.updatedEpoch>=$e.updatedEpoch)&&m.set(ee,k)}}return Il(hs.current,m)?hs.current:(hs.current=m,m)},[i]),Ys=o.useMemo(()=>{const m=new Map;for(const v of i){const k={startedAt:v.startedAt??null,completedAt:v.completedAt??null},S=[v.runId,v.sliceRunId].filter(ee=>typeof ee=="string"&&ee.trim().length>0);for(const ee of S)m.set(ee,k)}return m},[i]),$=o.useMemo(()=>{const m=new Map;for(const v of s){const k=Fc(v.progress);k!==null&&(m.set(v.runId,k),m.set(v.id,k))}return m},[s]),xe=o.useMemo(()=>{const m=new Map;for(const v of s)!v.agentId||!v.agentName||m.set(v.agentId,v.agentName);return m},[s]),ve=o.useMemo(()=>{const m=new Map;for(const v of s){const k=v.workstreamId??null;m.set(v.runId,k),m.set(v.id,k)}return m},[s]),De=o.useMemo(()=>{const m=new Map;for(const v of i){const k=v.workstreamId??null,S=ks(v.workstreamTitle,k);if(!S)continue;const ee=[v.runId,v.sliceRunId].filter($e=>typeof $e=="string"&&$e.trim().length>0).map($e=>$e.trim());for(const $e of ee)m.set($e,S)}return m},[i]),Nt=o.useMemo(()=>{const m=new Map;for(const v of r){const k=ks(v.name,v.id);k&&m.set(v.id,k)}return m},[r]),xt=o.useMemo(()=>{const m=new Map;for(const v of r)for(const k of v.workstreams??[]){const S=ks(k.name,k.id);S&&m.set(k.id,S)}for(const v of i){const k=v.workstreamId??null;if(!k||m.has(k))continue;const S=ks(v.workstreamTitle,k);S&&m.set(k,S)}return m},[r,i]);o.useMemo(()=>{const m=[...s];return m.sort((v,k)=>{const S=ms(v.updatedAt??v.lastEventAt??v.startedAt??null);return ms(k.updatedAt??k.lastEventAt??k.startedAt??null)-S}),m},[s]);const pt=o.useMemo(()=>t.map(m=>{const v=ui(m),k=Dh(m),S=rt(m),ee=v?Ts.get(v)??null:null,$e=v?hn.get(v)??null:null,Pe=$h(m,S),ft=Ef({sessionStatus:Pe?null:(ee==null?void 0:ee.status)??(v?Cs.get(v)??null:null),sessionPhase:Pe?null:(ee==null?void 0:ee.phase)??null,sessionState:Pe?null:(ee==null?void 0:ee.state)??null,sliceStatus:Pe?null:($e==null?void 0:$e.status)??null,activityType:m.type,activityStatus:fe(S,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:fe(S,["stop_reason","stopReason"]),decisionRequired:m.decisionRequired??!1,blockingDecisionCount:Hs(S,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??($e==null?void 0:$e.blockingDecisions)??0,nonBlockingDecisionCount:Hs(S,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??($e==null?void 0:$e.nonBlockingDecisions)??0,blockerCount:Pe?0:(ee==null?void 0:ee.blockerCount)??0,blockerReason:Pe?null:(ee==null?void 0:ee.blockerReason)??null}),yt=Oh(k,ft),wt=[m.title,m.description,m.summary,m.agentName,Ih(S)].filter(Xe=>typeof Xe=="string"&&Xe.length>0).join(" ").toLowerCase(),Be=v?(Zn.get(v)??v).toLowerCase():"",et=S==null?void 0:S.scope,At=et==="milestone"||et==="workstream"?et:void 0;return{item:m,bucket:k,userState:yt.state,userStateWhy:yt.why,canonicalProjection:ft,runId:v,timestampEpoch:ms(m.timestamp),searchText:wt,runLabelSearch:Be,scopeGroupId:At?v??null:null,scope:At}}),[t,Zn,Ts,Cs,hn]),In=o.useMemo(()=>{const m=[...pt];return m.sort((v,k)=>{const S=k.timestampEpoch-v.timestampEpoch;return S!==0?S:k.item.id.localeCompare(v.item.id)}),m},[pt]),ts=o.useMemo(()=>[...In].reverse(),[In]),ns=o.useMemo(()=>{let m=0;for(const v of pt)m=Math.max(m,v.timestampEpoch);return m<=0?!1:Date.now()-m<6e4},[pt]),cn=o.useMemo(()=>new Set(l.filter(m=>m&&m.trim().length>0)),[l]),Yt=cn.size>0,ss=o.useMemo(()=>Ki.filter(m=>["live","24h","7d","all"].includes(m.id)),[]),$t=o.useMemo(()=>{if(!Yt)return null;for(const m of cn){const v=s.find(k=>k.runId===m||k.id===m);if(v)return v}return null},[Yt,cn,s]),Ms=o.useMemo(()=>Yt?$t!=null&&$t.runtimeProvider?{id:kh($t.runtimeProvider)}:js($t==null?void 0:$t.agentId,$t==null?void 0:$t.agentName,$t==null?void 0:$t.title,$t==null?void 0:$t.lastEventSummary,$t==null?void 0:$t.runtimeClient,c):js(),[$t,Yt,c]),Es=o.useMemo(()=>p?js(p):js(),[p]),{filtered:jt,filteredTotal:vn,hiddenCount:Fn,hiddenSyncCount:Ji}=o.useMemo(()=>{const m=We==="newest"?In:ts,v=[];let k=0,S=0,ee=0;const $e=new Set,Pe=me.trim().toLowerCase();for(const Be of m){const et=Be.runId;if(Yt&&(!et||!cn.has(et)))continue;if(d){const qt=mi(Be.item),Wt=et?ve.get(et)??null:null;if((qt??Wt)!==d)continue}const At=fi(Be.item);if(p&&At.agentName!==p){ee++;continue}if(!G){const qt=rt(Be.item),Wt=fe(qt,["event","event_name","eventName"]);if(Wt&&fg.has(Wt))continue}const Xe=_a(Be.item);if(Xe){if($e.has(Xe)){S+=1;continue}if($e.add(Xe),!oe){S+=1;continue}}else if(!oe&&Wi(Be.item)){S+=1;continue}ge==="completed"&&Be.userState!=="completed"||ge==="needs_attention"&&Be.userState!=="needs_input"&&Be.userState!=="issue"||ge==="in_progress"&&Be.userState!=="in_progress"||Pe.length>0&&!`${Be.searchText} ${Be.runLabelSearch}`.includes(Pe)||(v.length<vl?v.push(Be):k+=1)}const ft=Math.min(Math.max(1,Math.min(bl,St)),v.length),yt=v.slice(0,ft),wt=v.length+k;return{filtered:yt,filteredTotal:wt,hiddenCount:Math.max(0,wt-yt.length),hiddenSyncCount:S,skippedByAgent:ee}},[ge,p,In,ts,Yt,me,St,d,cn,ve,oe,We]),Ut=o.useMemo(()=>{if(!p)return null;let m=0;for(const v of t)if(fi(v).agentName===p){const S=ms(v.timestamp);S>m&&(m=S)}return m===0?null:Pt(m)},[p,t]),is=o.useMemo(()=>{const m=new Map;for(const k of jt){const S=Ph(k.item.timestamp),ee=m.get(S);ee?ee.push(k):m.set(S,[k])}return Array.from(m.keys()).sort((k,S)=>{const ee=Number(S)-Number(k);return We==="newest"?ee:-ee}).map(k=>({key:k,label:Fh(k),items:m.get(k)??[]}))},[jt,We]),yi=o.useMemo(()=>is.map(m=>{const v=new Map;for(const k of m.items){const S=Xi(k.item).title.trim().toLowerCase(),ee=_a(k.item),$e=rt(k.item),Pe=fe($e,["event","event_name","eventName"]),ft=(Pe==null?void 0:Pe.startsWith("autopilot_"))||(Pe==null?void 0:Pe.startsWith("auto_continue_")),yt=Pe==="auto_continue_stopped"||Pe==="autopilot_transition"||Pe==="auto_continue_completed",wt=mi(k.item),Be=ee?`${k.item.type}::sync::${ee}`:ft&&wt?`autopilot::${wt}::${yt?"stop":Math.floor(k.timestampEpoch/3e5)}`:`${k.item.type}::${S}`,et=v.get(Be);et?(et.count+=1,et.firstTimestamp=Math.min(et.firstTimestamp,k.timestampEpoch),et.allItems.push(k),k.timestampEpoch>et.representative.timestampEpoch&&(et.representative=k)):v.set(Be,{key:Be,representative:k,count:1,firstTimestamp:k.timestampEpoch,allItems:[k]})}return{...m,clusters:Array.from(v.values())}}),[is]),bi=o.useCallback(m=>{Y(v=>{const k=new Set(v);return k.has(m)?k.delete(m):k.add(m),k}),qe(v=>{if(Object.prototype.hasOwnProperty.call(v,m)){const k={...v};return delete k[m],k}return{...v,[m]:Fi}})},[]),gs=o.useCallback((m,v)=>{qe(k=>{const S=k[m]??Fi,ee=Math.min(v,S+Fi);return ee===S?k:{...k,[m]:ee}})},[]),Jr=o.useCallback(()=>{!I||!b||!Ot||!Gt||Gt.getTime()<Ot.getTime()||(I({startIso:Ot.toISOString(),endIso:Gt.toISOString()}),b("custom"),Qe(!1))},[Gt,Ot,I,b]),Js=o.useCallback(()=>{Hn(null),Pn(null),I==null||I({startIso:null,endIso:null}),x==="custom"&&(b==null||b("live"))},[I,b,x]),dn=o.useMemo(()=>Math.min(bl,Math.min(vl,vn)),[vn]);o.useEffect(()=>{zt(ka),Y(new Set),qe({})},[ge,p,Yt,me,d,oe,We,x]),o.useEffect(()=>{if(!L)return;const m=k=>{var ee;const S=k.target;S instanceof Node&&((ee=dt.current)!=null&&ee.contains(S)||ct(!1))},v=k=>{k.key==="Escape"&&ct(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",v),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",v)}},[L]),o.useEffect(()=>{if(!Me)return;const m=k=>{var ee;const S=k.target;S instanceof Node&&((ee=rn.current)!=null&&ee.contains(S)||Qe(!1))},v=k=>{k.key==="Escape"&&Qe(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",v),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",v)}},[Me]);const Tn=o.useRef(w);Tn.current=w;const rs=o.useRef(y);rs.current=y;const Rs=o.useRef(j);Rs.current=j;const[Mn,xs]=o.useState(!1),as=o.useRef(null),vi=o.useRef(x),Zi=o.useRef(Date.now()),wi=o.useRef(!1);o.useEffect(()=>{vi.current!==x&&(vi.current=x,as.current=null,Zi.current=Date.now(),wi.current=!1)},[x]),o.useEffect(()=>{const m=an.current,v=ln.current;if(!m||!v)return;const k=new IntersectionObserver(ee=>{const $e=ee.some(Pe=>Pe.isIntersecting);xs($e)},{root:m,rootMargin:"0px 0px 600px 0px"});k.observe(v);const S=()=>{wi.current=!0};return m.addEventListener("scroll",S,{passive:!0}),()=>{k.disconnect(),m.removeEventListener("scroll",S)}},[]),o.useEffect(()=>{var m;if(Mn){if(jt.length<dn){zt(v=>Math.min(dn,Math.max(v,ka)+wh));return}if(rs.current&&!Rs.current){(m=Tn.current)==null||m.call(Tn);return}}},[jt.length,dn,Mn]),o.useEffect(()=>{if(!Mn||y||j||!b)return;const m=an.current,v=m?m.scrollHeight<=m.clientHeight+4:!1;if(!wi.current&&!v||Date.now()-Zi.current<3e3)return;const S=kl(x);S&&as.current!==S&&(as.current=S,b(S))},[jt.length,y,j,b,Mn,x]);const Vn=o.useMemo(()=>Mt?jt.findIndex(m=>m.item.id===Mt):-1,[Mt,jt]),C=Vn>=0?jt[Vn]:null,ys=o.useMemo(()=>{if(!C)return!1;const m=rt(C.item),v=fe(m,["parsed_status","status"]);return!!v&&v!=="completed"&&v!=="success"},[C]);o.useEffect(()=>{if(!ys)return;const m=setInterval(()=>gt(v=>v+1),1e3);return()=>clearInterval(m)},[ys]),o.useEffect(()=>{gt(0)},[C==null?void 0:C.item.id]);const er=o.useMemo(()=>{var v;const m=new Map;for(const k of a){const S=(v=k==null?void 0:k.sliceRunId)==null?void 0:v.trim();!S||m.has(S)||m.set(S,k)}return m},[a]),os=o.useMemo(()=>{if(!C)return null;const m=C.runId??ui(C.item);return m?er.get(m)??null:null},[C,er]),En=o.useMemo(()=>Lc((C==null?void 0:C.item)??null),[C]),Zs=o.useMemo(()=>Ir((C==null?void 0:C.item)??null),[C]),On=o.useMemo(()=>Rc((C==null?void 0:C.item)??null),[C]),Gn=o.useMemo(()=>On?null:sg((C==null?void 0:C.item)??null,t),[On,C,t]),it=o.useMemo(()=>C?Sl(C.item):null,[C]),Nn=o.useMemo(()=>it?it.executor??it.requester:null,[it]),se=On??(Gn==null?void 0:Gn.detail)??null,Ls=o.useMemo(()=>{var m,v;return Aa((se==null?void 0:se.requesterAgentName)??((m=it==null?void 0:it.requester)==null?void 0:m.name)??null,(se==null?void 0:se.requesterAgentId)??((v=it==null?void 0:it.requester)==null?void 0:v.id)??null,xe)},[se,it,xe]),ls=o.useMemo(()=>_h(Ls),[Ls]),Xn=o.useMemo(()=>{var v,k;const m=Aa((se==null?void 0:se.agentName)??((v=it==null?void 0:it.executor)==null?void 0:v.name)??null,(se==null?void 0:se.agentId)??((k=it==null?void 0:it.executor)==null?void 0:k.id)??null,xe);return m==="—"?(it==null?void 0:it.primaryLabel)??"Codex":m},[se,it,xe]),tr=o.useMemo(()=>C!=null&&C.runId?$.get(C.runId)??null:null,[C,$]),kt=o.useMemo(()=>ag(se,tr),[se,tr]),P=o.useMemo(()=>{const m=se;if(!m)return null;const v=m.initiativeId??(C==null?void 0:C.item.initiativeId)??null,k=v?r.find(Xe=>Xe.id===v)??null:null,S=m.initiativeTitle??(k==null?void 0:k.name)??null,ee=m.initiativeStatus??(k==null?void 0:k.status)??null,$e=(k==null?void 0:k.workstreams)??[],Pe=$e.length>0?$e.length:null,ft=Pe!==null?$e.filter(Xe=>Yi(Xe.status)).length:null,yt=Pe&&ft!==null?Math.round(ft/Pe*100):null,wt=m.workstreamId??null,Be=wt&&$e.length>0?$e.find(Xe=>Xe.id===wt)??null:null,et=m.workstreamTitle??(Be==null?void 0:Be.name)??(wt?xt.get(wt)??null:null),At=m.workstreamStatus??(Be==null?void 0:Be.status)??null;return{initiativeId:v,initiativeTitle:S,initiativeStatus:ee,totalInitiativeWorkstreams:Pe,doneInitiativeWorkstreams:ft,initiativeWorkstreamPct:yt,workstreamId:wt,workstreamTitle:et,workstreamStatus:At,taskTitle:m.taskTitle,milestoneTitle:m.milestoneTitle,scopedTaskCount:m.taskIds.length,scopedMilestoneCount:m.milestoneIds.length,statusUpdatesApplied:m.statusUpdatesApplied,statusUpdatesBuffered:m.statusUpdatesBuffered,artifacts:m.artifacts,decisions:m.decisions,blockingDecisions:m.blockingDecisions,nonBlockingDecisions:m.nonBlockingDecisions,tokensUsed:m.tokensUsed,tokenBudget:m.tokenBudget,nextStep:m.nextStep,phase:m.phase,stopReason:m.stopReason,parsedStatus:m.parsedStatus}},[se,C,r,xt]),Tt=o.useMemo(()=>C?og(C.item,se,P?{decisions:P.decisions,blockingDecisions:P.blockingDecisions,nonBlockingDecisions:P.nonBlockingDecisions,stopReason:P.stopReason,parsedStatus:P.parsedStatus}:null,C.canonicalProjection??null):null,[se,C,P]),qn=o.useMemo(()=>{if(!C)return new Set;if(G)return new Set(["header","artifact","outcome","structured_outcomes","action_needed","session","scope","summary","evidence"]);const m=fe(rt(C.item),["event","event_name","eventName"])??"";return pg(m,!!En||!!Ir(C.item),!!Tt,Hh(C.item))},[C,En,Tt,G]),nr=o.useMemo(()=>{if(!P)return[];const m=[];Tt&&m.push({label:"Status",value:Tt.label}),P.scopedTaskCount>0&&m.push({label:"Tasks",value:P.scopedTaskCount}),P.scopedMilestoneCount>0&&m.push({label:"Milestones",value:P.scopedMilestoneCount});const v=P.artifacts??0;v>0&&m.push({label:"Artifacts",value:v});const k=P.decisions??0;k>0&&m.push({label:"Decisions",value:k}),P.blockingDecisions&&P.blockingDecisions>0&&m.push({label:"Blocking",value:P.blockingDecisions,tone:"critical"}),P.stopReason&&m.push({label:"Stop reason",value:Si(P.stopReason)??st(P.stopReason)});const S=pd(P.tokensUsed,P.tokenBudget);return S&&m.push({label:"Token usage",value:S}),m},[P,Tt]),cs=o.useMemo(()=>{const m=new Set;for(const v of tg((C==null?void 0:C.item)??null))m.add(v);for(const v of(se==null?void 0:se.decisionIds)??[])m.add(v);for(const v of(se==null?void 0:se.blockingDecisionIds)??[])m.add(v);for(const v of(se==null?void 0:se.nonBlockingDecisionIds)??[])m.add(v);return Array.from(m)},[se,C]),sr=o.useMemo(()=>Z?cs.length>0||(C==null?void 0:C.item.decisionRequired)===!0||((P==null?void 0:P.blockingDecisions)??0)>0?!0:(Tt==null?void 0:Tt.label)==="Needs decision":!1,[cs,C,P,Tt,Z]),ir=o.useMemo(()=>{if(!C)return[];const m=ui(C.item);if(!m)return[];const v=i.find(k=>k.runId===m||k.sliceRunId===m);return(v==null?void 0:v.decisionOptions)??[]},[C,i]),Ds=o.useMemo(()=>kt?kt.tone==="positive"?M.lime:kt.tone==="warning"?M.amber:kt.tone==="critical"?M.red:M.teal:M.teal,[kt]),ei=(kt==null?void 0:kt.terminalStop)===!0,ut=o.useMemo(()=>Bh(rt((C==null?void 0:C.item)??null)),[C]),ki=o.useMemo(()=>rt((C==null?void 0:C.item)??null),[C]),vt=o.useMemo(()=>Qh((C==null?void 0:C.item)??null,se),[se,C]),ti=o.useMemo(()=>{if(!(vt!=null&&vt.retryAt))return null;const m=new Date(vt.retryAt);if(!Number.isFinite(m.getTime()))return null;const v=m.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),k=Pt(vt.retryAt);return k?`${v} (${k})`:v},[vt]),g=o.useMemo(()=>C?fi(C.item):{agentId:null,agentName:null},[C]),A=o.useMemo(()=>El(tn(C==null?void 0:C.item.metadata)??void 0),[C]),F=o.useMemo(()=>{var k;if(!C)return[];const m=ui(C.item);if(m){const S=i.find(ee=>ee.runId===m||ee.sliceRunId===m);if((k=S==null?void 0:S.scopeProgress)!=null&&k.milestones)return S.scopeProgress.milestones.map(ee=>({id:ee.id,title:ee.title,tasks:[],totalTasks:ee.total,doneTasks:ee.done}))}const v=fe(rt(C.item),["workstream_id","workstreamId"]);if(v&&R){const S=R.find(ee=>ee.workstreamId===v);if(S!=null&&S.milestoneBreakdown)return S.milestoneBreakdown}return[]},[C,i,R]);o.useMemo(()=>El(ki),[ki]);const _=o.useMemo(()=>{const m=$c((C==null?void 0:C.item)??null);return m.length>0?m:ng((C==null?void 0:C.item)??null,t,new Set)},[C,t]),V=o.useMemo(()=>_.filter((m,v,k)=>k.findIndex(S=>S.path===m.path)===v),[_]),Ne=o.useMemo(()=>V.slice(0,4),[V]),Ze=o.useMemo(()=>V.slice(4),[V]),Oe=o.useMemo(()=>{if(V.length===0)return null;const m=V[0];return m?Pr(m.path):null},[V]),Ie=o.useMemo(()=>{var S;const m=Kt(Q);if(m)return m;const v=Rl((C==null?void 0:C.item)??null);if(v)return v;const k=Kt(C==null?void 0:C.item.summary)??Kt(C==null?void 0:C.item.description);if(k)return k;if(C){const ee=C.item,$e=rt(ee),Pe=fe($e,["agent_name","agentName"])??ee.agentName??"OrgX",ft=fe($e,["task_title","taskTitle","workstream_title","workstreamTitle"]),yt=((S=ee.type)==null?void 0:S.replace(/_/g," "))??"activity";return ft?`${Pe} worked on ${ft}`:`${Pe} recorded a ${yt}`}return null},[Q,C]),Ye=o.useMemo(()=>C?Wi(C.item):!1,[C]),Re=o.useMemo(()=>{if(!se||!C)return null;const m=se.initiativeId??C.item.initiativeId??null,v=se.workstreamId??mi(C.item);if(!m||!v)return null;const k=$n((P==null?void 0:P.parsedStatus)??se.parsedStatus),S=$n((P==null?void 0:P.stopReason)??se.stopReason),ee=Math.max(0,(P==null?void 0:P.blockingDecisions)??se.blockingDecisions??(C.item.decisionRequired?1:0)),$e=Math.max(0,(P==null?void 0:P.nonBlockingDecisions)??se.nonBlockingDecisions??0),Pe=k==="blocked"||k==="error"||k==="failed"||S==="blocked"||S==="error"||C.item.type==="blocker_created",ft=!Pe&&ee===0&&$e>0&&(k==="needs_decision"||k==="completed"||S==="completed");return!Pe&&!ft?null:{initiativeId:m,workstreamId:v,runId:C.runId??null,event:se.event,requestedByAgentId:se.requesterAgentId??C.item.requesterAgentId??null,requestedByAgentName:se.requesterAgentName??C.item.requesterAgentName??null,actionLabel:Pe?"Auto-fix in 10s":"Auto-continue in 10s",helperText:Pe?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:Pe}},[se,C,P]),gn=o.useCallback(()=>{q(null)},[]),$s=o.useCallback(async(m,v)=>{if(v){Ge(null),Je(m);try{await v()}catch(k){Ge(k instanceof Error?k.message:"Action failed")}finally{Je(k=>k===m?null:k)}}},[]),Bn=o.useCallback(async()=>{var m;if(!(!Re||Lt)){bt(!0),Et(null);try{const v=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:Re.initiativeId,workstreamId:Re.workstreamId,runId:Re.runId,event:Re.event,requestedByAgentId:Re.requestedByAgentId,requestedByAgentName:Re.requestedByAgentName,graceMs:1e4})}),k=await v.json().catch(()=>null);if(!v.ok||(k==null?void 0:k.ok)!==!0)throw new Error((k==null?void 0:k.error)||`Request failed (${v.status})`);const S=(m=k==null?void 0:k.scheduled)!=null&&m.dueAt?new Date(k.scheduled.dueAt):null,ee=S&&Number.isFinite(S.getTime())?S.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;Et(ee?`Scheduled. Auto action starts by ${ee} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(v){const k=v instanceof Error?v.message:"Failed to schedule auto-fix";Et(Xt(k)||k)}finally{bt(!1)}}},[Re,Lt]);o.useEffect(()=>{if(!_e)return;const m=window.setTimeout(()=>be(null),2e3);return()=>window.clearTimeout(m)},[_e]),o.useEffect(()=>{Ge(null)},[ge,me,x]),o.useEffect(()=>{if(!ke){Dt.current=null;return}const m=ke.trim();!m||Dt.current===m||!t.some(k=>k.id===m)||(Dt.current=m,Se("all"),O(""),J(1),q(m),D==null||D(m))},[t,D,ke]);const Jt=o.useCallback(async(m,v)=>{if(v)try{await navigator.clipboard.writeText(v),be(`${m} copied`)}catch{be("Copy failed")}},[]);o.useEffect(()=>{je("structured"),tt(!1),bt(!1),Et(null)},[Mt]),o.useEffect(()=>{Ee(null),Te("feed");const m=gg((C==null?void 0:C.item)??null);if(!m||Zt())return;const v=new URLSearchParams({turnId:m.turnId});m.sessionKey&&v.set("sessionKey",m.sessionKey),m.runId&&v.set("run",m.runId);const k=new AbortController;return fetch(`/orgx/api/live/activity/detail?${v.toString()}`,{method:"GET",signal:k.signal}).then(async S=>{var $e;return S.ok?(($e=(await S.json()).detail)==null?void 0:$e.summary)??null:(S.status===404&&Te("missing"),null)}).then(S=>{typeof S=="string"&&S.trim().length>0?(Ee(S),Te("local")):Te("missing")}).catch(S=>{S instanceof DOMException&&S.name==="AbortError"||Te("missing")}),()=>k.abort()},[C]),o.useEffect(()=>{ht(null),Ft(null);const m=C==null?void 0:C.item;if(!m||H)return;const v=(Q??m.summary??m.description??m.title??"").trim();if(!v||Zt())return;const k=new AbortController;return fetch("/orgx/api/live/activity/headline",{method:"POST",headers:{"Content-Type":"application/json"},signal:k.signal,body:JSON.stringify({text:v,title:m.title??null,type:m.type})}).then(async S=>S.ok?await S.json():((S.status===404||S.status===405)&&Ae(!0),null)).then(S=>{const ee=S==null?void 0:S.headline;typeof ee=="string"&&ee.trim().length>0&&(Ae(!1),ht(ee.trim()),Ft((S==null?void 0:S.source)??null))}).catch(S=>{S instanceof DOMException&&S.name}),()=>k.abort()},[C,Q,H]);const Qn=o.useCallback(m=>{var S;if(jt.length===0)return;const k=((Vn>=0?Vn:0)+m+jt.length)%jt.length;J(m),q(((S=jt[k])==null?void 0:S.item.id)??null)},[Vn,jt]);o.useEffect(()=>{Mt&&(Vn>=0||q(null))},[Vn,Mt]),o.useEffect(()=>{if(!Mt)return;const m=v=>{v.key==="ArrowRight"||v.key.toLowerCase()==="l"?(v.preventDefault(),Qn(1)):(v.key==="ArrowLeft"||v.key.toLowerCase()==="h")&&(v.preventDefault(),Qn(-1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[Mt,Qn]);const ni=cn.size===1,Ps=ni?[...cn][0]:null,si=Ps?s.find(m=>m.runId===Ps||m.id===Ps)??null:null,Fs=o.useMemo(()=>{if(!ni)return[];const m=[],v=new Set;for(const k of pt){if(!k.runId||!cn.has(k.runId))continue;const S=_a(k.item);if(S){if(v.has(S)||(v.add(S),!oe))continue}else if(!oe&&Wi(k.item))continue;m.push(k.item)}return m},[ni,pt,cn,oe]),io=!B&&jt.length<=160,ii=(m,v,k)=>{const S=m.item,ee=k??S.id,$e=fi(S),Pe=Sl(S),ft=Mh(S,Pe),yt=Pe.executor??Pe.requester,wt=Aa(wn((yt==null?void 0:yt.name)??Pe.primaryLabel??S.agentName??$e.agentName??null),wn((yt==null?void 0:yt.id)??S.agentId??$e.agentId??null),xe)||"OrgX";let Be=Rh(ft)||wt;if(ft==="agent"&&wt){const uo=Gi(wt);uo&&(Be=`${wt} (${uo})`)}const et=ja(m.userState),At=ft==="agent"?Qa(wt)||et:Eh[ft]||et,Xe=We==="newest"&&v<2,qt=m.runId,Wt=Rl(S),Ii=Wh(S),{title:Ni}=Xi(S),Rn=Wt??Ii??Kt(S.summary),ji=Kt(S.description),ao=Dl(S,Rn??ji??null),Zr=rt(S),oo=Ar([{value:fe(Zr,["initiative_title","initiativeTitle"]),idHint:S.initiativeId},{value:S.initiativeId?Nt.get(S.initiativeId)??null:null,idHint:S.initiativeId}]),bs=mi(S)??(qt?ve.get(qt)??null:null),lo=Ar([{value:fe(Zr,["workstream_title","workstreamTitle"]),idHint:bs},{value:bs?xt.get(bs)??null:null,idHint:bs},{value:qt?De.get(qt)??null:null,idHint:bs}]),Bc=[oo,lo].filter(Boolean).join(" > "),zc=ks(fe(Zr,["event","event_name","eventName"]),null),Ai=bs?re.get(bs):void 0,Uc=(z==null?void 0:z.state)==="running"&&bs===(z==null?void 0:z.activeWorkstreamId),Wc=Ai?` — #${Ai.rank} in queue`:"",Hc=(Bc||oo||lo||zc||Ui(S.type))+(Uc?Wc:""),Kc=Na(m.userState),Vc=new Date(S.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),Gc=Pt(S.timestamp),Xc=m.bucket==="artifact"?zh(S):null,co=Uh(S);return n.jsx(Xf,{renderKey:ee,displayTitle:Ni,headline:ao,contextLabel:Hc,detailText:(Rn??ji)!==ao?Rn??ji:null,displayAgentName:Be,railColor:At,statusColor:et,userStateLabel:Kc,userStateWhy:m.userStateWhy,relativeTime:Gc,timeLabel:Vc,isRecent:Xe,enableMotion:io,onOpen:()=>{J(1),q(S.id)},ariaLabel:`Open activity details for ${Ni||Ui(S.type)}`,artifactSnippet:Xc,evidenceChips:co.length>0?co:void 0,actorCategory:ft,queuePosition:Ai?{rank:Ai.rank,state:Ai.state}:null},ee)};return n.jsx(dh,{sessions:s,initiatives:r??[],workspaceId:pe??null,query:me,statusFilter:ge,sortOrder:We,timeFilterId:x,customTimeRange:h,snapshot:le,onRequestRefresh:te,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[ni&&Fs.length>0?n.jsx(Hf,{items:Fs,session:si,agentName:((ro=Fs[0])==null?void 0:ro.agentName)??null,onBack:N,onOpenItem:m=>{J(1),q(m.id)}}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h2",{className:"flex-shrink-0 text-heading font-semibold text-white",children:"Activity"}),n.jsx("span",{className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.05] px-2 py-0.5 text-micro text-primary tabular-nums",children:vn}),Fn>0&&n.jsxs("span",{className:"hidden flex-shrink-0 rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums sm:inline-flex",children:["+",Fn," hidden"]}),Ji>0&&!oe&&n.jsxs("button",{type:"button",onClick:()=>ye(!0),className:"hidden flex-shrink-0 rounded-full border border-white/[0.14] bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums transition-colors hover:bg-white/[0.08] hover:text-primary sm:inline-flex",title:"Show low-signal sync replay events",children:[Ji," sync hidden"]}),oe&&n.jsx("button",{type:"button",onClick:()=>ye(!1),className:"hidden flex-shrink-0 rounded-full border border-lime/30 bg-lime/[0.10] px-2 py-0.5 text-micro text-[#E1FFB2] transition-colors hover:bg-lime/[0.16] sm:inline-flex",title:"Hide low-signal sync replay events",children:"Sync visible"}),n.jsx("span",{className:ue("h-1.5 w-1.5 flex-shrink-0 rounded-full",ns&&"pulse-soft"),style:{backgroundColor:M.lime},"aria-label":"Live",title:ns?"New activity within the last minute":"Live activity feed"}),n.jsx("div",{className:"ml-auto w-[180px] flex-shrink-0 sm:w-[220px]",children:n.jsxs("div",{className:"relative",children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-muted",children:[n.jsx("circle",{cx:"11",cy:"11",r:"7"}),n.jsx("path",{d:"m20 20-3.5-3.5"})]}),n.jsx("input",{value:me,onChange:m=>O(m.target.value),placeholder:"Search...",className:"h-7 w-full rounded-full border border-white/[0.08] bg-white/[0.03] pl-7 pr-2 text-micro text-primary placeholder:text-muted transition-colors focus:border-[#BFFF00]/30 focus:outline-none","aria-label":"Search activity"})]})})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsxs("div",{className:"relative",ref:rn,children:[n.jsxs("button",{type:"button",onClick:()=>{Qe(m=>!m),ct(!1)},"aria-haspopup":"menu","aria-expanded":Me,className:ue("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",Me?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsx("span",{className:"max-w-[120px] truncate",children:mn}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:ue("transition-transform duration-200",Me&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(It,{children:Me&&n.jsx(he.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute left-0 z-30 mt-2 w-[min(92vw,380px)] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity time range",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Presets"}),n.jsx("div",{className:"flex flex-wrap gap-1",children:Ki.filter(m=>m.id!=="custom").map(m=>{const v=x===m.id;return n.jsx("button",{type:"button",onClick:()=>{b==null||b(m.id),Qe(!1)},className:ue("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",v?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:m.label},m.id)})})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] p-2.5",children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Custom range"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"Start"}),fs?n.jsx("input",{type:"datetime-local",step:300,value:Ia(Ot),onChange:m=>Hn(jl(m.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(mo,{selected:Ot,onChange:m=>Hn(m instanceof Date?m:null),selectsStart:!0,startDate:Ot,endDate:Gt,showTimeSelect:!0,timeIntervals:5,dateFormat:"MMM d, yyyy h:mm aa",className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35",calendarClassName:"orgx-datepicker",popperClassName:"orgx-datepicker-popper",popperPlacement:"bottom-start",showPopperArrow:!1}),n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"End"}),fs?n.jsx("input",{type:"datetime-local",step:300,min:Ia(Ot),value:Ia(Gt),onChange:m=>Pn(jl(m.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(mo,{selected:Gt,onChange:m=>Pn(m instanceof Date?m:null),selectsEnd:!0,minDate:Ot??void 0,startDate:Ot,endDate:Gt,showTimeSelect:!0,timeIntervals:5,dateFormat:"MMM d, yyyy h:mm aa",className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35",calendarClassName:"orgx-datepicker",popperClassName:"orgx-datepicker-popper",popperPlacement:"bottom-start",showPopperArrow:!1})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-micro text-secondary",children:on?`${kr(Ot)} - ${kr(Gt)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:Js,className:"rounded-full border border-white/[0.14] bg-white/[0.03] px-2.5 py-1 text-micro font-semibold text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Clear"}),n.jsx("button",{type:"button",onClick:Jr,disabled:!on,className:"rounded-full border border-lime/30 bg-lime/[0.14] px-2.5 py-1 text-micro font-semibold text-[#E1FFB2] transition-colors hover:bg-lime/[0.2] disabled:opacity-45",children:"Apply"})]})]})]})]})})})]}),n.jsx("div",{className:"mx-0.5 h-3.5 w-px flex-shrink-0 bg-white/[0.08]"}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[(Yt||d||p)&&n.jsxs(n.Fragment,{children:[Yt&&n.jsxs("button",{onClick:N,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[Nl(Ms.id)?n.jsx(hi,{provider:Ms.id,size:"xs"}):n.jsx(en,{name:($t==null?void 0:$t.agentName)??"OrgX",hint:c??null,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Session",c?`: ${c}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),d&&n.jsxs("button",{onClick:f,className:"chip inline-flex min-w-0 items-center gap-2",style:{borderColor:"rgba(191,255,0,0.28)",color:"#D8FFA1"},"aria-label":"Clear workstream filter",children:[n.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro",children:"↳"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Workstream",u?`: ${u}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),p&&n.jsxs("button",{onClick:T,className:"chip chip-avatar inline-flex min-w-0 items-center",style:{borderColor:"rgba(10,212,196,0.3)",color:"#0AD4C4"},"aria-label":"Clear agent filter",children:[Nl(Es.id)?n.jsx(hi,{provider:Es.id,size:"xs"}):n.jsx(en,{name:p,hint:p,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Agent: ",p]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]})]}),n.jsx("div",{className:"inline-flex flex-shrink-0 items-center gap-1 rounded-full border border-white/[0.08] bg-white/[0.02] p-0.5",role:"group","aria-label":"Activity status filters",children:Object.keys(vr).map(m=>{const v=ge===m;return n.jsx("button",{type:"button",onClick:()=>Se(m),"aria-pressed":v,className:ue("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",v?"border border-lime/25 bg-lime/[0.10] text-[#E1FFB2]":"border border-transparent text-secondary hover:bg-white/[0.08] hover:text-bright"),children:vr[m]},m)})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:dt,children:[n.jsxs("button",{type:"button",onClick:()=>{ct(m=>!m),Qe(!1)},"aria-haspopup":"menu","aria-expanded":L,"aria-label":"Activity filters",title:"Activity filters",className:ue("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",L?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"border-white/[0.1] bg-white/[0.03] text-primary hover:bg-white/[0.08]"),children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 6h16"}),n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"M10 18h4"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Filters"}),n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:ue("transition-transform duration-200",L&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(It,{children:L&&n.jsx(he.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute right-0 z-20 mt-2 w-[290px] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity view controls",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Sort"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:[{id:"newest",label:"Newest"},{id:"oldest",label:"Oldest"}].map(m=>n.jsx("button",{type:"button",onClick:()=>{Fe(m.id),ct(!1)},className:ue("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",We===m.id?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:m.label},m.id))})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Time window"}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Use the time dropdown beside Activity count for presets and custom date/time ranges."})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:Object.keys(vr).map(m=>{const v=ge===m;return n.jsx("button",{type:"button",onClick:()=>{Se(m),ct(!1)},className:ue("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",v?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:vr[m]},m)})})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Signal"}),n.jsx("button",{type:"button",onClick:()=>{ye(m=>!m)},className:ue("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",oe?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:oe?"Hide background sync events":"Show background sync events"}),n.jsx("p",{className:"mt-1 text-micro leading-relaxed text-muted",children:"Background sync events are routine system operations that most users can safely ignore."})]})]})})})]})]})]})]})}),n.jsxs("div",{ref:an,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[jt.length===0&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-4 py-5",children:n.jsxs("div",{className:"mx-auto max-w-2xl",children:[n.jsx(Qr,{icon:"activity",headline:ne?"Syncing activity feed...":Yt?"No activity yet for this session":d?"No activity yet for this workstream":p?`No recent activity from ${p}`:ge!=="all"?`No matches for this filter. ${vn>0?`${vn} events in other categories.`:""}`:R&&R.length>0?`Waiting for autopilot to start. Queue has ${R.length} item${R.length===1?"":"s"} ready.`:"No activity yet",description:ne?"Live updates usually appear within a few seconds after dispatch.":ge!=="all"?'Try selecting "All" to see every event.':p?`Try widening the time window or select a different agent.${Ut?` Last active: ${Ut}.`:""}`:`Try widening the time window (${mn}), changing filters, or launch the next workstream.`,className:"py-6"}),n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-1.5",children:ss.map(m=>{const v=x===m.id;return n.jsx("button",{type:"button",onClick:()=>b==null?void 0:b(m.id),className:ue("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",v?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.1] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:m.label},`empty-time-${m.id}`)})}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[p&&n.jsx("button",{type:"button",onClick:()=>{T==null||T(),b==null||b("all")},className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Show all activity"}),(Yt||d||ge!=="all")&&n.jsx("button",{type:"button",onClick:()=>{Yt&&N(),d&&(f==null||f()),p&&(T==null||T()),ge!=="all"&&Se("all")},className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Clear filters"}),E&&n.jsx("button",{type:"button",onClick:()=>void $s("play",E),disabled:Ve!==null,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18 disabled:opacity-45",children:Ve==="play"?"Starting...":"Start next session"}),!E&&ae&&n.jsx("button",{type:"button",onClick:ae,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18",children:"Browse initiatives"})]}),He&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:He})]})}),n.jsx(Kf,{completedCount:bn.completed,decisionsCount:bn.decisions,blockerCount:bn.blocked,visible:Vt,onDismiss:()=>{Qt(!1),ot.current=Date.now()}}),jt.length>0&&n.jsxs("div",{className:"space-y-4",children:[yi.map(m=>{const v=m.clusters;return n.jsxs("section",{children:[n.jsx("h3",{className:"mb-2.5 border-b border-subtle pb-1.5 text-caption font-semibold tracking-[0.01em] text-muted",children:m.label}),io?n.jsx(It,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:v.map((k,S)=>{const ee=U.has(k.key),$e=k.allItems.slice(1),Pe=$e.length,ft=Math.min(Pe,ce[k.key]??Fi),yt=$e.slice(0,ft);if(k.count===1)return ii(k.representative,S);if(k.key.startsWith("autopilot::")&&k.count>=3){const Be=Ml(k);return n.jsx(yl,{workstreamTitle:Be.workstreamTitle,items:Be.items,firstTimestamp:k.firstTimestamp,lastTimestamp:k.representative.timestampEpoch,onExpandItem:et=>{const At=k.allItems[et];At&&q(At.item.id)}},k.key)}const wt=`cluster:${k.key}`;return n.jsxs("div",{children:[ii(k.representative,S,wt),n.jsxs("button",{type:"button",onClick:Be=>{Be.stopPropagation(),bi(k.key)},className:"mt-1 ml-8 inline-flex items-center gap-1.5 rounded-full border border-white/[0.1] bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:[n.jsxs("span",{className:"font-semibold",children:["×",k.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:ee?"hide":`and ${k.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ue("transition-transform",ee?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ee&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[yt.map((Be,et)=>ii(Be,S+et+1)),ft<Pe&&n.jsxs("button",{type:"button",onClick:Be=>{Be.stopPropagation(),gs(k.key,Pe)},className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:["Load more (",Pe-ft," remaining)"]})]})]},k.key)})})}):n.jsx("div",{className:"space-y-2",children:v.map((k,S)=>{const ee=U.has(k.key),$e=k.allItems.slice(1),Pe=$e.length,ft=Math.min(Pe,ce[k.key]??Fi),yt=$e.slice(0,ft);if(k.count===1)return ii(k.representative,S);if(k.key.startsWith("autopilot::")&&k.count>=3){const Be=Ml(k);return n.jsx(yl,{workstreamTitle:Be.workstreamTitle,items:Be.items,firstTimestamp:k.firstTimestamp,lastTimestamp:k.representative.timestampEpoch,onExpandItem:et=>{const At=k.allItems[et];At&&q(At.item.id)}},k.key)}const wt=`cluster:${k.key}`;return n.jsxs("div",{children:[ii(k.representative,S,wt),n.jsxs("button",{type:"button",onClick:Be=>{Be.stopPropagation(),bi(k.key)},className:"mt-1 ml-8 inline-flex items-center gap-1.5 rounded-full border border-white/[0.1] bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:[n.jsxs("span",{className:"font-semibold",children:["×",k.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:ee?"hide":`and ${k.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ue("transition-transform",ee?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ee&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[yt.map((Be,et)=>ii(Be,S+et+1)),ft<Pe&&n.jsxs("button",{type:"button",onClick:Be=>{Be.stopPropagation(),gs(k.key,Pe)},className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:["Load more (",Pe-ft," remaining)"]})]})]},k.key)})})]},m.key)}),n.jsx("div",{ref:ln,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:ue("flex items-center justify-center py-6 transition-opacity duration-500 ease-out",j?"opacity-100":y?"opacity-0":"opacity-0 pointer-events-none"),children:n.jsx("div",{className:"flex items-center gap-2.5",children:n.jsxs("div",{className:"flex gap-1","aria-label":"Loading older events",children:[n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/70 animate-[pulse_1.4s_ease-in-out_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/50 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/30 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]"})]})})}),!y&&!j&&jt.length>0&&!kl(x)&&n.jsx("p",{className:"py-6 text-center text-caption text-muted",children:Fn>0?`${jt.length} of ${vn} events`:"Beginning of activity history"})]})]})]}),G?n.jsx(vh,{}):null,n.jsx(Qf,{open:C!==null,onClose:gn,children:C&&n.jsxs("div",{className:"relative flex h-[100dvh] w-full min-h-0 flex-col sm:h-[86vh] sm:max-h-[86vh]",children:[n.jsx("div",{className:"absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-lime/10 via-cyan/5 to-transparent"}),n.jsxs("div",{className:"relative z-10 flex items-center justify-between border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:{backgroundColor:ja(C.userState),boxShadow:`0 0 12px ${ja(C.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Na(C.userState)," · ",Vn+1,"/",jt.length," sessions"]}),_e&&n.jsx(Ln,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:_e})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[C.runId&&X&&n.jsx("button",{type:"button",onClick:()=>{X(C.runId),gn()},className:"rounded-full border border-lime/25 bg-lime/10 px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/20",children:"Focus session"}),n.jsx("button",{type:"button",onClick:()=>Qn(-1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-primary transition hover:bg-white/[0.1]","aria-label":"Previous activity item",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})})}),n.jsx("button",{type:"button",onClick:()=>Qn(1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-primary transition hover:bg-white/[0.1]","aria-label":"Next activity item",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m9 18 6-6-6-6"})})}),n.jsxs("div",{className:"relative",children:[n.jsx("button",{type:"button",onClick:()=>tt(m=>!m),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"More actions",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[n.jsx("circle",{cx:"12",cy:"5",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"19",r:"1.5"})]})}),Le&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>tt(!1)}),n.jsxs("div",{className:"absolute right-0 top-full z-40 mt-1 min-w-[160px] rounded-lg border border-strong bg-[#0d0f16] py-1 shadow-xl",children:[C.runId&&n.jsx("button",{type:"button",onClick:()=>{Jt("Run id",C.runId??""),tt(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy run ID"}),g.agentId&&n.jsx("button",{type:"button",onClick:()=>{Jt("Agent id",g.agentId??""),tt(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy agent ID"}),n.jsx("button",{type:"button",onClick:()=>{Jt("Event id",C.item.id),tt(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy event ID"})]})]})]}),n.jsx("button",{type:"button",onClick:gn,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"Close activity detail",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]})]}),n.jsx("div",{className:"relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-5 pb-5 pt-4 sm:px-6",children:n.jsx(It,{mode:"wait",custom:at,children:n.jsx(he.section,{custom:at,initial:{opacity:0,x:at*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:at*-32,scale:.985},transition:{duration:.28,ease:[.16,1,.3,1]},className:"min-h-full w-full overscroll-contain",children:n.jsxs("div",{className:"space-y-6 pb-1",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-title font-semibold tracking-[-0.02em] text-white whitespace-pre-wrap break-words",children:lt||Dl(C.item,Q)||st(C.item.title||Ui(C.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(C.item.timestamp).toLocaleString()," · ",Pt(C.item.timestamp),Rt==="llm"&&n.jsx("span",{className:"text-muted",children:"· AI title"})]}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-caption",children:[(()=>{const m=rt(C.item),v=(se==null?void 0:se.workstreamId)??mi(C.item)??(C.runId?ve.get(C.runId)??null:null),k=Ar([{value:(se==null?void 0:se.workstreamTitle)??null,idHint:v},{value:fe(m,["workstream_title","workstreamTitle"]),idHint:v},{value:v?xt.get(v)??null:null,idHint:v},{value:C.runId?De.get(C.runId)??null:null,idHint:v}]),ee=[Ar([{value:(se==null?void 0:se.initiativeTitle)??null,idHint:C.item.initiativeId},{value:fe(m,["initiative_title","initiativeTitle"]),idHint:C.item.initiativeId},{value:C.item.initiativeId?Nt.get(C.item.initiativeId)??null:null,idHint:C.item.initiativeId}]),k].filter(Boolean).join(" > ");return ee?n.jsx(Ln,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:ee})}):null})(),n.jsx(Ln,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:Na(C.userState)}),n.jsxs(Ln,{tone:"muted",children:[n.jsx(en,{name:(Nn==null?void 0:Nn.label)??(it==null?void 0:it.primaryLabel)??"OrgX",hint:Nn?Cl(Nn):(it==null?void 0:it.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(Nn==null?void 0:Nn.label)??(it==null?void 0:it.primaryLabel)??"OrgX"})]}),Ye&&n.jsx(Ln,{tone:"lime",children:"Sync replay"})]})]}),qn.has("artifact")&&C&&Ir(C.item)&&!En&&n.jsxs("button",{type:"button",onClick:()=>{const m=Ir(C.item);m&&K(m)},className:"flex w-full items-center gap-2.5 rounded-xl border border-cyan-400/25 bg-cyan-500/[0.08] px-3.5 py-2.5 text-left transition-colors hover:bg-cyan-500/[0.14]",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:M.cyan,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsx("span",{className:"text-body font-medium",style:{color:M.cyan},children:"View registered artifact"})]}),n.jsx(Zf,{item:C.item}),qn.has("artifact")&&En&&n.jsxs("div",{className:"rounded-xl border border-cyan-400/25 bg-gradient-to-b from-cyan-500/[0.10] to-cyan-500/[0.04]",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 px-4 pt-3.5 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#67e8f9",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsx("span",{className:"text-micro font-semibold uppercase tracking-wider text-cyan-200/80",children:En.source==="metadata"?"Artifact":st(En.source)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[G&&n.jsxs("div",{className:"inline-flex rounded-full border border-cyan-400/20 bg-black/30 p-0.5 text-caption",children:[n.jsx("button",{type:"button",onClick:()=>je("structured"),"aria-pressed":Ue==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${Ue==="structured"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"Structured"}),n.jsx("button",{type:"button",onClick:()=>je("json"),"aria-pressed":Ue==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${Ue==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),Zs&&n.jsx("button",{type:"button",onClick:()=>K(Zs),className:"rounded-full border border-cyan-400/25 bg-cyan-500/[0.12] px-2.5 py-0.5 text-caption font-semibold text-cyan-100 transition hover:bg-cyan-500/[0.2]",children:"Open full artifact"})]})]}),n.jsx("div",{className:"max-h-[320px] overflow-y-auto px-4 pb-4",children:n.jsx("div",{className:"rounded-lg border border-white/[0.06] bg-black/20 p-3.5",children:Ue==="structured"?Oc(En.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(En.value,null,2)})})})]}),qn.has("outcome")&&Tt&&n.jsxs("div",{className:ue("rounded-xl border px-3.5 py-3",Tt.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",Tt.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",Tt.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",Tt.tone==="neutral"&&"border-cyan-400/22 bg-cyan-500/[0.07]"),children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-white/78",children:Tt.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:Tt.summary}),Tt.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:Tt.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[C.runId&&X&&n.jsx("button",{type:"button",onClick:()=>{X(C.runId),gn()},className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Open work session"}),sr&&n.jsx("button",{type:"button",onClick:()=>{Z==null||Z(cs[0]??null),gn()},className:"rounded-full border border-amber-300/30 bg-amber-400/[0.10] px-3 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-400/[0.16]",children:cs.length>0?"Resolve decision":"Resolve decisions"}),Zs&&!En&&n.jsx("button",{type:"button",onClick:()=>K(Zs),className:"rounded-full border border-cyan-300/25 bg-cyan-500/[0.1] px-3 py-1 text-caption font-semibold text-cyan-100 transition hover:bg-cyan-500/[0.16]",children:"Open artifact"}),Oe&&n.jsx("a",{href:Oe,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Review evidence"}),Re&&n.jsx("button",{type:"button",onClick:()=>void Bn(),disabled:Lt,className:ue("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",Re.isBlockedFlow?"border-amber-300/30 bg-amber-500/[0.12] text-amber-100 hover:bg-amber-500/[0.18]":"border-lime/30 bg-lime/[0.12] text-[#D8FFA1] hover:bg-lime/[0.18]"),children:Lt?"Scheduling...":Re.actionLabel})]}),Re&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:Ct??Re.helperText})]}),(()=>{var Wt,Ii,Ni;if(!qn.has("structured_outcomes"))return null;const m=rt(C.item),v=tn(m==null?void 0:m.outcomes),k=Yr(m),S=kn((m==null?void 0:m.status_updates_applied)??(m==null?void 0:m.statusUpdatesApplied)??((Wt=tn(m==null?void 0:m.result))==null?void 0:Wt.status_updates_applied)??((Ii=tn(m==null?void 0:m.result))==null?void 0:Ii.statusUpdatesApplied)),ee=((Ni=fe(m,["event","event_name","eventName"]))==null?void 0:Ni.toLowerCase())??"",$e=(m==null?void 0:m.status_updates_buffered)??(m==null?void 0:m.statusUpdatesBuffered),Pe=ee.includes("status_updates_buffered")||$e===!0||typeof $e=="number"&&$e>0||typeof $e=="string"&&["true","1","yes"].includes($e.trim().toLowerCase()),ft=fe(v,["pr_url","prUrl","url"]),yt=v==null?void 0:v.pr_number,wt=fe(v,["commit_sha","commitSha"]),Be=fe(v,["commit_url","commitUrl"]),et=tn(v==null?void 0:v.tests),Xe=(k.length>0||(S??0)>0||Pe)&&(!En||ee.includes("status_updates"));return ft||wt||et||Xe?n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-muted",children:Xe?"Updates & outcomes":"Outcomes"}),Xe&&n.jsxs("div",{className:"rounded-xl border border-[#14B8A6]/20 bg-[#14B8A6]/[0.06] px-3.5 py-2.5",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-[#14B8A6]"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-[#7ce0d3]",children:Pe?"Updates being applied":"Updates applied"}),n.jsxs("p",{className:"mt-0.5 text-body text-primary",children:[k.length>0?`${k.length} scoped update${k.length===1?"":"s"}`:(S??0)>0?`${S} status update${S===1?"":"s"}`:"Status updates recorded",Pe?" · queued for sync":""]})]})]}),k.length>0&&n.jsx("ul",{className:"mt-2 space-y-1.5 pl-5",children:k.slice(0,6).map((Rn,ji)=>n.jsxs("li",{className:"text-caption text-secondary",children:[n.jsxs("span",{className:"text-primary",children:[Rn.scope,": ",Rn.label]}),Rn.status?` → ${Rn.status}`:"",Rn.reason?` · ${Rn.reason}`:""]},`${Rn.scope}-${Rn.label}-${ji}`))})]}),ft&&n.jsxs("a",{href:ft,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 rounded-xl border border-lime/20 bg-lime/[0.06] px-3.5 py-2.5 transition-colors hover:bg-lime/[0.10]",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-lime"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-lime/70",children:"Pull Request"}),n.jsx("p",{className:"mt-0.5 text-body font-semibold text-primary",children:yt?`#${yt}`:"View on GitHub"})]}),n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:"flex-shrink-0 text-muted",children:n.jsx("path",{d:"M7 17 17 7M17 7H7M17 7v10"})})]}),wt&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-lime/15 bg-lime/[0.04] px-3.5 py-2.5",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-lime/60"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-lime/60",children:"Commit"}),n.jsx("p",{className:"mt-0.5 font-mono text-caption text-primary",children:wt.slice(0,7)})]}),Be&&n.jsx("a",{href:Be,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary hover:text-primary transition-colors",children:"View"})]}),et&&n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-cyan-400/15 bg-cyan-500/[0.04] px-3.5 py-2.5",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:(et.failed??0)>0?M.red:"#67e8f9"}}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider",style:{color:(et.failed??0)>0?M.red:"rgba(103,232,249,0.7)"},children:"Tests"}),n.jsxs("p",{className:"mt-0.5 text-body text-primary",children:[et.passed??0," passed",(et.failed??0)>0&&n.jsxs("span",{className:"text-red-300",children:[" · ",et.failed," failed"]}),(et.skipped??0)>0&&n.jsxs("span",{className:"text-muted",children:[" · ",et.skipped," skipped"]})]})]})]})]}):null})(),vt&&!G&&n.jsxs("div",{className:"mt-3 rounded-xl border border-amber-300/20 bg-amber-500/[0.06] px-3.5 py-3",children:[n.jsx("p",{className:"text-caption text-amber-100/80",children:"Temporarily paused to manage capacity. Will resume automatically."}),vt.retryInMs!==null&&n.jsxs("p",{className:"mt-1 text-micro text-muted",children:["Retrying in ~",Math.max(1,Math.round(vt.retryInMs/1e3)),"s"]})]}),vt&&G&&n.jsxs("div",{className:"mt-3 rounded-xl border border-amber-300/26 bg-amber-500/[0.08] px-3.5 py-3",children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-amber-100/85",children:"Spawn guard"}),n.jsx(Ln,{tone:vt.isRateLimited?"muted":"red",children:vt.isRateLimited?"Rate limited":"Blocked"})]}),n.jsx("p",{className:"mt-1 text-caption text-amber-100/80",children:"Dispatch was stopped before launch. Adjust limits or retry after the window resets."}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Domain window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:vt.domainCurrent!==null&&vt.domainMax!==null?`${vt.domainCurrent}/${vt.domainMax} per hour`:"Not provided"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Global window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:vt.totalCurrent!==null&&vt.totalMax!==null?`${vt.totalCurrent}/${vt.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[vt.domain&&n.jsxs(Ln,{tone:"muted",children:["Domain: ",st(vt.domain)]}),vt.modelTier&&n.jsxs(Ln,{tone:"muted",children:["Tier: ",st(vt.modelTier)]}),ti&&n.jsxs(Ln,{tone:"muted",children:["Retry: ",ti]}),!ti&&vt.retryInMs!==null&&n.jsxs(Ln,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(vt.retryInMs/1e3)),"s"]})]}),vt.blockedReason&&n.jsx("p",{className:"mt-2 rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2 text-caption text-primary",children:Kt(vt.blockedReason)??vt.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[ze&&n.jsx("button",{type:"button",onClick:ze,className:"rounded-full border border-amber-300/32 bg-amber-500/[0.14] px-3 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-500/[0.2]",children:"Edit limits"}),Re&&n.jsx("button",{type:"button",onClick:()=>void Bn(),disabled:Lt,className:"rounded-full border border-lime/30 bg-lime/[0.12] px-3 py-1 text-caption font-semibold text-[#D8FFA1] transition hover:bg-lime/[0.18] disabled:opacity-50",children:Lt?"Scheduling...":"Retry now"})]})]}),nr.length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Results"}),n.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-caption sm:grid-cols-3",children:nr.map(m=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:m.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${m.tone==="critical"?"text-red-300":"text-primary"}`,children:m.value})]},m.label))})]}),it&&!se&&it.mode!=="system"&&n.jsxs("div",{className:"flex items-center gap-2 text-body text-secondary",children:[it.executor&&n.jsxs(n.Fragment,{children:[n.jsx(en,{name:it.executor.label,hint:Cl(it.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:it.executor.label}),(()=>{const m=Gi(it.executor.label);return m?n.jsxs("span",{className:"text-caption text-muted",children:["(",m,")"]}):null})()]}),it.mode==="handoff"&&it.requester&&n.jsxs("span",{className:"text-caption text-muted",children:["requested by ",it.requester.label]})]}),se&&n.jsxs("div",{className:"space-y-5",children:[qn.has("action_needed")&&(P==null?void 0:P.nextStep)&&((kt==null?void 0:kt.tone)==="critical"||(kt==null?void 0:kt.tone)==="warning")&&n.jsxs("div",{className:"rounded-xl border border-red-400/25 bg-red-500/[0.08] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-red-400"}),n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-red-200",children:"Action needed"})]}),n.jsx("p",{className:"text-body text-primary leading-relaxed",children:P.nextStep})]}),(()=>{if(!qn.has("session"))return null;const m=rt(C.item),v=fe(m,["parsed_status","status"]),k=["Queued","Dispatched","Running","Completed"],S={queued:"Queued",dispatched:"Dispatched",running:"Running",completed:"Completed",success:"Completed",blocked:"Running",needs_decision:"Running",needs_attention:"Running",failed:"Running"},ee=S[v??""]??S[se.event??""]??null,$e=ee?k.indexOf(ee):-1,Pe=v==="completed"||v==="success",ft=ui(C.item),yt=ft?Ys.get(ft):null,wt=yt!=null&&yt.startedAt?new Date(yt.startedAt).getTime():null,Be=yt!=null&&yt.completedAt?new Date(yt.completedAt).getTime():Pe?null:Date.now();let et=null;if(wt&&Be){const At=Be-wt;et=At<6e4?`${Math.round(At/1e3)}s`:`${Math.floor(At/6e4)}m ${Math.round(At%6e4/1e3)}s`}else if(wt&&!Pe){const At=Date.now()-wt;et=At<6e4?`${Math.round(At/1e3)}s`:`${Math.floor(At/6e4)}m ${Math.round(At%6e4/1e3)}s`}return n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5",children:[n.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Execution Flow"}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[n.jsx("span",{className:"rounded-full border border-lime/30 bg-lime/[0.08] px-2 py-0.5 text-micro font-semibold text-lime/85",children:Si(se.event)??st(se.event)}),et&&n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-black/20 px-2 py-0.5 text-micro text-secondary",children:[et," elapsed"]})]})]}),kt&&n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:Ds},children:ei?(Tt==null?void 0:Tt.label)??"Stopped":`${kt.pct}%`})]}),$e>=0&&n.jsx("div",{className:"mt-3 flex items-center gap-1",children:k.map((At,Xe)=>{const qt=Xe<$e||Xe===$e&&Pe,Wt=Xe===$e&&!Pe;return n.jsxs("div",{className:"flex items-center gap-1",children:[Xe>0&&n.jsx("div",{className:"h-[1.5px] w-4 sm:w-5",style:{backgroundColor:qt||Wt?M.lime:"rgba(255,255,255,0.14)"}}),n.jsxs("div",{className:"flex flex-col items-center gap-1",children:[n.jsx("span",{className:ue("h-2 w-2 rounded-full transition-transform duration-200",Wt&&"animate-pulse scale-110"),style:{backgroundColor:qt||Wt?M.lime:"rgba(255,255,255,0.18)"}}),n.jsxs("span",{className:ue("text-[10px] leading-none tracking-[0.05em]",qt||Wt?"text-primary":"text-muted/60"),children:[At,qt&&Xe===k.length-1&&" ✓"]})]})]},At)})}),kt&&n.jsxs("div",{className:"mt-3 border-t border-white/[0.06] pt-3",children:[n.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-white/[0.10]",children:n.jsx("div",{className:"h-full rounded-full transition-[width] duration-300",style:{width:`${Math.max(4,kt.pct)}%`,backgroundColor:Ds}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:ei?(Tt==null?void 0:Tt.summary)??kt.label:kt.label})]})]})})(),n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"People"}),ls.primary!==Xn?n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(en,{name:ls.primary,hint:ls.secondary??ls.primary,size:"xs"}),n.jsx("span",{children:ls.primary}),n.jsx("span",{className:"text-white/[0.2]",children:"→"}),n.jsx(en,{name:Xn,hint:Xn,size:"xs"}),n.jsx("span",{children:Xn}),se.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",st(se.domain),")"]})]}):n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(en,{name:Xn,hint:Xn,size:"xs"}),n.jsx("span",{children:Xn}),se.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",st(se.domain),")"]})]}),G&&n.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-x-6 gap-y-3 sm:grid-cols-4",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Requester"}),n.jsx("div",{className:"mt-0.5 text-caption text-primary",children:ls.primary})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Executor"}),n.jsx("div",{className:"mt-0.5 text-caption text-primary",children:Xn})]}),se.dispatcherClient&&se.dispatcherClient!=="unknown"&&n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Dispatcher"}),n.jsx("div",{className:"mt-0.5 text-caption text-primary",children:st(se.dispatcherClient)})]}),(se.domain||se.requiredSkills.length>0)&&n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Policy"}),n.jsxs("div",{className:"mt-0.5 text-caption text-primary",children:[se.domain??"",se.requiredSkills.length>0?`${se.domain?" · ":""}${se.requiredSkills.join(", ")}`:""]})]})]})]}),qn.has("scope")&&P&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Scope"}),n.jsxs("div",{className:"grid grid-cols-1 gap-x-6 gap-y-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Initiative"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:P.initiativeTitle??(P.initiativeId?Is(P.initiativeId):"—")})]}),P.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:st(P.initiativeStatus)})]}),(P.workstreamTitle||P.workstreamId)&&n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Workstream"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:P.workstreamTitle??Is(P.workstreamId)})]}),P.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:st(P.workstreamStatus)})]})]}),P.initiativeWorkstreamPct!==null&&n.jsxs("div",{className:"mt-3",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro text-muted",children:[n.jsx("span",{children:"Workstreams complete"}),n.jsxs("span",{className:"tabular-nums",children:[P.doneInitiativeWorkstreams??0,"/",P.totalInitiativeWorkstreams??0]})]}),n.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-white/[0.10]",children:n.jsx("div",{className:"h-full rounded-full bg-[#BFFF00]/80",style:{width:`${Math.max(4,P.initiativeWorkstreamPct)}%`}})})]})]}),F.length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Milestones"}),n.jsx(Pm,{nodes:Lm(F),compact:!0})]}),((P==null?void 0:P.taskTitle)||(P==null?void 0:P.milestoneTitle)||(P==null?void 0:P.phase)||(P==null?void 0:P.nextStep)||(P==null?void 0:P.parsedStatus)||(P==null?void 0:P.stopReason))&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Current step"}),n.jsxs("div",{className:"space-y-1 text-caption",children:[(P==null?void 0:P.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:P.taskTitle})]}),(P==null?void 0:P.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:P.milestoneTitle})]}),(P==null?void 0:P.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:Si(P.phase)??st(P.phase)})]}),(P==null?void 0:P.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:P.nextStep})]}),(P==null?void 0:P.parsedStatus)&&P.parsedStatus!==(P==null?void 0:P.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:Si(P.parsedStatus)??st(P.parsedStatus)})]}),(P==null?void 0:P.stopReason)&&P.stopReason!==(P==null?void 0:P.phase)&&P.stopReason!==(P==null?void 0:P.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:Si(P.stopReason)??st(P.stopReason)})]})]})]}),se.error&&n.jsx("div",{className:"rounded-lg border border-red-400/20 bg-red-500/10 px-4 py-3 text-body text-red-100/80",children:se.error})]}),qn.has("summary")&&Ie&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),nt==="missing"&&!Ye&&G&&n.jsx("p",{className:"mb-1 text-caption italic text-muted",children:"Transcript expired — showing event metadata"}),n.jsx(zi,{mode:"block",text:Ie,className:"text-body leading-relaxed text-primary"})]}),Kt(C.item.description)&&Kt(C.item.description)!==Ie&&(()=>{const m=Kt(C.item.description)??"";return m.length>200?n.jsxs("details",{children:[n.jsx("summary",{className:"cursor-pointer text-micro font-semibold uppercase tracking-wider text-muted select-none",children:"Details"}),n.jsx("div",{className:"mt-2",children:n.jsx(zi,{mode:"block",text:m,className:"text-body leading-relaxed text-secondary"})})]}):n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Details"}),n.jsx(zi,{mode:"block",text:m,className:"text-body leading-relaxed text-secondary"})]})})(),os&&n.jsxs("details",{children:[n.jsx("summary",{className:"cursor-pointer text-micro font-semibold uppercase tracking-wider text-muted select-none",children:"Narrative"}),n.jsxs("div",{className:"mt-2 space-y-1.5 text-caption",children:[n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Intent"})," ",n.jsx("span",{className:"text-primary",children:os.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:os.dispatch})]}),os.highlights.length>0&&n.jsxs("div",{children:[n.jsx("span",{className:"text-muted",children:"Highlights"}),n.jsx("ul",{className:"mt-1 list-disc space-y-0.5 pl-4 text-primary",children:os.highlights.slice(0,3).map((m,v)=>n.jsx("li",{children:m},`${os.sliceRunId}:highlight:${v}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:os.outcome.summary})]})]})]}),(()=>{var At;if(!qn.has("evidence"))return null;const m=rt(C.item),v=m==null?void 0:m.blocker,k=m==null?void 0:m.decisions_needed,S=m==null?void 0:m.outcomes,ee=(At=m==null?void 0:m.task_updates)==null?void 0:At.filter(Xe=>{var qt,Wt;return((qt=Xe.title)==null?void 0:qt.trim().toLowerCase())!==((Wt=v==null?void 0:v.description)==null?void 0:Wt.trim().toLowerCase())}),$e=(v==null?void 0:v.description)&&(Tt==null?void 0:Tt.summary)&&v.description.trim().toLowerCase()===Tt.summary.trim().toLowerCase(),Pe=!!v&&!$e,ft=!!(S!=null&&S.pr_url||S!=null&&S.commit_sha||S!=null&&S.tests||ee&&ee.length>0),yt=!!(Pe||k&&k.length>0),wt=ft||yt,Be=yt,et=V.length>0;return!Be&&!et?null:n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Evidence"}),n.jsxs("div",{className:"space-y-2",children:[Pe&&n.jsxs("div",{className:"rounded-xl border border-red-400/20 bg-red-500/[0.06] px-3.5 py-2.5",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-red-400"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-red-300/70",children:"Blocker"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:v.description??"Blocked"}),v.waiting_on&&n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Waiting on: ",v.waiting_on]})]})]}),sr&&cs.length>0&&n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[ir.map(Xe=>n.jsx("button",{type:"button",onClick:()=>void(W==null?void 0:W(cs[0],Xe.id)),className:"rounded-full border border-lime/30 bg-lime/[0.10] px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/[0.16]",children:Xe.label},Xe.id)),n.jsx("button",{type:"button",onClick:()=>{Z==null||Z(cs[0]??null),gn()},className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption text-secondary transition hover:bg-white/[0.1]",children:"Review in detail"})]})]}),k&&k.length>0&&n.jsx("div",{className:"space-y-1.5",children:k.map((Xe,qt)=>n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-amber-300/15 bg-amber-400/[0.05] px-3.5 py-2.5",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full bg-amber-400"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-amber-200/70",children:"Decision needed"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:Xe.title??"Pending decision"})]}),Xe.id&&Z&&n.jsx("button",{type:"button",onClick:()=>{Z(Xe.id),gn()},className:"rounded-full border border-amber-300/30 bg-amber-400/[0.10] px-2.5 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-400/[0.16]",children:"Resolve"})]},Xe.id??qt))}),et&&n.jsxs("details",{className:"group rounded-lg border border-white/[0.08] bg-black/15 px-2.5 py-2",open:!wt,children:[n.jsxs("summary",{className:"cursor-pointer list-none text-caption font-semibold text-secondary select-none",children:[V.length," evidence file",V.length===1?"":"s"]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[Ne.map((Xe,qt)=>{const Wt=Pr(Xe.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:st(Xe.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Un(Xe.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[Wt&&n.jsx("a",{href:Wt,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Open"}),n.jsx("button",{type:"button",onClick:()=>void Jt(`${st(Xe.key)} path`,Xe.path),className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Copy"})]})]},`${Xe.key}:${Xe.path}:${qt}`)}),Ze.length>0&&Ze.map((Xe,qt)=>{const Wt=Pr(Xe.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:st(Xe.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Un(Xe.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[Wt&&n.jsx("a",{href:Wt,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Open"}),n.jsx("button",{type:"button",onClick:()=>void Jt(`${st(Xe.key)} path`,Xe.path),className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Copy"})]})]},`${Xe.key}:${Xe.path}:overflow:${qt}`)})]})]})]})]})})(),G&&(ut||(se==null?void 0:se.logPath)||A)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),G&&(ut||(se==null?void 0:se.logPath)||(se==null?void 0:se.outputPath)||(P==null?void 0:P.initiativeId)||(P==null?void 0:P.workstreamId))&&n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"flex cursor-pointer items-center gap-1.5 px-1 text-micro font-semibold uppercase tracking-wider text-muted select-none",children:[n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"transition-transform group-open:rotate-90",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),"Technical"]}),n.jsxs("div",{className:"mt-3 space-y-3 text-caption",children:[ut&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[ut.domain&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Domain"}),n.jsx("div",{className:"mt-0.5 text-primary",children:st(ut.domain)})]}),(ut.provider||ut.model)&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model"}),n.jsxs("div",{className:"mt-0.5 text-primary",children:[ut.provider?`${st(ut.provider)} · `:"",ut.model?Hi(ut.model):"—"]})]}),ut.modelTier&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model tier"}),n.jsx("div",{className:"mt-0.5 text-primary",children:st(ut.modelTier)})]}),ut.pluginVersion&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Plugin"}),n.jsxs("div",{className:"mt-0.5 text-primary",children:["v",ut.pluginVersion]})]})]}),(ut==null?void 0:ut.skillPack)&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-1",children:[n.jsx("span",{className:"text-micro text-muted",children:"Skill pack"}),n.jsxs("span",{className:"text-primary",children:[ut.skillPack.name??"—",ut.skillPack.version?`@${ut.skillPack.version}`:"",ut.skillPack.source?` · ${ut.skillPack.source}`:""]}),ut.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var m;return void Jt("Skill pack checksum",((m=ut.skillPack)==null?void 0:m.checksum)??"")},className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:["sha ",ut.skillPack.checksum.slice(0,12)]})]}),ut&&ut.requiredSkills.length>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-1",children:[n.jsx("span",{className:"text-micro text-muted",children:"Skills"}),ut.requiredSkills.map(m=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:m},m))]}),(ut==null?void 0:ut.kickoffContextHash)&&n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-micro text-muted",children:"Kickoff context"})," ",n.jsxs("span",{className:"font-mono text-muted",children:[ut.kickoffContextSource?`${ut.kickoffContextSource} · `:"",ut.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void Jt("Kickoff context hash",ut.kickoffContextHash??""),className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),((se==null?void 0:se.logPath)||(se==null?void 0:se.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(se==null?void 0:se.logPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["log: ",Un(se.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void Jt("Log path",(se==null?void 0:se.logPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),(se==null?void 0:se.outputPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["output: ",Un(se.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void Jt("Output path",(se==null?void 0:se.outputPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]})]}),((P==null?void 0:P.initiativeId)||(P==null?void 0:P.workstreamId))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(P==null?void 0:P.initiativeId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["initiative: ",Is(P.initiativeId)]}),(P==null?void 0:P.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",Is(P.workstreamId)]})]})]})]}),G&&A&&n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"flex cursor-pointer items-center gap-1.5 px-1 text-micro font-semibold uppercase tracking-wider text-muted select-none",children:[n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"transition-transform group-open:rotate-90",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),"Raw metadata"]}),n.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-muted",children:A})]})]})},C.item.id)})}),n.jsx("div",{className:"border-t border-subtle px-5 py-2.5 text-caption text-muted sm:px-6",children:"Keyboard: ← previous · → next · Esc close"})]})})]})})}),bg=o.lazy(async()=>({default:(await un(()=>import("./CaAkScfa.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))).MissionControlView})),vg=o.lazy(async()=>({default:(await un(()=>import("./uNGpYMSH.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13]))).SessionInspector})),wg=o.lazy(async()=>({default:(await un(()=>import("./D2G51wQm.js"),__vite__mapDeps([16,1,8,5,15,2,10,11,12,13]))).DecisionQueue})),kg=o.lazy(()=>un(()=>import("./CSlBSRyv.js"),__vite__mapDeps([17,1,5])).then(e=>({default:e.TriageQueue}))),Ig=o.lazy(()=>un(()=>import("./C-MOJWHs.js"),__vite__mapDeps([18,1,5])).then(e=>({default:e.TriageDetailModal}))),Ng=o.lazy(async()=>({default:(await un(()=>import("./BUvcp_7V.js").then(t=>t.a),__vite__mapDeps([3,1,4,5,6]))).NextUpPanel})),jg=o.lazy(async()=>({default:(await un(()=>import("./Ck5KlsPN.js"),__vite__mapDeps([19,1,2,5,9,10,11,12,13]))).SettingsModal})),Ag=o.lazy(async()=>({default:(await un(()=>import("./BoDhb8_y.js"),__vite__mapDeps([20,1,2,5,10,11,12,13]))).BulkSessionsModal})),_g=o.lazy(async()=>({default:(await un(()=>import("./_zpQCpjm.js"),__vite__mapDeps([21,1,16,8,5,15,2,10,11,12,13]))).BulkDecisionsModal})),Sg=o.lazy(async()=>({default:(await un(()=>import("./CV0sWMbv.js"),__vite__mapDeps([22,1,2,5,10,11,12,13]))).BulkOutboxModal})),Cg=o.lazy(async()=>({default:(await un(()=>import("./B014hrCe.js"),__vite__mapDeps([23,1,2,5,10,11,12,13]))).BulkHandoffsModal})),Tg=o.lazy(async()=>({default:(await un(()=>import("./Dm0CfDGr.js"),__vite__mapDeps([24,1,2,4,5,10,11,12,13]))).ArtifactViewerModal})),Mg=o.lazy(async()=>({default:(await un(()=>import("./Bqk_l0k6.js"),__vite__mapDeps([25,1,8,5,7,6,2,10,11,12,13]))).SliceDetailModal})),Eg=o.lazy(async()=>({default:(await un(()=>import("./BYb6DARX.js"),__vite__mapDeps([26,1,2,5,10,11,12,13]))).RealtimeOrchestratorModal})),$l={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},Rg={connected:M.lime,reconnecting:M.amber,disconnected:M.red},Sa="orgx.demo_mode",Ca="orgx.dev_mode",Ta="orgx.show_synthetic_entities",Ua="orgx.selected_workspace_id",Pl={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},Fl=new Set(["running","active","queued","pending","in_progress","working","planning"]),Lg=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function pn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Dg(e){const t=pn(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function $g(e,t=220){const s=e.split("|").map(a=>a.trim()).filter(Boolean).map(a=>a.replace(/^[^:]+:\s*/,"").trim()),r=Array.from(new Set(s.length>0?s:[e.trim()])).slice(0,2).join(" ");return r.length<=t?r:`${r.slice(0,t-1).trimEnd()}…`}function Pg(e){const t=e.trim().toLowerCase();if(t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("signal is aborted"))return{title:"Live sync delayed",message:"OrgX Live is responding slowly. Initiatives and Next Up may look empty until sync recovers.",action:"refresh"};if(t.includes("unauthorized")||t.includes("forbidden")||t.includes("api key")||t.includes("auth"))return{title:"OrgX auth required",message:"Reconnect your OrgX API key in Settings to restore live initiatives, activity, and Next Up.",action:"settings"};if(t.includes("unknown api endpoint")||t.includes("missing required live routes")||t.includes("runtime is missing required live routes"))return{title:"Plugin update required",message:"This runtime is missing required live routes. Restart the plugin and update to the latest build.",action:"settings"};const s=Xt(e);return{title:"Live stream degraded",message:$g(s),action:"settings"}}function _r(e){if(e.runId&&e.runId.trim().length>0)return e.runId.trim();if(!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata))return null;const t=e.metadata,s=["runId","run_id","sessionId","session_id","agentRunId"];for(const i of s){const r=t[i];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function Ol(e){const t=e.sliceRunId;if(typeof t=="string"&&t.trim().length>0)return t.trim();if(!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata))return null;const s=e.metadata,i=["sliceRunId","slice_run_id","sliceId","slice_id","sliceRun","slice_run"];for(const r of i){const a=s[r];if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function ql(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function Bl(e,t){if(!e)return null;for(const s of t){const i=e[s];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function Ma(e,t){const s=Pl[e.status]??99,i=Pl[t.status]??99;return s!==i?s-i:pn(e.updatedAt??e.lastEventAt??e.startedAt)-pn(t.updatedAt??t.lastEventAt??t.startedAt)}function zl(e,t=null){if(!Array.isArray(e)||e.length===0)return null;const s=i=>i.find(r=>r.queueState!=="blocked"&&r.queueState!=="running")??i.find(r=>r.queueState!=="blocked")??null;if(t&&t.trim().length>0){const i=e.filter(a=>a.initiativeId===t),r=s(i);if(r)return r}return s(e)}function Ul(e){var i;const t=((i=e.autoContinue)==null?void 0:i.updatedAt)??e.updatedAt??null;if(!t)return 0;const s=Date.parse(t);return Number.isFinite(s)?s:0}function Fg(e){const t=e.toLowerCase();return t==="blocked"||t==="failed"?"blocked":t==="running"||t==="active"||t==="in_progress"?"working":t==="pending"||t==="queued"?"waiting":t==="completed"||t==="done"?"done":"idle"}function Og(e){if(Xs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function qg(e){if(Xs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Bg(e){const t=e.metadata;return t==null||typeof t!="object"?!1:t.mock===!0}function zg(e){return Lg.test(e)}function Sr(e,t){for(const s of t){const i=e[s];if(typeof i!="string")continue;const r=i.trim();if(r.length>0)return r}return null}function Ug(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Wg(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function Hg(e){const t=e.get("workspace_id")??e.get("workspaceId")??e.get("command_center_id")??e.get("commandCenterId")??e.get("project_id")??e.get("projectId")??e.get("center");return!t||t.trim().length===0?null:t.trim()}function Kg(e,t){_s(e,t)}function Vg(e){e.delete("workspace_id"),e.delete("workspaceId"),e.delete("command_center_id"),e.delete("commandCenterId"),e.delete("project_id"),e.delete("projectId"),e.delete("center")}function Gg(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=Hg(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(Ua);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function Xg(){const e=Nu();return e.showGate?n.jsx(xm,{state:e.state,isLoading:e.isLoading,isStarting:e.isStarting,isSubmittingManual:e.isSubmittingManual,onRefresh:e.refreshStatus,onStartPairing:e.startPairing,onSubmitManualKey:e.submitManualKey,onBackToPairing:e.backToPairing,onUseManualKey:e.setManualMode,onSkip:e.skipGate}):n.jsx(Rp,{children:n.jsx(ex,{onboarding:e})})}function Qg(e){const t=e.toLowerCase();return/market|email|campaign|content|brand/.test(t)?"Marketing":/product|feature|ux|discovery/.test(t)?"Product":/engineer|infra|platform|api|backend|frontend|dev/.test(t)?"Engineering":"Program"}function Yg(e){return e==="Marketing"?["Brief","Draft","Review","Ship"]:e==="Engineering"?["Spec","Dev","QA","Deploy"]:e==="Product"?["Brief","Define","Build","Ship"]:["Plan","Build","Review","Ship"]}function Wl(e){const t=(e??"").trim().toLowerCase();return t?t==="critical"||t==="p0"||t==="urgent"?0:t==="high"||t==="p1"?1:t==="medium"||t==="normal"||t==="p2"?2:t==="low"||t==="p3"?3:4:4}function Hl(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Jg(){return n.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center rounded-lg border border-strong bg-white/[0.04] p-0.5",children:n.jsx("img",{src:Gr,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function Zg(){const{state:e}=bc();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Tg,{})}):null}function ex({onboarding:e}){const[t,s]=o.useState(()=>{if(typeof window>"u")return!1;if(new URLSearchParams(window.location.search).get("demo")==="1")return!0;try{return window.localStorage.getItem(Sa)==="1"}catch{return!1}}),[i,r]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ta)==="1"}catch{return!1}}),[a,l]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ca)==="1"}catch{return!1}}),[c,d]=o.useState(()=>{if(new URLSearchParams(window.location.search).get("view")==="mission-control")return"mission-control";try{if(localStorage.getItem("orgx-dashboard-view")==="mission-control")return"mission-control"}catch{}return"activity"}),[u,p]=o.useState(()=>Gg()),x=o.useCallback(g=>{d(g);try{localStorage.setItem("orgx-dashboard-view",g)}catch{}},[]),{data:b=[]}=Gs({queryKey:["workspace-options",t?"demo":"live"],queryFn:async()=>{if(t)return[];const g=await fetch("/orgx/api/entities?type=command_center&limit=50");if(!g.ok)return[];const A=await g.json().catch(()=>null),F=Array.isArray(A==null?void 0:A.data)?A.data:[],_=[];for(const V of F){if(!V||typeof V!="object"||Array.isArray(V))continue;const Ne=Sr(V,["id"]);if(!Ne)continue;const Ze=Sr(V,["status","priority"]);if(!Ug(Ze))continue;const Oe=Sr(V,["title","name"])??(Ne.length>10?`${Ne.slice(0,8)}…`:Ne),Ie=V.is_default===!0,Ye=Wg({title:Oe,isDefault:Ie}),Re=Sr(V,["created_at"]);_.push({id:Ne,title:Ye,status:Ze,isDefault:Ie,createdAt:Re})}return _.sort((V,Ne)=>{if(V.isDefault!==Ne.isDefault)return V.isDefault?-1:1;const Ze=pn(V.createdAt)-pn(Ne.createdAt);return Ze!==0?Ze:V.title.localeCompare(Ne.title)}),_},staleTime:6e4}),h=o.useMemo(()=>{var g;return u?((g=b.find(A=>A.id===u))==null?void 0:g.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,b]),I=o.useMemo(()=>!u||b.some(g=>g.id===u)?b:[{id:u,title:h,status:null,isDefault:!1,createdAt:null},...b],[u,h,b]);o.useEffect(()=>{u&&b.length!==0&&(b.some(g=>g.id===u)||p(null))},[u,b]),t||e.state.hasApiKey&&e.state.connectionVerified;const y=o.useMemo(()=>c==="mission-control"?{maxSessions:240,maxActivityItems:120,maxHandoffs:60,maxDecisions:80,batchWindowMs:140}:{maxSessions:320,maxActivityItems:80,maxHandoffs:80,maxDecisions:80,batchWindowMs:120},[c]),{data:j,isLoading:w,error:N,refetch:f,approveDecision:T,rejectDecision:X,approveAllDecisions:Z,bulkDecisionAction:W,decisionMutation:ke}=Jd({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...y}),D=t||i,E=o.useMemo(()=>D?j.sessions.nodes:j.sessions.nodes.filter(g=>!Og(g)),[j.sessions.nodes,D]),de=o.useMemo(()=>j.activity.filter(g=>!(!D&&qg(g)||!a&&Bg(g))),[j.activity,D,a]),ie=j.connection==="connected"||j.decisions.length>0,[we,ae]=o.useState(null),[ze,pe]=o.useState(!1),[le,te]=o.useState(null),[ne,Ce]=o.useState(null),[G,R]=o.useState(null),[z,B]=o.useState(null),[K,re]=o.useState("24h"),[ge,Se]=o.useState({startIso:null,endIso:null}),oe=o.useRef(new Set),[ye,me]=o.useState(null),[O,U]=o.useState(null),[Y,ce]=o.useState(null),[qe,We]=o.useState(null),Fe=o.useRef(null),L=o.useCallback(g=>{Fe.current&&clearTimeout(Fe.current),We(g),Fe.current=setTimeout(()=>We(null),4e3)},[]),[ct,Me]=o.useState(!1),[Qe,St]=o.useState(!1),[zt,Mt]=o.useState([]),q=o.useRef(null),_e=o.useRef(null),[be,Le]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[tt,at]=o.useState(!1),[J,Ue]=o.useState(null),[je,Q]=o.useState("activity"),[Ee,nt]=o.useState("initiatives"),[Te,lt]=o.useState("next_up"),ht=o.useCallback(g=>{if(Q(g),g==="initiatives"){nt("initiatives"),lt("next_up");return}g==="decisions"&&(nt("initiatives"),lt("in_progress"),Ft("needs_attention"))},[]),[Rt,Ft]=o.useState("all"),H=o.useMemo(()=>Array.isArray(j.sliceRuns)?j.sliceRuns:[],[j.sliceRuns]),Ve=o.useMemo(()=>hc({sessions:E,sliceRuns:H}),[H,E]).length,Je=o.useMemo(()=>gc(H),[H]),He=Je.length+(ie?j.decisions.length:0),Ge=o.useMemo(()=>{var V,Ne,Ze,Oe;const g=H.filter(Ie=>{const Ye=nn(Ie.status);return Ye==="completed"||Ye==="archived"});if(g.length===0)return[];const A=new Map;for(const Ie of E){const Ye=(V=Ie.runId)==null?void 0:V.trim();Ye&&!A.has(Ye)&&A.set(Ye,Ie);const Re=(Ne=Ie.id)==null?void 0:Ne.trim();Re&&!A.has(Re)&&A.set(Re,Ie)}const F=new Map;for(const Ie of E){const Ye=(Ze=Ie.initiativeId)==null?void 0:Ze.trim(),Re=(Oe=Ie.groupLabel)==null?void 0:Oe.trim();!Ye||!Re||F.has(Ye)||F.set(Ye,Re)}const _=[];for(const Ie of g){const Ye=(Ie.runId??Ie.sliceRunId??"").trim();if(!Ye)continue;const Re=A.get(Ye)??A.get(Ie.sliceRunId)??null,gn=Ie.initiativeId??(Re==null?void 0:Re.initiativeId)??null,$s=de.filter(Bn=>{const Jt=_r(Bn),Qn=Ol(Bn);return!!(Jt&&(Jt===Ye||Jt===Ie.sliceRunId)||Qn&&Qn===Ie.sliceRunId)}).sort((Bn,Jt)=>pn(Bn.timestamp)-pn(Jt.timestamp));_.push({key:`completed:${Ie.sliceRunId}`,runId:Ye,title:Ie.workstreamTitle??(Re==null?void 0:Re.title)??`Completed slice ${Ie.sliceRunId.slice(0,8)}`,statusExplainer:Ie.statusExplainer??Ie.lastEventSummary??(Re==null?void 0:Re.lastEventSummary)??null,initiativeTitle:gn?F.get(gn)??gn:null,workstreamTitle:Ie.workstreamTitle??(Re==null?void 0:Re.title)??null,scope:Ie.scope??null,taskIds:Array.isArray(Ie.taskIds)?Ie.taskIds:[],milestoneIds:Array.isArray(Ie.milestoneIds)?Ie.milestoneIds:[],artifacts:Array.isArray(Ie.artifacts)?Ie.artifacts:[],artifactCount:Ie.artifactCount??0,completedAt:Ie.completedAt??Ie.updatedAt??Ie.lastEventAt??(Re==null?void 0:Re.updatedAt)??(Re==null?void 0:Re.lastEventAt)??null,timelineEvents:$s})}return _.sort((Ie,Ye)=>pn(Ye.completedAt)-pn(Ie.completedAt)),_},[H,de,E]),Ke=Ge.length,[gt,Lt]=o.useState(null),bt=o.useCallback(g=>{const A=H.find(F=>F.initiativeId===g.initiativeId&&F.workstreamId===g.workstreamId)??null;Lt({source:"queue",item:g,linkedSliceRun:A})},[H]),Ct=o.useCallback((g,A)=>{Lt({source:"in_progress",row:g,sliceRun:A})},[]),Et=o.useCallback(g=>{Lt({source:"needs_input",sliceRun:g})},[]),Vt=o.useCallback(async(g,A)=>{L("Slice accepted and marked complete."),f()},[f,L]),Qt=o.useCallback(async(g,A)=>{L("Changes requested — feedback posted.")},[L]),ot=o.useCallback(async(g,A,F)=>{await T(g,{optionId:A,...F?{note:F}:{}}),L("Decision resolved.")},[T,L]),dt=Wu({projectId:u,limit:40,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:j.snapshotVersion}),rn=Ku({authToken:null,embedMode:!1}),{model:an,actions:ln}=Xu({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),Dt=o.useMemo(()=>an.items.filter(g=>g.kind==="failure_diagnostic"),[an.items]),Ot=o.useMemo(()=>({...an,items:Dt,total:Dt.length}),[Dt,an]),[Hn,Gt]=o.useState(null),[Pn,fs]=o.useState(0),Qs=o.useCallback(g=>{Gt(g);const A=Dt.findIndex(F=>F.id===g.id);fs(A>=0?A:0)},[Dt]),Ss=o.useCallback(g=>{if(Dt.length===0)return;const A=(Pn+g+Dt.length)%Dt.length;fs(A),Gt(Dt[A]??null)},[Pn,Dt]),Kn=dt,fn=o.useMemo(()=>{var V;const g=dt.items.filter(Ne=>Ne.autoContinue);if(g.length===0)return null;const A=[...g].sort((Ne,Ze)=>Ul(Ze)-Ul(Ne)),F=A.find(Ne=>{var Ze,Oe;return((Ze=Ne.autoContinue)==null?void 0:Ze.status)==="running"||((Oe=Ne.autoContinue)==null?void 0:Oe.status)==="stopping"})??null;if(F)return{item:F,state:((V=F.autoContinue)==null?void 0:V.status)==="stopping"?"stopping":"running"};const _=A.find(Ne=>{var Ze,Oe;return((Ze=Ne.autoContinue)==null?void 0:Ze.stopReason)==="blocked"||((Oe=Ne.autoContinue)==null?void 0:Oe.stopReason)==="error"})??null;return _?{item:_,state:"blocked"}:null},[dt.items]),on=(fn==null?void 0:fn.item)??null,mn=(fn==null?void 0:fn.state)??"idle",bn=mn==="running"||mn==="stopping",Zn=mn==="blocked"?"blocked":bn?"active":"idle",Cs=mn==="blocked"?"Hold":bn?"On":"Off",es=mn==="blocked"?"Resolve blockers, then resume autopilot":bn?"Stop autopilot":"Start autopilot",Ts=mn==="blocked"?"amber":"teal",hs=o.useMemo(()=>{var g,A;return on?{state:mn,reason:((g=on.autoContinue)==null?void 0:g.stopReason)??on.blockReason??null,activeRunId:((A=on.autoContinue)==null?void 0:A.activeRunId)??null,activeWorkstreamTitle:on.workstreamTitle??null}:null},[on,mn]);o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(Sa,"1"):window.localStorage.removeItem(Sa)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{i?window.localStorage.setItem(Ta,"1"):window.localStorage.removeItem(Ta)}catch{}},[i]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(Ca,"1"):window.localStorage.removeItem(Ca)}catch{}},[a]),o.useEffect(()=>{a||at(!1)},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(Ua,u):window.localStorage.removeItem(Ua)}catch{}try{const g=new URL(window.location.href);u?Kg(g.searchParams,u):Vg(g.searchParams),g.searchParams.delete("initiative"),g.searchParams.delete("initiative_id"),g.searchParams.delete("project"),window.history.replaceState(null,"",`${g.pathname}${g.search}${g.hash}`)}catch{}}},[u]);const hn=o.useCallback((g,A)=>{Le(F=>({open:!0,tab:g??F.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),Ys=o.useCallback(g=>{if(s(g),!(typeof window>"u"))try{const A=new URL(window.location.href);g?A.searchParams.set("demo","1"):A.searchParams.delete("demo"),window.history.replaceState(null,"",`${A.pathname}${A.search}${A.hash}`)}catch{}},[]),$=o.useCallback(()=>{hn("orgx")},[hn]),xe=o.useCallback(()=>{un(()=>import("./CaAkScfa.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))},[]),{data:ve}=xc(c==="mission-control",u),{data:De}=Ep(c==="mission-control",u),{data:Nt=[]}=Gs({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[xt,pt]=o.useState(null),[In,ts]=o.useState(""),[ns,cn]=o.useState(!1),Yt=o.useCallback((g,A)=>{pt({type:g,initiativeId:A}),ts(""),cn(!1)},[]),ss=o.useCallback(()=>{pt(null),ts(""),cn(!1)},[]),$t=o.useCallback(()=>{Ce(null)},[]),Ms=o.useCallback(()=>{R(null),B(null)},[]),Es=o.useCallback(()=>{ce(null)},[]);o.useEffect(()=>{var F;const g=((F=E[0])==null?void 0:F.id)??null;if(!g){we!==null&&ae(null);return}if(we===null){ae(g);return}E.some(_=>_.id===we)||ae(g)},[E,we]),o.useEffect(()=>{if(!ne)return;E.some(A=>A.id===ne)||Ce(null)},[ne,E]);const jt=o.useCallback(g=>{un(()=>import("./uNGpYMSH.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),ae(g),pe(!0),te(null),Ce(g),R(null),B(null)},[]),vn=o.useCallback(g=>{un(()=>import("./uNGpYMSH.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),ae(g.id),pe(!0),Ce(g.id),R(g.workstreamId??null),B(g.title),te({workstreamId:g.workstreamId??null,text:`Intervention requested for "${g.title}". `}),L(`Opened intervention composer for ${g.title}.`)},[]),Fn=o.useCallback(g=>{const A=g.trim();if(!A)return;const F=E.find(_=>_.runId===A||_.id===A)??null;if(!F){L("Session not found — it may have ended or not started yet.");return}jt(F.id),L(`Focused session: ${F.title}`)},[E,jt,L]),Ji=o.useCallback(g=>{var _;const A=(_=g.id)==null?void 0:_.trim();if(!A)return;const F=_r(g);if(F){const V=E.find(Ne=>Ne.runId===F||Ne.id===F)??null;V&&(ae(V.id),Ce(V.id))}x("activity"),Q("activity"),pe(!1),me(A),L("Opened activity detail from session timeline.")},[E,x]),Ut=o.useMemo(()=>E.find(g=>g.id===ne)??null,[ne,E]),is=o.useMemo(()=>{var F,_;const g=((F=Ut==null?void 0:Ut.runId)==null?void 0:F.trim())??"",A=((_=Ut==null?void 0:Ut.id)==null?void 0:_.trim())??"";return!g||!A?[]:g===A?[g]:[g,A]},[Ut==null?void 0:Ut.id,Ut==null?void 0:Ut.runId]),yi=o.useMemo(()=>{const g=new Set;for(const A of is){const F=A.trim();F.length>0&&g.add(F)}return g},[is]),bi=o.useMemo(()=>{const g=new Map;for(const A of E){const F=A.workstreamId??null;A.runId&&g.set(A.runId,F),A.id&&g.set(A.id,F)}return g},[E]),gs=o.useMemo(()=>{const g=is.length>0?is.join("|"):"*",A=(G==null?void 0:G.trim())||"*",F=(Y==null?void 0:Y.trim())||"*";return`${g}::${A}::${F}`},[G,Y,is]),Jr=o.useCallback(g=>{oe.current.add(gs),re(g)},[gs]);o.useEffect(()=>{if(oe.current.has(gs)||w)return;const g=Date.now(),A=de.filter(V=>{const Ne=_r(V);if(yi.size>0&&(!Ne||!yi.has(Ne)))return!1;if(G){const Ze=ql(V);if((Bl(Ze,["workstreamId","workstream_id"])??(Ne?bi.get(Ne)??null:null))!==G)return!1}if(Y){const Ze=ql(V);if((Bl(Ze,["agentName","agent_name"])??V.agentName)!==Y)return!1}return!0});if(A.length===0)return;const _=["live","24h","7d","all"].find(V=>{const Ne=Qi(V,g);return A.some(Ze=>{const Oe=pn(Ze.timestamp);return Oe?Ne===null||Oe>=Ne:!1})})??"all";oe.current.add(gs),_!==K&&re(_)},[G,de,gs,K,bi,Y,w,yi]);const Js=cu({seed:de,timeFilterId:K,customSinceIso:K==="custom"?ge.startIso:null,customUntilIso:K==="custom"?ge.endIso:null,runId:(Ut==null?void 0:Ut.runId)??null,projectId:u,pageSize:50,demoMode:t}),dn=o.useMemo(()=>E.find(g=>g.id===we)??null,[E,we]),Tn=o.useMemo(()=>E.filter(g=>Fl.has(g.status)).length,[E]),rs=o.useMemo(()=>H.length>0?Je.length:E.filter(g=>{const A=nn(g.status),F=nn(g.phase??""),_=nn(g.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||F==="blocked"||_==="error"?!0:Fl.has(A)||A==="handoff"||A==="review"?!1:g.blockers.length>0}).length,[H.length,Je.length,E]);o.useMemo(()=>E.filter(g=>g.status==="failed").length,[E]);const Rs=o.useMemo(()=>E.filter(g=>g.status==="completed").length,[E]);o.useMemo(()=>{const g=(ie?j.decisions.length:0)+rs;return[{id:"active",label:"Running",value:Tn,color:Tn>0?M.lime:M.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:g,color:g>0?M.amber:M.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:Rs,color:M.teal,icon:"session"}]},[Tn,rs,Rs,j.decisions.length,E,ie]),o.useMemo(()=>j.decisions.length>0?Math.max(0,...j.decisions.map(g=>g.waitingMinutes)):0,[j.decisions]);const Mn=o.useMemo(()=>N?Pg(N):null,[N]),xs=o.useMemo(()=>{const g=[];if(Mn){const A=Mn.action==="refresh"&&typeof f=="function";g.push({id:`stream-error:${N}`,kind:"error",icon:"notification",title:Mn.title,message:Mn.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void f():()=>hn("orgx")})}return j.connection!=="connected"&&g.push({id:`connection:${j.connection}`,kind:j.connection==="disconnected"?"error":"info",icon:"notification",title:j.connection==="disconnected"?"Connection lost":"Reconnecting",message:j.connection==="disconnected"?"Live connection is offline. Initiatives and Next Up may stay stale until reconnect.":"Live connection is recovering. Fresh updates will resume automatically.",actionLabel:"Reconnect",onAction:$}),qe&&g.push({id:`ops:${qe}`,kind:"info",icon:/decision/i.test(qe)?"decision":"workstream",title:"Update",message:qe}),g},[j.connection,j.outbox.lastReplayError,j.outbox.pendingTotal,j.outbox.replayStatus,N,Mn,$,f,hn,qe]);o.useEffect(()=>{const g=new Set(xs.map(A=>A.id));Mt(A=>A.filter(F=>g.has(F)))},[xs]);const as=o.useMemo(()=>xs.filter(g=>!zt.includes(g.id)),[zt,xs]),vi=ie?j.decisions.length:0,Zi=Tn+rs+vi,wi=o.useCallback(g=>{Mt(A=>A.includes(g)?A:A.concat(g))},[]),Vn=o.useCallback(()=>{Mt(xs.map(g=>g.id))},[xs]);o.useEffect(()=>{if(!Qe)return;const g=F=>{var V,Ne;const _=F.target;_&&((V=_e.current)!=null&&V.contains(_)||(Ne=q.current)!=null&&Ne.contains(_)||St(!1))},A=F=>{F.key==="Escape"&&St(!1)};return document.addEventListener("mousedown",g),document.addEventListener("touchstart",g),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("touchstart",g),document.removeEventListener("keydown",A)}},[Qe]);const C=o.useMemo(()=>{var F;const g=new Map;for(const _ of E){const V=_.initiativeId??_.groupId??"unscoped",Ne=_.groupLabel&&_.groupLabel.trim().length>0?_.groupLabel:_.initiativeId??"Unscoped Initiative",Ze=Qg(Ne),Oe=g.get(V)??{id:V,name:Ne,category:Ze,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(_.progress!==null&&(Oe.progressTotal+=_.progress,Oe.progressCount+=1),Oe.statusCounts[_.status]=(Oe.statusCounts[_.status]??0)+1,_.agentName&&(Oe.allAgents.add(_.agentName),["running","queued","pending","blocked"].includes(_.status)&&Oe.activeAgents.add(_.agentName)),_.workstreamId){const Ie=j.sessions.groups.find(Re=>Re.id===_.workstreamId),Ye=((F=Ie==null?void 0:Ie.label)==null?void 0:F.trim())||_.workstreamId;Oe.workstreams.set(_.workstreamId,Ye)}Oe.latestEpoch=Math.max(Oe.latestEpoch,pn(_.updatedAt??_.lastEventAt??_.startedAt)),g.set(V,Oe)}const A=[];for(const _ of g.values()){const V=_.progressCount>0?Math.round(_.progressTotal/_.progressCount):_.statusCounts.completed?100:_.statusCounts.running?55:0,Ne=_.category,Ze=Yg(Ne),Oe=Math.round(Math.max(0,Math.min(100,V))/100*(Ze.length-1)),Ie=(_.statusCounts.blocked??0)>0,Ye=(_.statusCounts.completed??0)>0&&(_.statusCounts.running??0)===0&&(_.statusCounts.queued??0)===0&&(_.statusCounts.pending??0)===0&&(_.statusCounts.blocked??0)===0&&(_.statusCounts.paused??0)===0,Re=!Ye&&!Ie&&(_.statusCounts.paused??0)>0&&(_.statusCounts.running??0)===0&&(_.statusCounts.queued??0)===0&&(_.statusCounts.pending??0)===0,gn=(_.statusCounts.running??0)+(_.statusCounts.active??0)+(_.statusCounts.in_progress??0),$s=(_.statusCounts.queued??0)+(_.statusCounts.pending??0),Bn=_.workstreams.size,Jt=`${Bn} workstream${Bn===1?"":"s"}`,Qn=Bn===0?"No workstreams linked yet.":Ye?`${Jt} completed.`:Ie?`${Jt} linked · resolve blockers to continue.`:Re?`${Jt} linked · initiative is paused.`:gn>0?`${gn} workstream${gn===1?"":"s"} active right now.`:$s>0?`${$s} workstream${$s===1?"":"s"} queued to start.`:`${Jt} linked · ready to run.`,ni=Ze.map((Ps,si)=>{let Fs="upcoming";return(Ye||si<Oe)&&(Fs="completed"),si===Oe&&!Ye&&(Fs=Ie?"warning":"current"),{name:Ps,status:Fs}});A.push({id:_.id,name:_.name,status:Ye?"completed":Ie?"blocked":Re?"paused":"active",rawStatus:Ye?"completed":Ie?"blocked":Re?"paused":"active",category:Ne,health:Math.max(0,Math.min(100,V)),phases:ni,currentPhase:Ye?Ze.length-1:Oe,daysRemaining:0,targetDate:null,createdAt:_.latestEpoch>0?new Date(_.latestEpoch).toISOString():null,updatedAt:_.latestEpoch>0?new Date(_.latestEpoch).toISOString():null,activeAgents:_.activeAgents.size,totalAgents:_.allAgents.size,avatars:Array.from(_.activeAgents).slice(0,3),description:Qn,workstreams:Array.from(_.workstreams.entries()).map(([Ps,si])=>({id:Ps,name:si,status:"active"}))})}return A.sort((_,V)=>{const Ne=_.status==="blocked"?0:_.status==="active"?1:2,Ze=V.status==="blocked"?0:V.status==="active"?1:2;return Ne!==Ze?Ne-Ze:V.health-_.health})},[E,j.sessions.groups]),ys=o.useMemo(()=>{const g=(_,V)=>{var Oe,Ie;const Ne=typeof V.description=="string"&&V.description.trim().length>0?V.description:null,Ze=typeof _.description=="string"&&_.description.trim().length>0?_.description:null;return{..._,...V,health:V.health>0?V.health:_.health,activeAgents:Math.max(_.activeAgents,V.activeAgents),totalAgents:Math.max(_.totalAgents,V.totalAgents),avatars:(Oe=_.avatars)!=null&&Oe.length?_.avatars:V.avatars,workstreams:(Ie=_.workstreams)!=null&&Ie.length?_.workstreams:V.workstreams,description:Ne??Ze??void 0,rawStatus:V.rawStatus??_.rawStatus??null,targetDate:V.targetDate??_.targetDate??null,createdAt:V.createdAt??_.createdAt??null,updatedAt:V.updatedAt??_.updatedAt??null}},A=new Map;for(const _ of C)A.set(_.id,_);for(const _ of[...De??[],...ve??[]]){if(!D&&Xs(_.id)){A.delete(_.id);continue}const V=_.rawStatus??_.status;if(!Hl(V)){A.delete(_.id);continue}const Ne=A.get(_.id);A.set(_.id,Ne?g(Ne,_):_)}const F=new Set(Nt);return Array.from(A.values()).filter(_=>!F.has(_.id)).filter(_=>Hl(_.rawStatus??_.status)).sort((_,V)=>{const Ne=Re=>Re==="blocked"?0:Re==="active"?1:Re==="paused"?2:3,Ze=Ne(_.status)-Ne(V.status);if(Ze!==0)return Ze;const Oe=Wl(_.priority)-Wl(V.priority);if(Oe!==0)return Oe;const Ie=pn(V.updatedAt)-pn(_.updatedAt);if(Ie!==0)return Ie;const Ye=V.health-_.health;return Ye!==0?Ye:_.name.localeCompare(V.name)})},[C,ve,D,De,Nt]),er=o.useMemo(()=>{const g={};for(const A of ys)A.id&&A.name&&(g[A.id]=A.name);return g},[ys]),os=o.useMemo(()=>{if(!Ut)return null;const g=Ut.agentName,A=Ut.title;if(g){const F=de.find(_=>{var V;return _.runId===Ut.runId&&((V=_.summary)==null?void 0:V.trim())});if(F!=null&&F.summary){const _=F.summary.trim().length>40?F.summary.trim().slice(0,40)+"…":F.summary.trim();return`${g}: ${_}`}return g}if(A){const F=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(F.length>0)return F}return A??null},[de,Ut]),En=o.useMemo(()=>{const g=new Map;for(const A of E){const F=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,_=(A.agentName??"").trim()||(A.agentId??"").trim();if(!_)continue;const V=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),Ne=pn(V),Ze=Ne?Math.max(0,Math.floor((Date.now()-Ne)/6e4)):0,Oe=g.get(F),Ie={id:F,name:_,role:"Agent",status:Fg(A.status),task:A.title??null,progress:A.progress??null,lastActive:V,lastActiveMinutes:Ze};(!Oe||pn(Ie.lastActive)>pn(Oe.lastActive))&&g.set(F,Ie)}return Array.from(g.values())},[E]),Zs=o.useCallback(async()=>{if(E.length===0){L("No sessions available to continue.");return}const g=[...E].sort(Ma)[0];if(ae(g.id),Ce(g.id),R(null),B(null),["blocked","pending","queued"].includes(g.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(g.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})})}catch{}L(`Focused highest priority session: ${g.title}`),await f()},[E,f]),On=o.useCallback(async(g,A)=>{const F=await g.json().catch(()=>null),_=typeof(F==null?void 0:F.error)=="string"&&F.error.trim()||typeof(F==null?void 0:F.message)=="string"&&F.message.trim()||`${A} (${g.status})`;return/unknown api endpoint/i.test(_)?`${A}. This route is unavailable in the running plugin build.`:Xt(_)},[]),Gn=o.useCallback((g,A)=>!g||g.trim().length===0?A:Xt(g.trim())||A,[]),it=o.useCallback(async()=>{const g=zl(dt.items);if(!g){L("No startable Next Up workstream is available."),x("mission-control");return}await dt.playWorkstream({initiativeId:g.initiativeId,workstreamId:g.workstreamId,agentId:g.runnerAgentId}),Ce(null),R(g.workstreamId),B(g.workstreamTitle),ce(null),L(`Dispatched Next Up: ${g.workstreamTitle}`),await Promise.all([dt.refetch(),f()])},[f,dt,x]),Nn=o.useCallback(async(g=null)=>{const A=zl(dt.items,g);if(!A){L("No startable initiative is ready for Autopilot yet."),x("mission-control");return}await rn.move({initiativeId:A.initiativeId,workstreamId:A.workstreamId,placement:"top"}),await dt.startWorkstreamAutoContinue({initiativeId:A.initiativeId,workstreamId:A.workstreamId,agentId:A.runnerAgentId,scope:"initiative"}),Ce(null),L(`Autopilot started for ${A.initiativeTitle}; queued from ${A.workstreamTitle}.`),await Promise.all([dt.refetch(),f()])},[f,rn,dt,x]),se=o.useCallback(async()=>{Me(!0);try{if(!on||!bn){const g=mn==="blocked"?(on==null?void 0:on.initiativeId)??null:null;await Nn(g);return}await dt.stopInitiativeAutoContinue({initiativeId:on.initiativeId}),L(`Autopilot stopped for ${on.initiativeTitle}.`),await Promise.all([dt.refetch(),f()])}finally{Me(!1)}},[bn,on,mn,f,dt,Nn]),Ls=o.useCallback(async g=>{const A=(g.initiativeId??"").trim(),F=(g.workstreamId??"").trim();if(!A||!F)throw new Error("Missing initiative/workstream metadata for this session.");const _=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:F,agentId:g.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!_.ok)throw new Error(await On(_,"Failed to dispatch workstream from In Progress"));Ce(null),R(F),B(g.title),L(`Dispatched ${g.title}.`),await Promise.all([dt.refetch(),f()])},[On,f,dt]),ls=o.useCallback(async g=>{const A=(g.initiativeId??"").trim(),F=(g.workstreamId??"").trim();if(!A||!F)throw new Error("Missing initiative/workstream metadata for this session.");const _=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:F,placement:"bottom",resetToTodo:!1})});if(!_.ok){const V=await On(_,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(V))throw new Error(V);const Ne=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!Ne.ok)throw new Error(await On(Ne,"Failed to pause workstream using legacy fallback"))}L(`Paused ${g.title} and sent it to the bottom of queue.`),await Promise.all([dt.refetch(),f()])},[On,f,dt]),Xn=o.useCallback(async g=>{const A=(g.workstreamId??"").trim();if(!A)throw new Error("This session is missing a workstream id for intervention notes.");const F=g.text.trim();if(zg(F)){hn("agents",{focusAgentDomain:"engineering"}),L("Opened agent settings for engineering runtime configuration.");return}const _=await fetch(`/orgx/api/entities/workstream/${encodeURIComponent(A)}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:F,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!_.ok)throw new Error(await On(_,"Failed to submit intervention"));L(`Intervention sent for ${g.session.title}.`),await f()},[hn,On,f]),tr=o.useCallback(async g=>{if(ae(g.id),Ce(g.id),R(null),B(null),!["running","completed","archived"].includes(g.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(g.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})})}catch{}L(`Dispatch requested: ${g.title}`),await f()},[f]),kt=o.useCallback(async(g,A,F={})=>{const _=await fetch(`/orgx/api/runs/${encodeURIComponent(g.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!_.ok){const V=await _.json().catch(()=>null);throw new Error((V==null?void 0:V.error)??`${A} failed (${_.status})`)}},[]),P=o.useCallback(async g=>{var V;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(g.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!A.ok){const Ne=await A.json().catch(()=>null);throw new Error((Ne==null?void 0:Ne.error)??`Checkpoint creation failed (${A.status})`)}const F=await A.json().catch(()=>null),_=F&&"data"in F&&((V=F.data)==null?void 0:V.id)||F&&"id"in F&&F.id||null;L(_?`Checkpoint created: ${_.slice(0,8)}`:"Checkpoint created."),await f()},[f]),Tt=o.useCallback(async g=>{await kt(g,"pause",{reason:"pause_from_dashboard"}),L(`Pause requested: ${g.title}`),await f()},[f,kt]),qn=o.useCallback(async g=>{await kt(g,"resume",{reason:"resume_from_dashboard"}),L(`Resume requested: ${g.title}`),await f()},[f,kt]),nr=o.useCallback(async g=>{await kt(g,"cancel",{reason:"restart_from_in_progress"}),await Ls(g),L(`Restarted ${g.title}.`),await f()},[Ls,f,kt]),cs=o.useCallback(async g=>{await kt(g,"cancel",{reason:"cancel_from_dashboard"}),L(`Cancel requested: ${g.title}`),await f()},[f,kt]),sr=o.useCallback(async g=>{var Ze;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(g.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const Oe=await A.json().catch(()=>null);throw new Error((Oe==null?void 0:Oe.error)??`Checkpoint list failed (${A.status})`)}const F=await A.json().catch(()=>null),Ne=(Ze=(Array.isArray(F)?F:Array.isArray(F==null?void 0:F.data)?F.data:[]).map(Oe=>({id:typeof Oe.id=="string"?Oe.id:"",createdAt:typeof Oe.createdAt=="string"?Oe.createdAt:typeof Oe.created_at=="string"?Oe.created_at:""})).filter(Oe=>Oe.id.length>0).sort((Oe,Ie)=>Date.parse(Ie.createdAt)-Date.parse(Oe.createdAt))[0])==null?void 0:Ze.id;if(!Ne)throw new Error("No checkpoint available for rollback.");await kt(g,"rollback",{checkpointId:Ne,reason:"rollback_from_dashboard"}),L(`Rollback requested for ${g.title}.`),await f()},[f,kt]),ir=o.useCallback(async()=>{var F;if(!xt||In.trim().length===0||ns)return;cn(!0);const g=xt.type,A=In.trim();try{const _={type:g,title:A,status:"active"};if(g==="workstream"){const Ne=xt.initiativeId??(dn==null?void 0:dn.initiativeId)??((F=C[0])==null?void 0:F.id)??null;if(!Ne){L("Select an initiative first to start a workstream."),cn(!1);return}_.initiative_id=Ne,_.parentId=Ne}const V=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)});if(!V.ok){const Ne=await V.json().catch(()=>null);throw new Error((Ne==null?void 0:Ne.error)??`Failed to create ${g}.`)}L(`Created ${g}: ${A}`),ss(),await f()}catch(_){L(Gn(_ instanceof Error?_.message:"",`Failed to create ${g}.`)),cn(!1)}},[ss,ns,xt,In,C,f,dn==null?void 0:dn.initiativeId]),Ds=o.useCallback(()=>{Yt("initiative")},[Yt]),ei=o.useCallback(g=>{Yt("workstream",g)},[Yt]);o.useCallback(()=>{var g;return ei((dn==null?void 0:dn.initiativeId)??((g=C[0])==null?void 0:g.id)??null)},[C,dn==null?void 0:dn.initiativeId,ei]);const ut=o.useCallback(g=>{const A=[...E].filter(F=>(F.initiativeId??F.groupId)===g.id).sort(Ma)[0];A&&(ae(A.id),Ce(A.id),R(null),B(null),L(`Focused initiative: ${g.name}`))},[E]),ki=o.useCallback(g=>{const A=C.find(F=>F.id===g)??ys.find(F=>F.id===g)??null;A&&ut(A)},[ut,C,ys]),vt=o.useCallback(g=>{const A=(g??"").trim();x("activity"),nt("initiatives"),Q("initiatives"),lt("in_progress"),Ft("needs_attention"),U(A.length>0?A:null),L(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[x]),ti=o.useCallback(g=>{const A=new Set,F=(g.runId??"").trim();F.length>0&&A.add(F),A.add(g.sliceRunId);const _=new Map;for(const Ie of de){const Ye=_r(Ie),Re=Ol(Ie);(Ye&&A.has(Ye)||Re&&Re===g.sliceRunId)&&_.set(Ie.id,Ie)}const V=Array.from(_.values()),Ne=Ie=>{const Ye=Ie.type.trim().toLowerCase();let Re=0;return(Ye==="decision_requested"||Ye==="blocker_created")&&(Re+=80),(Ye==="run_failed"||Ye==="autopilot_stopped")&&(Re+=70),(Ye.includes("slice_completed")||Ye.includes("completed"))&&(Re+=60),Ye.includes("artifact")&&(Re+=55),(Ye.includes("progress")||Ye.includes("update"))&&(Re+=35),Re+=Math.floor(pn(Ie.timestamp)/1e3),Re};V.sort((Ie,Ye)=>Ne(Ye)-Ne(Ie));const Ze=V[0]??null;x("activity"),Q("activity"),nt("initiatives");const Oe=(F?E.find(Ie=>Ie.runId===F||Ie.id===F)??null:null)??(g.initiativeId&&g.workstreamId?E.find(Ie=>Ie.initiativeId===g.initiativeId&&Ie.workstreamId===g.workstreamId)??null:null);if(Oe?(ae(Oe.id),Ce(Oe.id),R(null),B(null)):g.workstreamId&&(Ce(null),R(g.workstreamId),B(g.workstreamTitle??"Work slice")),Ze!=null&&Ze.id){me(Ze.id),L(`Reviewing activity for ${g.workstreamTitle??"work slice"}.`);return}if(g.primaryAction==="resolve_decision"){vt();return}if(F.length>0){Fn(F),L("Opened the related work session. Timeline details were unavailable.");return}L("No activity details were found for this slice yet.")},[de,Fn,vt,E,x]);return o.useCallback(g=>{const A=new Set(g),F=[...E].filter(_=>A.has(_.status)).sort(Ma)[0];if(!F){L("No matching sessions for that metric right now.");return}jt(F.id),Q("activity")},[E,jt]),o.useCallback(g=>{c==="activity"&&(g==="sessions"||g==="active"||g==="blocked"||g==="failed"||g==="decisions"||g==="outbox"||g==="handoffs")&&Ue(g)},[c]),w?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:M.background},children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-2.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"shimmer-skeleton h-6 w-6 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-28 rounded-md"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-14 rounded-full"})]}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Array.from({length:4}).map((g,A)=>n.jsx("div",{className:"shimmer-skeleton h-7 w-24 rounded-full"},A))})]}),n.jsxs("div",{className:"grid flex-1 grid-cols-1 gap-4 p-4 sm:p-5 lg:grid-cols-12",children:[n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-3"}),n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-6"}),n.jsxs("div",{className:"flex flex-col gap-4 lg:col-span-3",children:[n.jsx("div",{className:"shimmer-skeleton h-40 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton h-48 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton flex-1 rounded-2xl",style:{minHeight:160}})]})]})]}):n.jsxs("div",{className:"relative flex min-h-screen flex-col pb-[92px] lg:h-screen lg:min-h-0 lg:overflow-hidden lg:pb-0",style:{backgroundColor:M.background},children:[typeof window<"u"&&window.location.port==="5173"&&n.jsx("div",{className:"absolute left-1/2 top-4 z-30 -translate-x-1/2",children:n.jsxs("div",{className:"rounded-full border border-strong bg-white/[0.06] px-4 py-2 text-caption text-primary shadow-[0_10px_30px_rgba(0,0,0,0.35)] backdrop-blur",children:["Dev preview on 5173. Installed plugin runs on OpenClaw port"," ",n.jsx("a",{href:"http://127.0.0.1:18789/orgx/live/",className:"text-white underline underline-offset-4 hover:text-secondary",children:"18789"}),"."]})}),n.jsxs("header",{className:"relative z-[180] border-b border-subtle px-4 py-1.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2.5 lg:grid lg:grid-cols-[1fr_auto_1fr]",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[n.jsx(Jg,{}),n.jsxs("h1",{className:"text-title font-semibold tracking-tight text-white sm:text-[17px]",children:["OrgX",n.jsx("span",{className:"ml-1.5 text-secondary",children:"Live"})]}),n.jsx(ym,{color:Rg[j.connection],pulse:j.connection==="connected",title:[`Status: ${$l[j.connection]??j.connection}`,j.connection==="connected"?"Meaning: receiving live updates.":j.connection==="reconnecting"?"Meaning: retrying live stream (data may be stale).":"Meaning: offline (data is stale).",`Last snapshot: ${Dg(j.lastSnapshotAt)}`,Mn?`Details: ${Mn.message}`:null].filter(Boolean).join(`
212
+ `),children:$l[j.connection]??"Unknown"}),(Tn>0||rs>0)&&n.jsx(sl,{className:"hidden md:flex",running:Tn,blocked:rs,decisionsCount:ie?j.decisions.length:0,completedToday:Rs,onDecisionsClick:()=>{x("activity"),nt("initiatives"),Q("initiatives"),lt("in_progress"),Ft("needs_attention")},onBlockedClick:()=>{H.length>0?(x("mission-control"),lt("in_progress"),Ft("needs_attention")):Ue("blocked")},onNewInitiative:Ds})]}),n.jsx("div",{className:"hidden items-center justify-center lg:flex",children:n.jsxs("div",{className:"flex rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>x("activity"),"aria-pressed":c==="activity",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${c==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>x("mission-control"),onMouseEnter:xe,onFocus:xe,"aria-pressed":c==="mission-control",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${c==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})}),n.jsxs("div",{className:"relative isolate flex items-center justify-end gap-1.5 sm:gap-2",children:[n.jsxs("div",{className:"relative hidden md:block",children:[n.jsx("label",{htmlFor:"workspace-switcher",className:"sr-only",children:"Workspace scope"}),n.jsxs("select",{id:"workspace-switcher",value:u??"__all__",onChange:g=>{const A=g.target.value;p(A==="__all__"?null:A)},className:"control-pill h-8 min-w-[170px] appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${h}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),I.map(g=>n.jsx("option",{value:g.id,children:g.title},g.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),j.lastActivity&&n.jsxs("span",{className:"hidden text-body text-secondary xl:inline",children:["Last activity: ",j.lastActivity]}),t&&n.jsx("button",{type:"button",onClick:()=>{Ys(!1),$()},className:"hidden rounded-full border border-amber-200/25 bg-amber-200/10 px-3 py-1.5 text-caption font-semibold text-amber-100 transition-colors hover:bg-amber-200/15 sm:inline",title:"Exit demo mode",children:"Exit demo"}),n.jsxs("button",{type:"button",ref:q,onClick:()=>St(g=>!g),title:"Notifications","aria-haspopup":"dialog","aria-expanded":Qe,"aria-controls":"header-notifications-panel",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:[n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M15 17h5l-1.4-1.4a2 2 0 0 1-.6-1.4V11a6 6 0 1 0-12 0v3.2c0 .53-.21 1.04-.59 1.42L4 17h5"}),n.jsx("path",{d:"M9 17a3 3 0 0 0 6 0"})]}),as.length>0&&n.jsx("span",{className:"absolute -right-1 -top-1 inline-flex min-h-[16px] min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-micro font-semibold text-white",children:as.length})]}),a?n.jsx("button",{type:"button",onClick:()=>at(!0),title:"Realtime orchestrator",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 18a2.5 2.5 0 0 0 2.5-2.5v-7a2.5 2.5 0 1 0-5 0v7A2.5 2.5 0 0 0 12 18z"}),n.jsx("path",{d:"M6 12.5v2a6 6 0 0 0 12 0v-2"}),n.jsx("path",{d:"M12 20.5v2"})]})}):null,n.jsx("button",{type:"button",onClick:()=>hn("orgx"),title:"Settings",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z"}),n.jsx("path",{d:"M19.4 15a1.8 1.8 0 0 0 .36 2l.05.05a2.2 2.2 0 0 1-1.56 3.76 2.2 2.2 0 0 1-1.56-.64l-.05-.05a1.8 1.8 0 0 0-2-.36 1.8 1.8 0 0 0-1.1 1.63V22a2.2 2.2 0 0 1-4.4 0v-.07a1.8 1.8 0 0 0-1.1-1.63 1.8 1.8 0 0 0-2 .36l-.05.05a2.2 2.2 0 1 1-3.12-3.12l.05-.05a1.8 1.8 0 0 0 .36-2 1.8 1.8 0 0 0-1.63-1.1H2a2.2 2.2 0 0 1 0-4.4h.07a1.8 1.8 0 0 0 1.63-1.1 1.8 1.8 0 0 0-.36-2l-.05-.05a2.2 2.2 0 1 1 3.12-3.12l.05.05a1.8 1.8 0 0 0 2 .36 1.8 1.8 0 0 0 1.1-1.63V2a2.2 2.2 0 0 1 4.4 0v.07a1.8 1.8 0 0 0 1.1 1.63 1.8 1.8 0 0 0 2-.36l.05-.05a2.2 2.2 0 0 1 3.12 3.12l-.05.05a1.8 1.8 0 0 0-.36 2 1.8 1.8 0 0 0 1.63 1.1H22a2.2 2.2 0 0 1 0 4.4h-.07a1.8 1.8 0 0 0-1.63 1.1z"})]})}),n.jsxs("button",{type:"button",onClick:f,className:"group inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-body text-primary transition-colors hover:bg-white/[0.08] sm:w-auto sm:gap-1.5 sm:px-3",title:"Refresh data",children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"transition-transform group-hover:rotate-45",children:[n.jsx("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]}),Qe&&n.jsxs("div",{id:"header-notifications-panel",ref:_e,role:"dialog","aria-label":"Notifications",className:"absolute right-0 top-[calc(100%+8px)] z-[320] w-[min(92vw,380px)] rounded-2xl border border-strong bg-[#070a11]/95 p-2 shadow-[0_20px_50px_rgba(0,0,0,0.45)] backdrop-blur",children:[n.jsxs("div",{className:"mb-1.5 flex items-center justify-between px-2 py-1",children:[n.jsx("p",{className:"text-body font-semibold uppercase tracking-[0.12em] text-secondary",children:"Notifications"}),n.jsxs("div",{className:"flex items-center gap-2",children:[as.length>0&&n.jsx("button",{type:"button",onClick:Vn,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>St(!1),className:"rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary","aria-label":"Close notifications",children:"Close"})]})]}),n.jsx("div",{className:"mb-1.5 px-1.5",children:n.jsx(sl,{className:"max-w-full overflow-hidden",running:Tn,blocked:rs,decisionsCount:vi,completedToday:Rs,onDecisionsClick:()=>{x("activity"),Q("initiatives"),nt("initiatives"),lt("in_progress"),Ft("needs_attention"),St(!1)},onBlockedClick:()=>{H.length>0?(x("mission-control"),lt("in_progress"),Ft("needs_attention")):Ue("blocked"),St(!1)}})}),as.length===0?n.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-body text-secondary",children:Zi>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:as.map(g=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:g.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:g.kind==="error"?"rgba(239,68,68,0.08)":"rgba(255,255,255,0.02)"},children:n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex items-center gap-1.5 text-body font-semibold",style:{color:g.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(xn,{type:g.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:g.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:g.message}),g.onAction&&n.jsx("button",{type:"button",onClick:()=>{var A;(A=g.onAction)==null||A.call(g),St(!1)},className:"mt-1.5 rounded-md border border-strong bg-white/[0.05] px-2.5 py-1 text-caption font-medium text-primary transition-colors hover:bg-white/[0.1] hover:text-white",children:g.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>wi(g.id),className:"shrink-0 rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary",title:"Dismiss",children:"Dismiss"})]})},g.id))})]})]})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-center gap-2 lg:hidden",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"workspace-switcher-mobile",className:"sr-only",children:"Workspace scope"}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{id:"workspace-switcher-mobile",value:u??"__all__",onChange:g=>{const A=g.target.value;p(A==="__all__"?null:A)},className:"control-pill h-8 w-full appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${h}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),I.map(g=>n.jsx("option",{value:g.id,children:g.title},g.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})]}),n.jsxs("div",{className:"flex w-full max-w-[248px] rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>x("activity"),"aria-pressed":c==="activity",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${c==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>x("mission-control"),"aria-pressed":c==="mission-control",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${c==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})]})]}),c==="mission-control"?n.jsx("div",{className:"relative z-0 flex-1 min-h-0 flex flex-col overflow-hidden",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"flex flex-1 items-center justify-center text-body text-secondary",children:"Loading Mission Control…"}),children:n.jsx(bg,{initiatives:ys,activities:de,agents:En,runtimeInstances:j.runtimeInstances??[],workspaceInitiativeId:u,isLoading:w,authToken:null,embedMode:!1,connection:j.connection,lastSnapshotAt:j.lastSnapshotAt,error:N,hasApiKey:e.state.hasApiKey,devMode:a,onOpenSettings:()=>hn("orgx"),onRefresh:f,onCreateInitiative:Ds,onPlayNextUp:it,onStartAutopilot:Nn,nextUpQueueModel:dt,nextUpActionsModel:rn,snapshotVersion:j.snapshotVersion})})}):n.jsxs("main",{className:"relative z-0 grid min-h-0 flex-1 grid-cols-1 gap-4 overflow-y-auto p-4 pb-20 sm:p-5 sm:pb-20 lg:grid-cols-12 lg:overflow-hidden lg:pb-5",children:[n.jsx("section",{className:`min-h-0 lg:col-span-3 lg:flex lg:flex-col lg:[&>section]:h-full ${je!=="agents"?"hidden lg:flex":""}`,children:n.jsx(wf,{sessions:j.sessions,activity:de,runtimeInstances:j.runtimeInstances??[],showSyntheticEntities:t||i,selectedSessionId:we,onSelectSession:jt,onAgentFilter:ce,agentFilter:Y,timeFilterId:K,onReconnect:$,onLaunched:f,connectionStatus:j.connection,autopilotState:hs})}),n.jsx("section",{className:`min-h-0 lg:col-span-6 lg:flex lg:flex-col lg:[&>section]:h-full ${je!=="activity"?"hidden lg:flex":""}`,children:n.jsx(yg,{activity:Js.items,sessions:E,sliceRuns:H,initiatives:C,timelineNarrative:j.timelineNarrative??[],workspaceId:u,chatSnapshot:j.chat,devMode:a,selectedRunIds:is,selectedSessionLabel:os,selectedWorkstreamId:G,selectedWorkstreamLabel:z,agentFilter:Y,timeFilterId:K,onTimeFilterChange:Jr,customTimeRange:ge,onCustomTimeRangeChange:Se,hasMore:Js.hasMore,isLoadingMore:Js.isLoadingMore,onLoadMore:Js.loadMore,onClearSelection:$t,onClearWorkstreamFilter:Ms,onClearAgentFilter:Es,onFocusRunId:Fn,onOpenDecision:vt,onResolveDecision:ot,requestedActivityItemId:ye,onActivityItemRequestHandled:()=>me(null),onPlayNextUp:it,onStartAutopilot:Nn,onPauseWorkstream:ls,onCreateInitiative:Ds,onOpenMissionControl:()=>x("mission-control"),onOpenNextUp:()=>x("mission-control"),onOpenSettings:()=>hn("orgx"),onRefreshData:f,isLoading:w})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${je!=="decisions"&&je!=="initiatives"?"hidden lg:flex":""}`,children:n.jsx("div",{className:`min-h-0 ${Ee==="initiatives"?"flex-1":"flex-shrink-0"} `,children:Ee==="initiatives"?n.jsxs(Vs,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-2.5",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-3 overflow-x-auto",children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":Te==="in_progress",onClick:g=>{g.stopPropagation(),lt("in_progress")},className:ue("relative inline-flex h-8 items-center gap-1.5 px-0.5 text-caption font-semibold transition-colors",Te==="in_progress"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"In Progress"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:Ve}),n.jsx("span",{className:ue("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",Te==="in_progress"?"opacity-100":"opacity-0")})]}),n.jsxs("button",{type:"button",role:"tab","aria-selected":Te==="next_up",onClick:g=>{g.stopPropagation(),lt("next_up")},className:ue("relative inline-flex h-8 items-center gap-1.5 px-0.5 text-caption font-semibold transition-colors",Te==="next_up"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"Next Up"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:Kn.total}),n.jsx("span",{className:ue("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-[#BFFF00] transition-opacity",Te==="next_up"?"opacity-100":"opacity-0")})]})]}),n.jsxs("button",{type:"button",onClick:()=>{se().catch(g=>{L(Gn(g instanceof Error?g.message:"","Autopilot action failed."))})},disabled:ct,className:"control-pill inline-flex h-8 items-center gap-1.5 px-2.5 text-caption font-semibold disabled:opacity-45","data-tone":Ts,"data-state":Zn,title:es,"aria-label":es,children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:ue("h-3.5 w-3.5",bn?"animate-pulse":""),"aria-hidden":!0,children:n.jsx("path",{d:"M6.1 13.25C4.25 13.25 2.8 11.8 2.8 10s1.45-3.25 3.3-3.25c3.15 0 4.35 6.5 8.05 6.5 1.85 0 3.3-1.45 3.3-3.25s-1.45-3.25-3.3-3.25c-3.7 0-4.9 6.5-8.05 6.5Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),n.jsx("span",{className:"text-micro uppercase tracking-[0.12em]",children:"Auto"}),n.jsx("span",{className:ue("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",mn==="blocked"?"bg-amber-400/18 text-amber-100":bn?"bg-[#BFFF00]/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:Cs})]})]}),Te==="in_progress"?n.jsxs("div",{className:"flex items-center gap-1.5 border-b border-subtle px-4 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>Ft("all"),className:ue("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Rt==="all"?"bg-white/[0.09] text-primary":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"All active"}),n.jsx("span",{className:"tabular-nums opacity-75",children:Ve})]}),n.jsxs("button",{type:"button",onClick:()=>Ft("needs_attention"),className:ue("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Rt==="needs_attention"?"bg-[#F5B700]/14 text-[#FFE7A8]":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"Needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:He})]}),n.jsxs("button",{type:"button",onClick:()=>Ft("completed"),className:ue("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",Rt==="completed"?"bg-[#14B8A6]/16 text-[#A9FFF3]":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"Completed"}),n.jsx("span",{className:"tabular-nums opacity-80",children:Ke})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:Te==="in_progress"?Rt==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[Ot.items.length>0&&n.jsx("div",{className:"min-h-[180px] max-h-[34%]",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading triage…"}),children:n.jsx(kg,{model:Ot,actions:ln,onOpenDetail:Qs})})}),ie?n.jsxs("section",{className:ue("overflow-hidden rounded-xl border border-subtle bg-white/[0.02]",Je.length===0?"flex-1 min-h-[220px]":"min-h-[220px] max-h-[50%]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Decision queue"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:j.decisions.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:"Resolve blockers and approvals to keep dispatch moving."})]}),n.jsx("div",{className:"min-h-0 p-2",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"h-full min-h-[160px] rounded-lg border border-subtle bg-white/[0.02] p-4 text-body text-secondary",children:"Loading decisions…"}),children:n.jsx(wg,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:j.decisions,focusDecisionId:O,onFocusDecisionHandled:()=>U(null),onApproveDecision:T,onRejectDecision:X,onApproveAll:Z,onBulkDecisionAction:W,mutationState:ke,initiativeNames:er})})})]}):n.jsx(Vs,{className:"border border-subtle bg-white/[0.02] px-4 py-3 text-body text-secondary",children:"OrgX is not connected. Decision actions are hidden until connectivity returns."}),n.jsxs("section",{className:ue("flex min-h-[180px] flex-1 flex-col overflow-hidden rounded-xl border border-subtle bg-white/[0.02]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:ie?"Blocked & review-required slices":"Needs attention"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:Je.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:"Retry, approve, or manually intervene on execution slices."})]}),n.jsx("div",{className:"min-h-0 flex-1 p-2",children:n.jsx(xp,{className:ue("h-full min-h-0"),title:ie?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:H,initiatives:C,onOpenDecisions:()=>vt(),onFocusRunId:Fn,onReviewActivity:ti,onOpenSliceDetail:Et})})]})]}):Rt==="completed"?n.jsx(wp,{rows:Ge,onFocusRunId:Fn,onOpenNextUp:()=>lt("next_up")}):n.jsx(ap,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:E,sliceRuns:H,initiatives:C,needsAttentionCount:He,onSwitchToNeedsAttention:()=>Ft("needs_attention"),onOpenSession:jt,onFocusRunId:Fn,onPlayWorkstream:Ls,onPauseWorkstream:ls,onResumeWorkstream:Ls,onRestartSession:nr,onIntervene:vn,onOpenSliceDetail:Ct}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Ng,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:dt,queueActions:rn,snapshotVersion:j.snapshotVersion,excludeRunning:!0,onOpenInitiative:ki,onOpenSliceDetail:bt})})},`${Te}:${Rt}`)]}):n.jsx(Vs,{className:"card-enter",children:n.jsxs("button",{onClick:()=>nt("initiatives"),className:"flex w-full items-center justify-between px-4 py-3 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("h2",{className:"text-heading font-semibold text-white",children:"Initiatives"})}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"-rotate-90 text-muted",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})})})})]}),n.jsx(It,{children:ze&&dn&&n.jsxs(n.Fragment,{children:[n.jsx(he.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed bottom-0 left-0 right-0 top-[64px] z-[240] hidden bg-black/40 backdrop-blur-sm lg:block",onClick:()=>pe(!1)},"session-drawer-backdrop"),n.jsx(he.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:400,damping:35},className:"glass-panel soft-shadow fixed bottom-0 right-0 top-[64px] z-[250] hidden w-[480px] flex-col lg:flex",style:{backgroundColor:M.cardBg,borderLeft:"1px solid rgba(255,255,255,0.08)"},children:n.jsx("div",{className:"flex-1 min-h-0",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading session detail…"}),children:n.jsx(vg,{session:dn,activity:de,initiatives:C,sliceRuns:H,initialInterventionDraft:le,onSubmitIntervention:Xn,onOpenActivityItem:Ji,onContinueHighestPriority:Zs,onDispatchSession:tr,onPauseSession:Tt,onResumeSession:qn,onCancelSession:cs,onCreateCheckpoint:P,onRollbackSession:sr,onStartInitiative:Ds,onStartWorkstream:ei,onClose:()=>pe(!1)})})})},"session-drawer-panel")]})}),c==="activity"?n.jsx(vm,{activeTab:je,onTabChange:ht,pendingDecisionCount:ie?j.decisions.length:0}):null,n.jsx(Xr,{open:xt!==null,onClose:ss,maxWidth:"max-w-sm",fitContent:!0,children:n.jsxs("div",{className:"flex w-full flex-col",children:[n.jsxs("div",{className:"px-5 pt-5 pb-1",children:[n.jsx("h3",{className:"text-heading font-semibold text-white",children:(xt==null?void 0:xt.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(xt==null?void 0:xt.type)==="workstream"?"Create a new workstream under the selected initiative.":"Create a new initiative to organize your work."})]}),n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("label",{className:"mb-1.5 block text-caption uppercase tracking-[0.1em] text-secondary",children:"Name"}),n.jsx("input",{value:In,onChange:g=>ts(g.target.value),onKeyDown:g=>{g.key==="Enter"&&ir()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(xt==null?void 0:xt.type)==="workstream"?"e.g. User Onboarding Flow":"e.g. Q1 Product Launch",className:"w-full rounded-lg border border-strong bg-black/30 px-3 py-2.5 text-body text-white placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/40"})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-subtle px-5 py-3",children:[n.jsx("button",{onClick:ss,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:ir,disabled:In.trim().length===0||ns,className:"rounded-md border border-lime/25 bg-lime/10 px-4 py-1.5 text-body font-semibold text-lime transition-colors hover:bg-lime/20 disabled:opacity-45",children:ns?"Creating…":"Create"})]})]})}),be.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(jg,{open:be.open,onClose:()=>Le(g=>({...g,open:!1,focusAgentDomain:null})),activeTab:be.tab,onChangeTab:g=>Le(A=>({...A,tab:g})),agentBehaviorInitialDomain:be.focusAgentDomain,demoMode:t,onToggleDemoMode:g=>{Ys(g),g||$()},devMode:a,onToggleDevMode:l,showSyntheticEntities:i,onToggleShowSyntheticEntities:r,workspaceOptions:I,selectedWorkspaceId:u,onSelectWorkspace:p,onboarding:e,authToken:null,embedMode:!1})}),a&&tt&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Eg,{open:tt,selectedWorkspaceId:u,onClose:()=>at(!1)})}),(J==="sessions"||J==="active"||J==="blocked"||J==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ag,{open:J==="sessions"||J==="active"||J==="blocked"||J==="failed",onClose:()=>Ue(null),mode:J==="active"||J==="blocked"||J==="failed"?J:"sessions",sessions:E,onOpenSession:g=>{jt(g.id),Ue(null)},onRunAction:async(g,A)=>{await kt(g,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>f(),onSetNotice:g=>L(g)})}),J==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(_g,{open:J==="decisions",onClose:()=>Ue(null),decisions:ie?j.decisions:[],onApproveDecision:T,onRejectDecision:X,onApproveAll:Z,onBulkDecisionAction:W})}),J==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Sg,{open:J==="outbox",onClose:()=>Ue(null),outbox:j.outbox,onOpenSettings:()=>{Ue(null),hn("orgx")},onRefresh:()=>{f()}})}),J==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Cg,{open:J==="handoffs",onClose:()=>Ue(null),handoffs:j.handoffs})}),n.jsx(Zg,{}),Hn&&n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:n.jsx("div",{className:"relative w-full max-w-lg max-h-[80vh] overflow-hidden rounded-xl border border-subtle bg-[#0E0F11] shadow-2xl",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-8 text-center text-secondary",children:"Loading…"}),children:n.jsx(Ig,{item:Hn,actions:ln,onClose:()=>Gt(null),onNavigate:Ss,currentIndex:Pn,totalCount:Dt.length,decisions:ie?j.decisions:void 0,onApproveDecision:T,onRejectDecision:X})})})}),gt&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Mg,{target:gt,initiatives:C,onClose:()=>Lt(null),onPlayWorkstream:async(g,A,F)=>{const _=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:g,workstreamId:A,agentId:F??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!_.ok){const V=await _.json().catch(()=>null);L(Gn((V==null?void 0:V.error)??(V==null?void 0:V.message)??null,`Failed to dispatch workstream (${_.status})`));return}L("Dispatched workstream."),f()},onStartAutoContinue:async(g,A,F)=>{await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:g,workstreamId:A,placement:"top"})});const _=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:g,agentId:F??void 0,ignoreSpawnGuardRateLimit:!0})});if(!_.ok){const V=await _.json().catch(()=>null);L(Gn((V==null?void 0:V.error)??(V==null?void 0:V.message)??null,`Failed to start auto-continue (${_.status})`));return}L("Auto-continue started."),f()},onMoveWorkstream:async(g,A,F)=>{const _=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:g,workstreamId:A,placement:F})});if(!_.ok){const V=await _.json().catch(()=>null);L(Gn((V==null?void 0:V.error)??(V==null?void 0:V.message)??null,`Move failed (${_.status})`));return}L(`Moved workstream to ${F}.`),f()},onRemoveFromQueue:async(g,A)=>{const F=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:g,workstreamId:A})});if(!F.ok){const _=await F.json().catch(()=>null);L(Gn((_==null?void 0:_.error)??(_==null?void 0:_.message)??null,`Remove failed (${F.status})`));return}L("Removed workstream from queue."),f()},onOpenSession:jt,onFocusRunId:Fn,onOpenInitiative:ki,onReviewActivity:ti,onOpenDecisions:()=>vt(),onAcceptSlice:Vt,onRejectSlice:Qt})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});yu();const tx=new td({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});Zc.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(nd,{client:tx,children:n.jsx(Xg,{})})}));export{hx as $,en as A,ue as B,Bt as C,Wn as D,xn as E,Is as F,Wu as G,mx as H,yx as I,px as J,fx as K,vs as L,zi as M,js as N,Ef as O,Vs as P,dx as Q,Un as R,Ln as S,Qr as T,ju as U,xx as V,ac as W,rm as X,am as Y,oc as Z,pm as _,Au as a,yd as a0,ux as a1,uc as a2,gx as a3,ur as a4,Em as a5,Lm as a6,Qp as a7,cx as a8,Si as a9,Pm as aa,Fr as ab,Ht as b,Np as c,iu as d,M as e,Ix as f,Hp as g,Xt as h,Zt as i,zs as j,bx as k,bc as l,sn as m,nn as n,wx as o,ua as p,Ns as q,kx as r,Nx as s,jp as t,Ku as u,Pt as v,vx as w,Oi as x,Xr as y,_s as z};