@useorgx/openclaw-plugin 0.7.20 → 0.7.23

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 (160) hide show
  1. package/dashboard/dist/assets/9gFmK3Kr.js +1 -0
  2. package/dashboard/dist/assets/9gFmK3Kr.js.br +0 -0
  3. package/dashboard/dist/assets/9gFmK3Kr.js.gz +0 -0
  4. package/dashboard/dist/assets/{BoDhb8_y.js → BrMXbzQ-.js} +2 -2
  5. package/dashboard/dist/assets/BrMXbzQ-.js.br +0 -0
  6. package/dashboard/dist/assets/BrMXbzQ-.js.gz +0 -0
  7. package/dashboard/dist/assets/By0MIBj_.js +1 -0
  8. package/dashboard/dist/assets/By0MIBj_.js.br +0 -0
  9. package/dashboard/dist/assets/By0MIBj_.js.gz +0 -0
  10. package/dashboard/dist/assets/C1u2SGin.css +1 -0
  11. package/dashboard/dist/assets/C1u2SGin.css.br +0 -0
  12. package/dashboard/dist/assets/C1u2SGin.css.gz +0 -0
  13. package/dashboard/dist/assets/{DAr4MfFk.js → CGJiHCIx.js} +1 -1
  14. package/dashboard/dist/assets/CGJiHCIx.js.br +0 -0
  15. package/dashboard/dist/assets/CGJiHCIx.js.gz +0 -0
  16. package/dashboard/dist/assets/CSd4rSuU.js +212 -0
  17. package/dashboard/dist/assets/CSd4rSuU.js.br +0 -0
  18. package/dashboard/dist/assets/CSd4rSuU.js.gz +0 -0
  19. package/dashboard/dist/assets/{DibzNd0I.js → CZXS5i_5.js} +1 -1
  20. package/dashboard/dist/assets/CZXS5i_5.js.br +0 -0
  21. package/dashboard/dist/assets/CZXS5i_5.js.gz +0 -0
  22. package/dashboard/dist/assets/{wa4jJQK9.js → CbVWL74-.js} +1 -1
  23. package/dashboard/dist/assets/CbVWL74-.js.br +0 -0
  24. package/dashboard/dist/assets/CbVWL74-.js.gz +0 -0
  25. package/dashboard/dist/assets/{Dm0CfDGr.js → D-FuHfT8.js} +1 -1
  26. package/dashboard/dist/assets/D-FuHfT8.js.br +0 -0
  27. package/dashboard/dist/assets/D-FuHfT8.js.gz +0 -0
  28. package/dashboard/dist/assets/{DXVs61e1.js → D0PN5_vY.js} +1 -1
  29. package/dashboard/dist/assets/D0PN5_vY.js.br +0 -0
  30. package/dashboard/dist/assets/D0PN5_vY.js.gz +0 -0
  31. package/dashboard/dist/assets/{_zpQCpjm.js → DDCPrZRt.js} +1 -1
  32. package/dashboard/dist/assets/DDCPrZRt.js.br +0 -0
  33. package/dashboard/dist/assets/DDCPrZRt.js.gz +0 -0
  34. package/dashboard/dist/assets/{BYb6DARX.js → DNQ-iFO2.js} +1 -1
  35. package/dashboard/dist/assets/DNQ-iFO2.js.br +0 -0
  36. package/dashboard/dist/assets/DNQ-iFO2.js.gz +0 -0
  37. package/dashboard/dist/assets/{BGY6oI8h.js → DhPuHPK7.js} +1 -1
  38. package/dashboard/dist/assets/DhPuHPK7.js.br +0 -0
  39. package/dashboard/dist/assets/DhPuHPK7.js.gz +0 -0
  40. package/dashboard/dist/assets/Dhz7qPtn.js +1 -0
  41. package/dashboard/dist/assets/Dhz7qPtn.js.br +0 -0
  42. package/dashboard/dist/assets/Dhz7qPtn.js.gz +0 -0
  43. package/dashboard/dist/assets/LOFrVoPD.js +1 -0
  44. package/dashboard/dist/assets/LOFrVoPD.js.br +0 -0
  45. package/dashboard/dist/assets/LOFrVoPD.js.gz +0 -0
  46. package/dashboard/dist/assets/OlLPtzdz.js +1 -0
  47. package/dashboard/dist/assets/OlLPtzdz.js.br +0 -0
  48. package/dashboard/dist/assets/OlLPtzdz.js.gz +0 -0
  49. package/dashboard/dist/assets/{B014hrCe.js → RN4M9u9W.js} +2 -2
  50. package/dashboard/dist/assets/RN4M9u9W.js.br +0 -0
  51. package/dashboard/dist/assets/RN4M9u9W.js.gz +0 -0
  52. package/dashboard/dist/assets/VCHu272d.js +1 -0
  53. package/dashboard/dist/assets/VCHu272d.js.br +0 -0
  54. package/dashboard/dist/assets/VCHu272d.js.gz +0 -0
  55. package/dashboard/dist/assets/m2smti3F.js +1 -0
  56. package/dashboard/dist/assets/m2smti3F.js.br +0 -0
  57. package/dashboard/dist/assets/m2smti3F.js.gz +0 -0
  58. package/dashboard/dist/assets/{CV0sWMbv.js → nra1yvJX.js} +1 -1
  59. package/dashboard/dist/assets/nra1yvJX.js.br +0 -0
  60. package/dashboard/dist/assets/nra1yvJX.js.gz +0 -0
  61. package/dashboard/dist/assets/qLX6NZ-J.js +1 -0
  62. package/dashboard/dist/assets/qLX6NZ-J.js.br +0 -0
  63. package/dashboard/dist/assets/qLX6NZ-J.js.gz +0 -0
  64. package/dashboard/dist/index.html +2 -2
  65. package/dashboard/dist/index.html.br +0 -0
  66. package/dashboard/dist/index.html.gz +0 -0
  67. package/dist/agent-run-store.js +162 -24
  68. package/dist/cli/orgx.d.ts +3 -0
  69. package/dist/config/resolution.d.ts +7 -0
  70. package/dist/config/resolution.js +13 -5
  71. package/dist/contracts/onboarding-state.d.ts +2 -0
  72. package/dist/contracts/onboarding-state.js +23 -0
  73. package/dist/contracts/shared-types.d.ts +17 -0
  74. package/dist/http/helpers/auto-continue-engine.d.ts +23 -0
  75. package/dist/http/helpers/auto-continue-engine.js +233 -53
  76. package/dist/http/helpers/autopilot-runtime.js +5 -1
  77. package/dist/http/helpers/autopilot-slice-utils.js +25 -1
  78. package/dist/http/helpers/decision-mapper.d.ts +1 -0
  79. package/dist/http/helpers/decision-mapper.js +19 -2
  80. package/dist/http/helpers/dispatch-lifecycle.js +3 -0
  81. package/dist/http/helpers/mission-control.d.ts +1 -0
  82. package/dist/http/helpers/mission-control.js +5 -2
  83. package/dist/http/helpers/slice-run-projections.d.ts +27 -0
  84. package/dist/http/helpers/slice-run-projections.js +198 -10
  85. package/dist/http/helpers/triage-mapper.js +220 -6
  86. package/dist/http/index.d.ts +1 -0
  87. package/dist/http/index.js +92 -45
  88. package/dist/http/router.js +64 -9
  89. package/dist/http/routes/live-legacy.d.ts +19 -2
  90. package/dist/http/routes/live-legacy.js +110 -27
  91. package/dist/http/routes/live-snapshot.d.ts +16 -2
  92. package/dist/http/routes/live-snapshot.js +169 -25
  93. package/dist/http/routes/mission-control-actions.js +28 -0
  94. package/dist/http/routes/mission-control-read.d.ts +4 -0
  95. package/dist/http/routes/mission-control-read.js +67 -219
  96. package/dist/http/routes/onboarding.d.ts +1 -0
  97. package/dist/http/routes/onboarding.js +17 -0
  98. package/dist/index.d.ts +5 -0
  99. package/dist/index.js +199 -123
  100. package/dist/outbox.d.ts +0 -2
  101. package/dist/outbox.js +259 -148
  102. package/dist/reporting/rollups.js +18 -11
  103. package/dist/runtime-instance-store.js +212 -58
  104. package/dist/stores/materialized-snapshot-store.d.ts +18 -0
  105. package/dist/stores/materialized-snapshot-store.js +91 -0
  106. package/dist/stores/sqlite-state.d.ts +6 -0
  107. package/dist/stores/sqlite-state.js +179 -0
  108. package/package.json +5 -1
  109. package/dashboard/dist/assets/B014hrCe.js.br +0 -0
  110. package/dashboard/dist/assets/B014hrCe.js.gz +0 -0
  111. package/dashboard/dist/assets/BCudUvwg.js +0 -1
  112. package/dashboard/dist/assets/BCudUvwg.js.br +0 -0
  113. package/dashboard/dist/assets/BCudUvwg.js.gz +0 -0
  114. package/dashboard/dist/assets/BGY6oI8h.js.br +0 -0
  115. package/dashboard/dist/assets/BGY6oI8h.js.gz +0 -0
  116. package/dashboard/dist/assets/BJI1Iy5v.css +0 -1
  117. package/dashboard/dist/assets/BJI1Iy5v.css.br +0 -0
  118. package/dashboard/dist/assets/BJI1Iy5v.css.gz +0 -0
  119. package/dashboard/dist/assets/BUvcp_7V.js +0 -1
  120. package/dashboard/dist/assets/BUvcp_7V.js.br +0 -0
  121. package/dashboard/dist/assets/BUvcp_7V.js.gz +0 -0
  122. package/dashboard/dist/assets/BV2Tf8S2.js +0 -212
  123. package/dashboard/dist/assets/BV2Tf8S2.js.br +0 -0
  124. package/dashboard/dist/assets/BV2Tf8S2.js.gz +0 -0
  125. package/dashboard/dist/assets/BYb6DARX.js.br +0 -0
  126. package/dashboard/dist/assets/BYb6DARX.js.gz +0 -0
  127. package/dashboard/dist/assets/BoDhb8_y.js.br +0 -0
  128. package/dashboard/dist/assets/BoDhb8_y.js.gz +0 -0
  129. package/dashboard/dist/assets/Bqk_l0k6.js +0 -1
  130. package/dashboard/dist/assets/Bqk_l0k6.js.br +0 -0
  131. package/dashboard/dist/assets/Bqk_l0k6.js.gz +0 -0
  132. package/dashboard/dist/assets/C-MOJWHs.js +0 -1
  133. package/dashboard/dist/assets/C-MOJWHs.js.br +0 -0
  134. package/dashboard/dist/assets/C-MOJWHs.js.gz +0 -0
  135. package/dashboard/dist/assets/CV0sWMbv.js.br +0 -0
  136. package/dashboard/dist/assets/CV0sWMbv.js.gz +0 -0
  137. package/dashboard/dist/assets/CaAkScfa.js +0 -1
  138. package/dashboard/dist/assets/CaAkScfa.js.br +0 -0
  139. package/dashboard/dist/assets/CaAkScfa.js.gz +0 -0
  140. package/dashboard/dist/assets/Ck5KlsPN.js +0 -1
  141. package/dashboard/dist/assets/Ck5KlsPN.js.br +0 -0
  142. package/dashboard/dist/assets/Ck5KlsPN.js.gz +0 -0
  143. package/dashboard/dist/assets/D2G51wQm.js +0 -1
  144. package/dashboard/dist/assets/D2G51wQm.js.br +0 -0
  145. package/dashboard/dist/assets/D2G51wQm.js.gz +0 -0
  146. package/dashboard/dist/assets/DAr4MfFk.js.br +0 -0
  147. package/dashboard/dist/assets/DAr4MfFk.js.gz +0 -0
  148. package/dashboard/dist/assets/DXVs61e1.js.br +0 -0
  149. package/dashboard/dist/assets/DXVs61e1.js.gz +0 -0
  150. package/dashboard/dist/assets/DibzNd0I.js.br +0 -0
  151. package/dashboard/dist/assets/DibzNd0I.js.gz +0 -0
  152. package/dashboard/dist/assets/Dm0CfDGr.js.br +0 -0
  153. package/dashboard/dist/assets/Dm0CfDGr.js.gz +0 -0
  154. package/dashboard/dist/assets/_zpQCpjm.js.br +0 -0
  155. package/dashboard/dist/assets/_zpQCpjm.js.gz +0 -0
  156. package/dashboard/dist/assets/uNGpYMSH.js +0 -1
  157. package/dashboard/dist/assets/uNGpYMSH.js.br +0 -0
  158. package/dashboard/dist/assets/uNGpYMSH.js.gz +0 -0
  159. package/dashboard/dist/assets/wa4jJQK9.js.br +0 -0
  160. package/dashboard/dist/assets/wa4jJQK9.js.gz +0 -0
@@ -0,0 +1,212 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/OlLPtzdz.js","assets/Dj2k1r16.js","assets/DMKyYAtD.js","assets/9gFmK3Kr.js","assets/D0PN5_vY.js","assets/eeHXe_OQ.js","assets/CbVWL74-.js","assets/By0MIBj_.js","assets/DhPuHPK7.js","assets/CZXS5i_5.js","assets/cX2e-TLi.js","assets/BjK42gtU.js","assets/qm8xLgv-.css","assets/BV0BcV1u.js","assets/LOFrVoPD.js","assets/CGJiHCIx.js","assets/qLX6NZ-J.js","assets/CSlBSRyv.js","assets/Dhz7qPtn.js","assets/m2smti3F.js","assets/BrMXbzQ-.js","assets/DDCPrZRt.js","assets/nra1yvJX.js","assets/RN4M9u9W.js","assets/D-FuHfT8.js","assets/VCHu272d.js","assets/DNQ-iFO2.js"])))=>i.map(i=>d[i]);
2
+ var Yc=Object.defineProperty;var Jc=(e,t,s)=>t in e?Yc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var os=(e,t,s)=>Jc(e,typeof t!="symbol"?t+"":t,s);import{r as o,j as n,a as Zc,d as ed}from"./Dj2k1r16.js";import{u as Xa,a as td,b as $n,c as Zs,Q as nd,d as sd}from"./DMKyYAtD.js";import{m as ce,A as Nt,u as xs}from"./eeHXe_OQ.js";import{a7 as id}from"./cX2e-TLi.js";import{D as mo}from"./BjK42gtU.js";import{T as rd,u as ad}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 od="modulepreload",ld=function(e){return"/orgx/live/"+e},po={},cn=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(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};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=ld(u),u in po)return;po[u]=!0;const p=u.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${g}`))return;const v=document.createElement("link");if(v.rel=p?"stylesheet":od,p||(v.as="script"),v.crossOrigin="",v.href=u,d&&v.setAttribute("nonce",d),document.head.appendChild(v),p)return new Promise((h,w)=>{v.addEventListener("load",h),v.addEventListener("error",()=>w(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()}}},aa="all";function hs(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function cd(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return hs(e.get("workspace_id"))??hs(e.get("workspaceId"))??hs(e.get("command_center_id"))??hs(e.get("commandCenterId"))??hs(e.get("center"))??hs(e.get("project_id"))??hs(e.get("projectId"))}catch{return null}}function Ts(e,t,s){const i=hs(t);if(!i){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",aa),e.set("command_center_id",aa),e.set("center",aa));return}e.set("workspace_id",i),e.set("command_center_id",i),e.set("center",i)}function dd(e){const t=hs(e);return t?{"x-orgx-workspace-id":t}:{}}function Ut(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??cd();return Object.assign(t,dd(s)),t}const ud=[[/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 zi(e){if(!e)return"";for(const[s,i]of ud)if(s.test(e))return i;const t=e.split("/");return t[t.length-1]??e}const Vl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Gl=/^[0-9a-f]{20,}$/i;function As(e){return Vl.test(e)?`#${e.slice(0,4)}`:Gl.test(e)?`#${e.slice(0,4)}`:e}function Hn(e){return Vl.test(e)||Gl.test(e)}function Wn(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 rt(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=>zi(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>Wn(s)),t}function Wt(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=>Wn(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 oa(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 Ni(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 md(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=Ni(i,["message","detail","error_description"])??(s?null:Ni(t,["error"])),a=Ni(i,["code","error_code","type"]),l=md(i,["status","httpStatusCode"]),c=Ni(i,["requestId","request_id"]),d=Ni(i,["docsUrl","docs_url"]);return!r&&!a&&l==null&&!c&&!d?null:{code:a,message:r,status:l,requestId:c,docsUrl:d}}function pd(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 g=JSON.parse(p),v=go(g);if(v)return v}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 en(e){var c;const t=pd(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.":Wt(rt(a))}function fd(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 hd(e){const t=(e==null?void 0:e.event_name)??(e==null?void 0:e.event)??"";if(t){const i=rt(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 gd(e){const t=e.metadata??{},s=ni(t,"task_title")??ni(t,"workstream_title"),i=s?Wt(String(s)):e.title?Wt(e.title):null,r=ni(t,"user_summary")??ni(t,"summary"),a=r?Wt(String(r)):e.summary?Wt(e.summary):e.description?Wt(e.description):null,l=ni(t,"next_step")??ni(t,"nextStep"),c=l?Wt(String(l)):null,d=(g,v)=>g===v||g.includes(v)||v.includes(g),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 ni(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const xd={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 ji(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return xd[t]??e.replace(/_/g," ")}const yd={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function gx(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return yd[t]??e.replace(/_/g," ")}function xx(e,t){return e.toLowerCase().includes("path")?Wn(t):Hn(t)?As(t):t.includes(",")?t.split(",").map(i=>{const r=i.trim();return Hn(r)?As(r):r}).join(", "):Wt(t)}function bd(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 yx(e){const t=bd(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function Br(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function qt(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 vd=8e3,wd=320,kd=300,Id=80,Nd=80,jd=120,yo=6e4,Ad=1200,_d=240,Sd=3,Cd=24,bo=24,Ai=new WeakMap,Qa={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},or={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Js={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},Xl=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),lr=10*6e4;function Td(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 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 en(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 St(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Fr(e,t){const s=vo[e.status]??99,i=vo[t.status]??99;if(s!==i)return s-i;const r=St(e.updatedAt??e.lastEventAt??e.startedAt),a=St(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 Xl.has(Rd(e.status))}function la(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(),w=e.nodes.filter(M=>{const F=St(M.updatedAt??M.lastEventAt??M.startedAt);if(wo(M))return!0;const A=["completed","archived","failed"].includes((M.status??"").toLowerCase())?lr/3:lr;return h-F<=A});if(!w.length)return t;const y=new Set(w.map(M=>M.id)),I=new Set(w.map(M=>M.groupId));return{nodes:w.sort(Fr),edges:e.edges.filter(M=>y.has(M.parentId)&&y.has(M.childId)),groups:e.groups.filter(M=>I.has(M.id))}}const s=new Set,i=[...t.nodes];for(const h of t.nodes)for(const w of la(h))s.add(w);const r=Date.now(),a=[];for(const h of e.nodes){if(la(h).some(b=>s.has(b)))continue;const y=St(h.updatedAt??h.lastEventAt??h.startedAt),M=["completed","archived","failed"].includes((h.status??"").toLowerCase())?lr/3:lr,F=r-y<=M;if(wo(h)||F){a.push(h),i.push(h);for(const b of la(h))s.add(b)}}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 w=c.get(h.groupId)??{id:h.groupId,label:h.groupLabel||h.agentName||"Ungrouped",status:null};d.set(h.groupId,w),u.push(w)}const p=h=>`${h.parentId}->${h.childId}`,g=new Set,v=[];for(const h of t.edges){if(!l.has(h.parentId)||!l.has(h.childId))continue;const w=p(h);g.has(w)||(g.add(w),v.push(h))}for(const h of e.edges){if(!l.has(h.parentId)||!l.has(h.childId))continue;const w=p(h);g.has(w)||(g.add(w),v.push(h))}return{nodes:i.sort(Fr),edges:v,groups:u}}function _i(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(Fr).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)=>St(i.updatedAt)-St(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()-St(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 Ql(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 Yl(e){if(!e||typeof e!="object")return Qa;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 zr(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=Ai.get(i);if(r)return r;if(t>=Sd){const g=Array.isArray(e)?"[…]":"{…}";return Ai.set(i,g),g}if(Ai.set(i,Array.isArray(e)?"[]":"{}"),Array.isArray(e)){const g=e.slice(0,bo).map(w=>zr(w,t+1)).join(","),v=e.length>bo?",…":"",h=`[${g}${v}]`;return Ai.set(i,h),h}const a=e,l=Object.keys(a).sort(),c=l.slice(0,Cd),d=c.map(g=>`${g}:${zr(a[g],t+1)}`).join("|"),u=l.length>c.length?"|…":"",p=`{${d}${u}}`;return Ai.set(i,p),p}function Pd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function zs(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 $d(e){const t=Pd(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)??zs(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=zs(t,["correlation_id","correlationId"]),l=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??zs(t,["initiative_id","initiativeId"]),c=zs(t,["workstream_id","workstreamId"]),d=zs(t,["task_id","taskId"]),u=zs(t,["stop_reason","stopReason"]),p=zs(t,["parsed_status","parsedStatus"]),g=(e.title??"").trim().toLowerCase();return!i&&!r&&!a||!r&&!a&&!c&&!d?null:[i,l??"",c??"",d??"",r??"",a??"",u??"",p??"",g].join("|")}function cr(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 Jl(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&&cr(l)>cr(a[d])&&(a[d]=l);continue}s.add(l.id);const c=$d(l);if(c&&i.has(c)){const d=r.get(c);cr(l)>cr(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 Od(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,zr(d.metadata));let a=!1;for(const d of t){const u=i.get(d.id),p=zr(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=St(u.timestamp)-St(d.timestamp);return p!==0?p:u.id.localeCompare(d.id)}),c=Jl(l,s);return Ql(e,c)?e:c}function ca(e,t){const s=[...e].sort((i,r)=>{const a=St(r.timestamp)-St(i.timestamp);return a!==0?a:r.id.localeCompare(i.id)});return Jl(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:St(l.requestedAt??l.updatedAt)-St(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 qd(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 Bd(e,t){return!!(Xl.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function dr(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function da(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 Fd(e,t,s){const i=new Map,r=[...e].sort((c,d)=>St(d.timestamp)-St(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 g=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:g,workstreamId:null,groupId:g??"unscoped",groupLabel:dr(g),startedAt:p,updatedAt:p,lastEventAt:p,lastEventSummary:c.title,blockers:c.type==="blocker_created"&&c.description?[c.description]:[]});continue}(!u.startedAt||St(p)<St(u.startedAt))&&(u.startedAt=p),St(p)>=St(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=dr(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=qd(c.status),g=new Date().toISOString(),v=Bd(c,p),h=c.startedAt??(v?g:null),w=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:w,workstreamId:null,groupId:w??"unscoped",groupLabel:dr(w),startedAt:h,updatedAt:h,lastEventAt:h,lastEventSummary:c.currentTask,blockers:da(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),v&&(u.updatedAt=h??u.updatedAt??g,u.lastEventAt=h??u.lastEventAt??g),u.status==="archived"&&p!=="archived"&&(u.status=p),da(c.blockers).length>0&&(u.blockers=da(c.blockers)),w&&!u.initiativeId&&(u.initiativeId=w,u.groupId=w,u.groupLabel=dr(w))}const a=Array.from(i.values()).sort(Fr).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 g=()=>r.abort();a.addEventListener("abort",g,{once:!0}),u=()=>a.removeEventListener("abort",g)}d=setTimeout(()=>r.abort(),i)}try{const g=await fetch(e,c),h=(((p=g.headers.get("content-type"))==null?void 0:p.toLowerCase())??"").includes("application/json");if(!g.ok){let w=`${g.status} ${g.statusText}`;if(h){const y=await g.json().catch(()=>null);y!=null&&y.error&&(w=`${g.status} ${y.error}`)}else{const y=(await g.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);y.length>0&&(w=`${g.status} ${y}`)}return{ok:!1,status:g.status,data:null,error:w}}if(!h){const w=(await g.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:g.status,data:null,error:`Unexpected content type for ${e}${w?`: ${w}`:""}`}}return{ok:!0,status:g.status,data:await g.json(),error:null}}catch(g){const v=g instanceof Error?g.message:"Network error",h=!!(r!=null&&r.signal.aborted)&&!(a!=null&&a.aborted);return g instanceof DOMException&&g.name==="AbortError"||Td(v)?{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:v}}finally{d&&clearTimeout(d),u&&u()}}function Ud(e,t,s,i,r=[],a=Qa,l=null,c=1,d=[],u=Js,p){var w,y,I;const g=((w=t[0])==null?void 0:w.timestamp)??null,v=((y=i[0])==null?void 0:y.requestedAt)??((I=i[0])==null?void 0:I.updatedAt)??null,h=St(g)>=St(v)?g:v;return{connection:"connected",lastActivity:h?qt(h):null,lastSnapshotAt:l,snapshotVersion:c,sessions:e,activity:t,handoffs:s,decisions:i,sliceRuns:r,outbox:Yl(a),chat:Er(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)=>St(i.lastEventAt??i.lastHeartbeatAt)-St(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)=>St(i.lastActivityAt??i.updatedAt)-St(s.lastActivityAt??s.updatedAt))}function Er(e){if(!e||typeof e!="object")return Js;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??Js,i=t??Js;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 Rr(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,g=typeof i.workstreamId=="string"&&i.workstreamId.trim().length>0?i.workstreamId.trim():d[0]??null,v=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:g,workstreamIds:d,iwmtId:v,iwmtIds:u,artifacts:Array.isArray(i.artifacts)?i.artifacts:[],decisionOptions:Array.isArray(i.decisionOptions)?i.decisionOptions:[],pendingDecisions:Array.isArray(i.pendingDecisions)?i.pendingDecisions??[]:[],blockers:Array.isArray(i.blockers)?i.blockers??[]:[],taskIds:Array.isArray(i.taskIds)?i.taskIds:[],milestoneIds:Array.isArray(i.milestoneIds)?i.milestoneIds:[]})}return Array.from(t.values()).sort((i,r)=>St(r.updatedAt??r.lastEventAt)-St(i.updatedAt??i.lastEventAt))}function ur(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)=>St(i.updatedAt??i.completedAt??i.failedAt)-St(s.updatedAt??s.completedAt??s.failedAt))}function ua(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)=>St(i.occurredAt)-St(s.occurredAt))}function ma(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 Rr(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=vd,useMock:i=!1,enableDecisions:r=!0,initiativeId:a=null,projectId:l=null,maxSessions:c=wd,maxActivityItems:d=kd,maxHandoffs:u=Id,maxDecisions:p=Nd,batchWindowMs:g=jd}=e,v=typeof a=="string"&&a.trim().length>0?a.trim():null,h=typeof l=="string"&&l.trim().length>0?l.trim():null,[w,y]=o.useState(fo()),[I,M]=o.useState(or),[F,b]=o.useState(!i),[A,H]=o.useState(null),j=o.useRef(),P=o.useRef(null),Z=o.useRef(null),[E,D]=o.useState(!1),[ee,ve]=o.useState(typeof document>"u"?!0:document.visibilityState==="visible"),[Ce,pe]=o.useState(typeof navigator>"u"?!0:navigator.onLine!==!1),Ae=o.useRef(0),re=o.useRef(!1),ne=o.useRef(!1),G=o.useRef(null),ae=o.useRef(`${v??"__all__"}::${h??"__all__"}`),De=o.useRef(!1),Te=o.useRef(null),de=o.useCallback((me,ke)=>{Te.current&&(clearTimeout(Te.current),Te.current=null),M(me),ke!=null&&ke.autoResetMs&&ke.autoResetMs>0&&(Te.current=setTimeout(()=>{Te.current=null,M(or)},ke.autoResetMs))},[]);o.useEffect(()=>()=>{Te.current&&(clearTimeout(Te.current),Te.current=null),G.current&&(clearTimeout(G.current),G.current=null)},[]),o.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const me=()=>{ve(document.visibilityState==="visible")},ke=()=>pe(!0),T=()=>pe(!1);return document.addEventListener("visibilitychange",me),window.addEventListener("online",ke),window.addEventListener("offline",T),()=>{document.removeEventListener("visibilitychange",me),window.removeEventListener("online",ke),window.removeEventListener("offline",T)}},[]),o.useEffect(()=>{const me=`${v??"__all__"}::${h??"__all__"}`;ae.current!==me&&(ae.current=me,De.current=!0,ne.current=!1,de(or),y(ke=>({...ke,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Js,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(ke.snapshotVersion??0)+1})),b(!0),H(null))},[v,h,de]);const we=o.useCallback((me,ke,T,be=null,Y=null,Ee=null,ze=null,Be=null,ft=null,Me=null)=>{Ae.current=Date.now(),re.current=!1,y(Se=>{const J=De.current;J&&(De.current=!1);const ht=ke===null?J?[]:Se.activity:ca(ke,d),It=T===null?J?[]:Se.handoffs:Io(T,u),We=_i(me===null?J?{nodes:[],edges:[],groups:[]}:Se.sessions:J?_i(me,c):ko(Se.sessions,_i(me,c)),c),Q=be===null?J?[]:Se.decisions:_o(be,p),q=Y===null?J?[]:Se.sliceRuns:Rr(Y),te=Ee===null?J?Qa:Se.outbox:Yl(Ee),le=Be===null?J?[]:Se.runtimeInstances??[]:Co(Be),$e=ft===null?J?Js:Se.chat??Js:Er(ft),Ve=(Me==null?void 0:Me.workSliceProjections)==null?J?[]:Se.workSliceProjections??[]:ur(Me.workSliceProjections),Ye=(Me==null?void 0:Me.timelineNarrative)==null?J?[]:Se.timelineNarrative??[]:ua(Me.timelineNarrative),fe=(Me==null?void 0:Me.nextUpByInitiative)==null?J?[]:Se.nextUpByInitiative??[]:ma(Me.nextUpByInitiative),Qe=typeof(Me==null?void 0:Me.runningWorkSlices)=="number"&&Number.isFinite(Me.runningWorkSlices)?Math.max(0,Math.floor(Me.runningWorkSlices)):Se.runningWorkSlices??0,ie=typeof(Me==null?void 0:Me.needsInputTotal)=="number"&&Number.isFinite(Me.needsInputTotal)?Math.max(0,Math.floor(Me.needsInputTotal)):Se.needsInputTotal??0,V=typeof(Me==null?void 0:Me.failedActionableTotal)=="number"&&Number.isFinite(Me.failedActionableTotal)?Math.max(0,Math.floor(Me.failedActionableTotal)):Se.failedActionableTotal??0,Re=typeof(Me==null?void 0:Me.completedTodayTotal)=="number"&&Number.isFinite(Me.completedTodayTotal)?Math.max(0,Math.floor(Me.completedTodayTotal)):Se.completedTodayTotal??0,et=(Me==null?void 0:Me.consistencyFlags)==null?Se.consistencyFlags??[]:Me.consistencyFlags.filter(mt=>typeof mt=="string"),ct=(Me==null?void 0:Me.dataHealth)===void 0||(Me==null?void 0:Me.dataHealth)===null?Se.dataHealth:Me.dataHealth,gt=(Se.snapshotVersion??0)+1;return No(Se.sessions,We)&&Ql(Se.activity,ht)&&jo(Se.handoffs,It)&&Ao(Se.decisions,Q)&&Kd(Se.sliceRuns,q)&&Dd(Se.outbox,te)&&Hd(Se.chat,$e)&&To(Se.runtimeInstances,le)&&Vd(Se.workSliceProjections??[],Ve)&&Gd(Se.timelineNarrative??[],Ye)&&Xd(Se.nextUpByInitiative??[],fe)&&(Se.runningWorkSlices??0)===Qe&&(Se.needsInputTotal??0)===ie&&(Se.failedActionableTotal??0)===V&&(Se.completedTodayTotal??0)===Re&&Qd(Se.consistencyFlags??[],et)&&Yd(Se.dataHealth,ct)&&Se.lastSnapshotAt===ze&&Se.connection==="connected"?Se:Ud(We,ht,It,Q,q,te,ze,gt,le,$e,{workSliceProjections:Ve,timelineNarrative:Ye,nextUpByInitiative:fe,runningWorkSlices:Qe,needsInputTotal:ie,failedActionableTotal:V,completedTodayTotal:Re,consistencyFlags:et,dataHealth:ct})}),b(!1)},[d,p,u,c]),C=o.useCallback(async()=>{if(!t){y(T=>T.connection==="disconnected"?T:{...T,connection:"disconnected"}),b(!1),H(null);return}const me=`${v??"__all__"}::${h??"__all__"}`;if(P.current&&Z.current===me)return P.current;if(i){y(fo()),b(!1);return}const ke=(async()=>{try{const T=new URLSearchParams({sessionsLimit:String(c),activityLimit:String(d),decisionsLimit:String(p),include_idle:"true"});h&&Ts(T,h),v&&T.set("initiative",v);const be=await zd(`/orgx/api/live/snapshot-v2?${T.toString()}`,{headers:Ut({workspaceId:h})},{timeoutMs:Ad});if(!be.ok||!be.data){if(be.status===401||be.status===403){const jt=new Error("Unauthorized. Update your OrgX API key in Settings (use a user-scoped oxk_... key; userId should be blank).");throw jt.code="ORGX_AUTH",jt}throw new Error(be.error??"live/snapshot-v2 unavailable")}const Y=be.data;if(ae.current!==me)return;const Ee=Array.isArray(Y.degraded)?Y.degraded.filter(jt=>typeof jt=="string"):[],ze=Ee.map(jt=>jt.toLowerCase()),Be=(...jt)=>ze.some(X=>jt.some(he=>X.includes(he))),ft=Array.isArray(Y.activity)?Y.activity:[],Me=Array.isArray(Y.handoffs)?Y.handoffs:[],Se=Array.isArray(Y.decisions)?Y.decisions:[],J=ft.length===0&&Be("activity unavailable","activity local fallback failed"),ht=Be("sessions unavailable","sessions local fallback failed"),It=Me.length===0&&Be("handoffs unavailable"),We=Se.length===0&&Be("decisions unavailable"),Q=ur(Array.isArray(Y.projections)?Y.projections:[]),q=Er(Y.chat??null),te=ua(Array.isArray(Y.timelineNarrative)?Y.timelineNarrative:[]),le=ma(Array.isArray(Y.nextUpByInitiative)?Y.nextUpByInitiative:[]),$e=Q.length>0?Mo(Q):Rr(Array.isArray(Y.sliceRuns)?Y.sliceRuns:[]),Ve=Y.sessions&&Array.isArray(Y.sessions.nodes)&&Array.isArray(Y.sessions.edges)&&Array.isArray(Y.sessions.groups)?Y.sessions:Fd(ft,Y.agents,c),Ye=$e.length===0&&Q.length===0&&Be("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),fe=le.length===0&&Be("next-up unavailable","next-up queue"),Qe=J?null:ft,ie=It?null:Me,V=We?null:Se,Re=ht&&Ve.nodes.length===0?null:Ve,et=Ye?null:Q,ct=Ye?null:te,gt=Ye?null:$e,mt=fe?null:le;we(Re,Qe,ie,V,gt,Y.outbox??null,Y.generatedAt??null,Y.runtimeInstances??null,q,{workSliceProjections:et,timelineNarrative:ct,nextUpByInitiative:mt,runningWorkSlices:Ye?null:Y.runningWorkSlices??null,needsInputTotal:Ye?null:Y.needsInput??null,failedActionableTotal:Ye?null:Y.failedActionable??null,completedTodayTotal:Ye?null:Y.completedToday??null,consistencyFlags:Array.isArray(Y.consistencyFlags)?Y.consistencyFlags:null,dataHealth:Y.dataHealth??null});const vt=Ee.length>0?Ed(Ee):[];vt.length>0?(H(`Partial live data: ${vt.join("; ")}`),y(jt=>jt.connection==="connected"?jt:{...jt,connection:"connected"}),D(!1)):(H(null),y(jt=>jt.connection==="connected"?jt:{...jt,connection:"connected"}))}catch(T){if(ae.current!==me)return;const be=T instanceof Error?T.message:"Unknown error",Y=T==null||typeof T!="object"||!("code"in T)?!1:T.code==="ORGX_AUTH";Y&&(re.current=!0);const Ee=Ae.current>0&&Date.now()-Ae.current>yo;H(be),y(ze=>{const Be=Y||Ee?"disconnected":"reconnecting";return ze.connection===Be?ze:{...ze,connection:Be}}),D(!Y),b(!1)}finally{Z.current===me&&(P.current=null,Z.current=null)}})();return P.current=ke,Z.current=me,ke},[we,t,r,d,p,u,c,h,v,i]),O=o.useCallback(async(me,ke,T)=>{var ft,Me,Se;if(!r)throw new Error("OrgX decisions are unavailable while disconnected.");const be=Array.from(new Set(me.filter(Boolean)));if(be.length===0)return{updated:0,failed:0};const Y=((ft=T==null?void 0:T.note)==null?void 0:ft.trim())||void 0,Ee=((Me=T==null?void 0:T.optionId)==null?void 0:Me.trim())||void 0;if(i){const J=new Set(be);return y(ht=>{const It=ht.decisions.filter(te=>J.has(te.id));if(It.length===0)return ht;const We=new Date().toISOString(),Q=It.map(te=>({id:`decision:${ke}:${te.id}:${Date.now()}`,type:"decision_resolved",title:ke==="approve"?`Approved: ${te.title}`:`Rejected: ${te.title}`,description:te.context,agentId:null,agentName:te.agentName,requesterAgentId:null,requesterAgentName:te.agentName??null,executorAgentId:null,executorAgentName:te.agentName??null,runId:null,initiativeId:null,timestamp:We,metadata:{decisionId:te.id,action:ke}})),q=ca(Q.concat(ht.activity),d);return{...ht,decisions:ht.decisions.filter(te=>!J.has(te.id)),activity:q,lastActivity:qt(We)}}),{updated:J.size,failed:0,firstError:void 0}}const ze=new Date().toISOString(),Be=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:Ut({contentTypeJson:!0,workspaceId:h}),body:JSON.stringify({ids:be,action:ke,...Y?{note:Y}:{},...Ee?{option_id:Ee}:{}})});try{const J=await Be.json().catch(()=>null),ht=Array.isArray(J==null?void 0:J.results)?J.results:[],It=new Set(ht.filter(le=>le.ok).map(le=>le.id)),Q=((Se=ht.filter(le=>!le.ok).find(le=>typeof le.error=="string"&&le.error.trim().length>0))==null?void 0:Se.error)??(typeof(J==null?void 0:J.error)=="string"&&J.error.trim().length>0?J.error:void 0);if(!Be.ok&&Be.status!==207){const le=Q??`Decision action failed (${Be.status})`;throw new Error(le)}if(It.size===0&&Be.ok&&((J==null?void 0:J.failed)??0)===0)for(const le of be)It.add(le);It.size>0?y(le=>{const $e=le.decisions.filter(ie=>It.has(ie.id));if($e.length===0)return le;const Ve=new Date().toISOString(),Ye=$e.map(ie=>({id:`decision:${ke}:${ie.id}:${Date.now()}`,type:"decision_resolved",title:ke==="approve"?`Approved: ${ie.title}`:`Rejected: ${ie.title}`,description:ie.context,agentId:null,agentName:ie.agentName,requesterAgentId:null,requesterAgentName:ie.agentName??null,executorAgentId:null,executorAgentName:ie.agentName??null,runId:null,initiativeId:null,timestamp:Ve,metadata:{decisionId:ie.id,action:ke}})),fe=ca(Ye.concat(le.activity),d);return{...le,decisions:le.decisions.filter(ie=>!It.has(ie.id)),activity:fe,lastActivity:qt(Ve)}}):Be.ok&&be.length>0&&y(le=>({...le,decisions:le.decisions.filter($e=>!be.includes($e.id))})),C();const q=(J==null?void 0:J.updated)??It.size,te=(J==null?void 0:J.failed)??Math.max(0,be.length-It.size);return de({phase:te>0?"error":"success",action:ke,targetCount:be.length,message:te>0?`${ke==="approve"?"Approve":"Reject"} completed with ${te} failure${te===1?"":"s"}.`:ke==="approve"?`Approved ${q} decision${q===1?"":"s"}.`:`Rejected ${q} decision${q===1?"":"s"}.`,startedAt:ze,completedAt:new Date().toISOString()},{autoResetMs:te>0?8e3:4e3}),{updated:q,failed:te,firstError:Q}}catch(J){throw de({phase:"error",action:ke,targetCount:be.length,message:J instanceof Error?J.message:"Decision update failed.",startedAt:ze,completedAt:new Date().toISOString()}),J}},[r,C,d,h,de,i]),U=o.useCallback(async(me,ke)=>O([me],"approve",ke),[O]),K=o.useCallback(async(me,ke)=>O([me],"reject",ke),[O]),ye=o.useCallback(async()=>{let me=[];return y(ke=>(me=ke.decisions.map(T=>T.id),ke)),me.length===0?{updated:0,failed:0}:O(me,"approve")},[O]),Oe=o.useCallback(async(me,ke,T)=>O(me,ke,T?{note:T}:void 0),[O]);return o.useEffect(()=>{r||de(or)},[r,de]),o.useEffect(()=>{if(!t){D(!1),b(!1),H(null);return}if(i){C();return}ne.current=!1;const me=new URLSearchParams;h&&Ts(me,h),v&&me.set("initiative",v);const ke=me.toString()?`/orgx/api/live/stream-v2?${me.toString()}`:"/orgx/api/live/stream-v2",T=new EventSource(ke),be=()=>{G.current&&(clearTimeout(G.current),G.current=null),!(!ee||!Ce)&&(G.current=setTimeout(()=>{G.current=null,!ne.current&&!re.current&&C()},_d))};be();let Y=null,Ee=null,ze=null,Be=null,ft=[],Me=null,Se;const J=()=>{if(Se=void 0,Y){Ae.current=Date.now(),re.current=!1;const We=Y;Y=null,ze=null,Be=null,ft=[],Me=null,Ee=null,we(We.sessions,We.activity,We.handoffs,We.decisions,We.sliceRuns,We.outbox,We.generatedAt,We.runtimeInstances,We.chat,We.v2);return}!ze&&!Be&&!Me&&!Ee&&ft.length===0||(Ae.current=Date.now(),re.current=!1,y(We=>{var q;let Q=We;if(ze){const te=_i(ze,c),le=_i(ko(Q.sessions,te),c);ze=null,No(Q.sessions,le)||(Q={...Q,sessions:le})}if(Be){const te=Io(Be,u);Be=null,jo(Q.handoffs,te)||(Q={...Q,handoffs:te})}if(Me){const te=_o(Me,p);Me=null,Ao(Q.decisions,te)||(Q={...Q,decisions:te})}if(Ee){const te=Co(Ee);Ee=null,To(Q.runtimeInstances,te)||(Q={...Q,runtimeInstances:te})}if(ft.length>0){const te=Od(Q.activity,ft,d);ft=[],te!==Q.activity&&(Q={...Q,activity:te,lastActivity:(q=te[0])!=null&&q.timestamp?qt(te[0].timestamp):Q.lastActivity})}return Q===We?We:Q.connection==="connected"?Q:{...Q,connection:"connected"}}),H(null),b(!1))},ht=()=>{Se||(Se=setTimeout(J,g))};T.onopen=()=>{Ae.current=Date.now(),re.current=!1,D(!1),y(We=>We.connection==="connected"?We:{...We,connection:"connected"}),H(null),be()},T.onerror=()=>{if(re.current){y(Q=>Q.connection==="disconnected"?Q:{...Q,connection:"disconnected"}),D(!1);return}const We=Ae.current>0&&Date.now()-Ae.current>yo;y(Q=>Q.connection===(We?"disconnected":"reconnecting")?Q:{...Q,connection:We?"disconnected":"reconnecting"}),D(!0)},T.addEventListener("snapshot",We=>{try{ne.current=!0,G.current&&(clearTimeout(G.current),G.current=null);const Q=JSON.parse(We.data),q=typeof Q.generatedAt=="string"&&Q.generatedAt.length>0?Q.generatedAt:new Date().toISOString();Y={sessions:Q.sessions,activity:Q.activity??[],handoffs:Q.handoffs??[],decisions:Q.decisions??null,sliceRuns:Array.isArray(Q.sliceRuns)?Rr(Q.sliceRuns):Array.isArray(Q.projections)?Mo(ur(Q.projections)):null,outbox:Q.outbox??null,generatedAt:q,runtimeInstances:Array.isArray(Q.runtimeInstances)?Q.runtimeInstances:null,chat:Er(Q.chat??null),v2:{workSliceProjections:Array.isArray(Q.projections)?ur(Q.projections):null,timelineNarrative:Array.isArray(Q.timelineNarrative)?ua(Q.timelineNarrative):null,nextUpByInitiative:Array.isArray(Q.nextUpByInitiative)?ma(Q.nextUpByInitiative):null,runningWorkSlices:typeof Q.runningWorkSlices=="number"?Q.runningWorkSlices:null,needsInputTotal:typeof Q.needsInput=="number"?Q.needsInput:null,failedActionableTotal:typeof Q.failedActionable=="number"?Q.failedActionable:null,completedTodayTotal:typeof Q.completedToday=="number"?Q.completedToday:null,consistencyFlags:Array.isArray(Q.consistencyFlags)?Q.consistencyFlags:null,dataHealth:Q.dataHealth??null}},ht()}catch(Q){H(Q instanceof Error?Q.message:"Invalid snapshot")}}),T.addEventListener("activity.appended",We=>{try{const Q=JSON.parse(We.data);if(Q.length===0)return;ft=ft.concat(Q),ht()}catch{}}),T.addEventListener("session.updated",We=>{try{ze=JSON.parse(We.data),ht()}catch{}});const It=We=>{try{const Q=JSON.parse(We.data);Ee=Array.isArray(Q)?Q:[Q],ht()}catch{}};return T.addEventListener("runtime.updated",It),T.addEventListener("handoff.updated",We=>{try{Be=JSON.parse(We.data),ht()}catch{}}),T.addEventListener("decision.updated",We=>{try{Me=JSON.parse(We.data),ht()}catch{}}),()=>{G.current&&(clearTimeout(G.current),G.current=null),Se&&clearTimeout(Se),T.close()}},[we,g,t,r,C,d,p,u,c,v,h,ee,Ce,i]),o.useEffect(()=>{if(t&&!i&&(j.current&&clearInterval(j.current),!(!E||!ee||!Ce)))return j.current=setInterval(()=>{C()},s),()=>{j.current&&clearInterval(j.current)}},[t,C,ee,Ce,h,s,E,i]),o.useEffect(()=>{!t||i||E&&(!ee||!Ce||C())},[t,C,ee,Ce,E,i]),{data:w,isLoading:F,error:A,refetch:C,approveDecision:U,rejectDecision:K,approveAllDecisions:ye,bulkDecisionAction:Oe,decisionMutation:I}}const Ui=[{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 Zl(e){return Ui.find(t=>t.id===e)??Ui[0]}function Vi(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=Ui.find(i=>i.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function Zd(e,t=Date.now()){const s=Vi(e,t);return s?new Date(s).toISOString():null}const Ur="orgx.sandbox_mode",Wr="orgx.demo_mode",pa="orgx.dev_mode",Lr="orgx.show_synthetic_entities",La="orgx.selected_workspace_id",mr="orgx.onboarding.skip",eu=new Set(["ungrouped","unscoped","unknown"]);function gi(e){const t=(e??"").trim().toLowerCase();return!!(!t||eu.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Oi(){if(typeof window>"u")return!1;try{const e=new URLSearchParams(window.location.search);if(e.get("sandbox")==="1"||e.get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(Ur)==="1"||window.localStorage.getItem(Wr)==="1"}catch{return!1}}function Kn(){return Oi()}function tu(){if(typeof window>"u")return!1;if(Kn())return!0;try{return window.localStorage.getItem(Lr)==="1"}catch{return!1}}function nu(e){return Kn()?!0:!gi(e)}function Da(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ec(e,t){const s=Da(t.timestamp)-Da(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function su(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function iu(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 tc(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=su(e.metadata);return iu(s,["initiative_id","initiativeId"])}function fa(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Pa(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(!Pa(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]||!Pa(s[c],i[c]))return!1}return!0}const ru=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function mi(e,...t){}function au(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&&tc(p)!==i){d++;continue}const g=Da(p.timestamp);if(g){if(a!==null&&g<a){u++;continue}if(l!==null&&g>l){u++;continue}r.set(p.id,p)}}return mi("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(ec)}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||!Pa(c.metadata??null,l.metadata??null))&&(s.set(l.id,l),a=!0,r++)}return mi("mergeById",{currentCount:e.length,incomingCount:t.length,added:i,updated:r,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(ec):e}function ou(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=Kn()}=e,p=o.useMemo(()=>fa(a),[a]),g=o.useMemo(()=>fa(l),[l]),v=o.useMemo(()=>fa(c),[c]),h=o.useMemo(()=>Vi(s),[s]),w=o.useMemo(()=>Zd(s),[s]),y=o.useMemo(()=>{if(s==="custom"){const de=(i==null?void 0:i.trim())??"";return de.length>0?de:null}return w},[i,w,s]),I=o.useMemo(()=>{if(s!=="custom")return null;const de=(r==null?void 0:r.trim())??"";return de.length>0?de:null},[r,s]),M=o.useMemo(()=>{if(y){const de=Date.parse(y);if(Number.isFinite(de))return de}return h},[h,y]),F=o.useMemo(()=>{if(!I)return null;const de=Date.parse(I);return Number.isFinite(de)?de:null},[I]),b=o.useMemo(()=>au(t,{sinceEpoch:M,untilEpoch:F},p,g),[t,M,F,p,g]),A=u?null:"",[H,j]=o.useState(b),[P,Z]=o.useState(()=>A),[E,D]=o.useState(!1),[ee,ve]=o.useState(null),[Ce,pe]=o.useState(null),Ae=o.useRef(null),re=o.useRef(!1),ne=o.useRef(b);ne.current=b;const G=o.useMemo(()=>`${p??""}|${g??""}|${s}|${y??""}|${I??""}|${v??""}|${u?"demo":"live"}`,[p,g,s,y,I,v,u]),ae=o.useRef(G);o.useEffect(()=>{ae.current!==G&&(ae.current=G,mi("RESET",{reason:"filter/run change",runId:p,initiativeId:g,projectId:v,timeFilterId:s,sinceIso:y,untilIso:I,seedCount:ne.current.length}),j(ne.current),Z(A),ve(null),pe(null),re.current=!1)},[G,A,p,g,v,s,y,I]),o.useEffect(()=>{j(de=>{const we=Eo(de,b);return we!==de&&mi("SSE_MERGE",{prevCount:de.length,seedCount:b.length,nextCount:we.length,delta:we.length-de.length}),we})},[b]);const De=o.useCallback(async()=>{if(u){Z(null),ve(null);return}if(P===null)return;if(Ae.current)return Ae.current;D(!0);const de=(async()=>{try{const we=new URLSearchParams;we.set("limit",String(Math.max(1,Math.min(500,d)))),P.trim().length>0&&we.set("cursor",P),y&&we.set("since",y),I&&we.set("until",I),p&&we.set("run",p),g&&we.set("initiative",g),v&&Ts(we,v);const C=await fetch(`/orgx/api/live/activity/page?${we.toString()}`,{headers:Ut({workspaceId:v})}),O=await C.json().catch(()=>null);if(!C.ok||!O){const ye=typeof(O==null?void 0:O.error)=="string"&&O.error.trim()||typeof(O==null?void 0:O.message)=="string"&&O.message.trim()||`Activity paging failed (${C.status})`;throw new Error(ye)}const U=Array.isArray(O.activities)?O.activities:[],K=U.filter(ye=>!g||tc(ye)===g);mi("PAGE_FETCH",{cursor:P,rawCount:U.length,afterFilter:K.length,filteredOut:U.length-K.length,initiativeId:g,runId:p,nextCursor:O.nextCursor??null}),j(ye=>{const Oe=Eo(ye,K);return mi("PAGE_MERGE",{prevCount:ye.length,pageCount:K.length,nextCount:Oe.length,added:Oe.length-ye.length}),Oe}),Z(O.nextCursor??null),pe(O.storeUpdatedAt??null),ve(null)}catch(we){const C=we instanceof Error?we.message:"";ve(C?en(C):"Activity paging failed"),Z(O=>O===""?null:O)}finally{D(!1),Ae.current=null}})();return Ae.current=de,de},[P,u,g,d,v,p,y,I]);return o.useEffect(()=>{P===""&&(re.current||(re.current=!0,De()))},[P,De]),{items:H,hasMore:P!==null,isLoadingMore:E,error:ee,storeUpdatedAt:Ce,loadMore:De,cutoffEpoch:M,sinceIso:y,untilIso:I}}const lu="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",cu="".trim().toLowerCase()==="true"||"".trim()==="1",du="".trim().toLowerCase()==="true"||"".trim()==="1",uu={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let ha=null,Ro=!1,Lo=!1,Ya=!1;function mu(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Yr(){return Ya||!cu?!1:du?!0:!mu()}function pu(){return Yr()?(ha||(ha=cn(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(Ya=!0,null))),ha):Promise.resolve(null)}function fu(e){if(Ro)return!0;try{return e.init(lu,uu),Ro=!0,!0}catch{return Ya=!0,!1}}async function Ja(){const e=await pu();return!e||!fu(e)?null:e}function hu(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 gu(){!Yr()||typeof window>"u"||Lo||(Lo=!0,hu(()=>{Ja()}))}function xu(e){if(!Yr())return;const t=e.trim();t&&Ja().then(s=>{if(s)try{s.identify(t)}catch{}})}function Is(e,t){Yr()&&e.trim()&&Ja().then(s=>{if(s)try{s.capture(e,t)}catch{}})}function si(e,t){const s=e.hasApiKey&&e.connectionVerified,i={...e,...t};return s&&(t.status==="pairing"||t.status==="awaiting_browser_auth")?(i.hasApiKey=!0,i.connectionVerified=!0,i.workspaceName=e.workspaceName??t.workspaceName??null):!t.workspaceName&&e.workspaceName&&(i.workspaceName=e.workspaceName),(!t.installationId||t.installationId.trim().length===0)&&e.installationId&&(i.installationId=e.installationId),(t.keySource==="none"||!t.keySource)&&e.keySource&&e.keySource!=="none"&&(i.keySource=e.keySource),i}const Ws="https://orgx.mintlify.site/guides/openclaw-plugin-setup",yu=1500,bu=680,vu=`<!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>`,$a={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:Ws,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function wu(e,t){return e.hasApiKey||e.connectionVerified||e.workspaceName?{...e,lastError:t,nextAction:e.nextAction??"connect"}:{...$a,status:"error",lastError:t,nextAction:"retry"}}function ga(e){if(typeof e=="string")return en(e);if(e&&typeof e=="object"){const t=e;if(typeof t.error=="string")return en(t.error);if(typeof t.message=="string")return en(t.message)}}async function ii(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:ga(s==null?void 0:s.error)??ga(s==null?void 0:s.message)??ga(s)??en(`Request failed (${t.status})`)}}function Si(e){if(e)try{xu(e)}catch{}}function ku(){const[e,t]=o.useState($a),s=o.useRef(e),[i,r]=o.useState(!0),[a,l]=o.useState(!1),[c,d]=o.useState(!1),u=o.useRef(null),[p,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(mr)==="1");o.useEffect(()=>{s.current=e},[e]),o.useEffect(()=>{!Oi()&&p&&g(!1)},[p]);const v=o.useCallback(async()=>{const A=await ii(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!A.ok||!A.data){const j=A.error??"Failed to load onboarding state",P=wu(s.current,j);return t(P),P}const H={...si(s.current,A.data),docsUrl:A.data.docsUrl??s.current.docsUrl??Ws};return Si(H.installationId??null),t(H),H},[]);o.useEffect(()=>{let A=!1;return(async()=>{r(!0);const H=await v();A||(t(H),r(!1))})(),()=>{A=!0}},[v]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"||e.status==="connected"&&typeof e.pairingId=="string"&&e.pairingId.trim().length>0&&typeof e.connectUrl=="string"&&e.connectUrl.trim().length>0))return;const H=Math.max(900,e.pollIntervalMs??yu),j=window.setInterval(async()=>{const P=await ii(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(P.ok&&P.data){const Z={...si(s.current,P.data),docsUrl:P.data.docsUrl??s.current.docsUrl??Ws};Si(Z.installationId??null),t(Z)}},H);return()=>{window.clearInterval(j)}},[e.connectUrl,e.connectionVerified,e.pairingId,e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(!Oi()){window.localStorage.removeItem(mr);return}if(p){window.localStorage.setItem(mr,"1");return}window.localStorage.removeItem(mr)}},[p]);const h=o.useCallback(()=>{if(typeof window>"u")return null;try{const A=window.open("","_blank");return A?(A.opener=null,A.document.title="Connecting to OrgX…",A.document.open(),A.document.write(vu),A.document.close(),A):null}catch{return null}},[]),w=o.useCallback(async()=>{const A=h();u.current=A,l(!0);try{const H=await ii(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),j=H.data;if(!H.ok||!(j!=null&&j.state)){A&&!A.closed&&A.close();const Z=H.error??"Could not start pairing";t(E=>({...E,status:"error",lastError:Z,nextAction:"enter_manual_key"}));return}t({...si(s.current,j.state),docsUrl:j.state.docsUrl??s.current.docsUrl??Ws});const P=j.connectUrl;if(P){const Z=u.current;let E=!1;if(Z&&!Z.closed)try{window.setTimeout(()=>{if(!Z.closed)try{Z.location.href=P}catch{}},bu),E=!0}catch{E=!1}E||(E=!!window.open(P,"_blank","noopener,noreferrer")),E||t(D=>({...D,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{u.current=null,l(!1)}},[h]),y=o.useCallback(async A=>{d(!0);try{const H=A.trim(),j=H.replace(/^[a-z]+_/i,""),P=Array.from(new Set([H,j?`oxk_${j}`:"",j?`orgx_${j}`:""].map(E=>E.trim()).filter(E=>E.length>0)));let Z="Manual key validation failed";for(const E of P){const D={"Content-Type":"application/json","X-OrgX-Api-Key":E,Authorization:`Bearer ${E}`},ee=await ii(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:D,body:JSON.stringify({apiKey:E})}));if(ee.ok&&ee.data){const ve={...si(s.current,ee.data),docsUrl:ee.data.docsUrl??s.current.docsUrl??Ws};return Si(ve.installationId??null),t(ve),ve}Z=ee.error??Z}throw t(E=>({...E,status:"manual_key",lastError:Z,nextAction:"enter_manual_key"})),new Error(Z)}finally{d(!1)}},[]),I=o.useCallback(async()=>{const A=await ii(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(A.ok&&A.data){const j={...si(s.current,A.data),docsUrl:A.data.docsUrl??s.current.docsUrl??Ws};return Si(j.installationId??null),t(j),j}const H={...$a,status:"idle"};return t(H),H},[]),M=o.useCallback(async()=>{const A=await ii(fetch("/orgx/api/onboarding/cancel",{method:"POST"}));if(A.ok&&A.data){const j={...si(s.current,A.data),docsUrl:A.data.docsUrl??s.current.docsUrl??Ws};return Si(j.installationId??null),t(j),j}const H=await v();return t(H),H},[v]),F=o.useCallback(()=>{t(A=>({...A,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),b=o.useMemo(()=>e.hasApiKey&&e.connectionVerified&&(e.status==="connected"||e.status==="pairing"||e.status==="awaiting_browser_auth")?!1:!(p&&Oi()),[p,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:b,isLoading:i,isStarting:a,isSubmittingManual:c,refreshStatus:v,startPairing:w,submitManualKey:y,cancelPairing:M,disconnect:I,skipGate:()=>g(!0),resumeGate:()=>g(!1),backToPairing:F,setManualMode:()=>t(A=>({...A,status:"manual_key",nextAction:"enter_manual_key"}))}}const cs={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 Iu extends Error{constructor(s,i){super(s);os(this,"code","upgrade_required");os(this,"currentPlan");os(this,"requiredPlan");os(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 Nu(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 Iu(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 bx(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 nc extends Error{constructor(s){super(s.message);os(this,"status");os(this,"code");os(this,"errorLocation");os(this,"retryable");os(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 ju(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Wi(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 Au(e,t){if(e.status!==404)return!1;const s=Wi(t,["error"])??"",i=Wi(t,["message"])??"";return/unknown api endpoint/i.test(`${s} ${i}`)}function _u(e,t,s){if(Au(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=Wi(t,["error","message"])??`${s} (${e.status})`;return en(i)}function xa(e,t,s){const i=ju(t),r=_u(e,i,s),a=Wi(i,["code"]),l=Wi(i,["error_location","errorLocation"]),c=i==null?void 0:i.retryable,d=typeof c=="boolean"?c:!1;return new nc({message:r,status:e.status,code:a,errorLocation:l,retryable:d,details:i})}function vx(e){return e instanceof nc}const sc=750;async function Oa(e,t){const{initiativeId:s=null,projectId:i=null,authToken:r=null,embedMode:a=!1,queueQueryKey:l,includeQueue:c=!0,includeGraph:d=!0,includeSlices:u=!0,includeAutoContinue:p=!0,includeLiveData:g=!0}=t,v=[];c&&(l?v.push(e.invalidateQueries({queryKey:l})):v.push(e.invalidateQueries({queryKey:["mission-control-next-up"]}))),d&&v.push(e.invalidateQueries({queryKey:cs.missionControlGraph({initiativeId:s,authToken:r,embedMode:a})})),u&&v.push(e.invalidateQueries({queryKey:["mission-control-slices"]})),p&&v.push(e.invalidateQueries({queryKey:cs.autoContinueStatus({initiativeId:s,authToken:r,embedMode:a})})),g&&(v.push(e.invalidateQueries({queryKey:cs.liveData({authToken:r,embedMode:a,projectId:i})})),v.push(e.invalidateQueries({queryKey:["live-data"]}))),await Promise.all(v)}function ri(e,t){return e&&{...e,pages:e.pages.map(s=>({...s,items:s.items.map(i=>t(i))}))}}async function pr(e){return await e.json().catch(()=>null)}function Su(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 Cu(e,t,s){if(Su(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 en(i)}function Tu(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?en(s):t}function Mu(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 qa({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 Eu(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 Ru(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;return!(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")}function ic(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 rc(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 Lu(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=ic(typeof l.id=="string"?l.id:null),d=rc(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 Du(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function Pu(e){const t=ic(e.runnerAgentId),s=rc(e.runnerAgentName,t),i=Lu(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=Du(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:Ru(e),autoRuntimeState:Eu(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 qa(e){var u,p,g,v,h;const t=e.items.map(w=>Pu(w)),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,summary:e.summary?{visibleTotal:typeof e.summary.visibleTotal=="number"&&Number.isFinite(e.summary.visibleTotal)?Math.max(0,Math.floor(e.summary.visibleTotal)):t.filter(w=>w.queueState!=="running"&&w.queueState!=="completed").length,stateCounts:{queued:Math.max(0,Math.floor(((u=e.summary.stateCounts)==null?void 0:u.queued)??0)),running:Math.max(0,Math.floor(((p=e.summary.stateCounts)==null?void 0:p.running)??0)),blocked:Math.max(0,Math.floor(((g=e.summary.stateCounts)==null?void 0:g.blocked)??0)),idle:Math.max(0,Math.floor(((v=e.summary.stateCounts)==null?void 0:v.idle)??0)),completed:Math.max(0,Math.floor(((h=e.summary.stateCounts)==null?void 0:h.completed)??0))}}:void 0,pagination:{offset:r,limit:a,total:s,nextCursor:d,hasMore:c}}}function $u(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 Ou(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 qu({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 re,ne,G,ae,De,Te,de,we;const u=Xa(),p=Kn(),g=Math.max(0,s),v=Math.max(1,Math.min(300,i)),h=o.useRef(null);o.useEffect(()=>()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]);const w=o.useMemo(()=>cs.nextUpQueue({initiativeId:e,projectId:t,offset:g,limit:v,authToken:r,embedMode:a}),[e,t,g,v,r,a]),y=o.useCallback((C,O)=>{const U=cs.autoContinueStatus({initiativeId:C,authToken:r,embedMode:a});u.setQueryData(U,K=>{const ye=K&&typeof K=="object"?K:null;return{ok:!0,initiativeId:C,run:O,defaults:(ye==null?void 0:ye.defaults)??{tokenBudget:null,tickMs:0}}})},[r,a,u]),I=o.useRef(c);o.useEffect(()=>{c!==null&&I.current!==null&&c!==I.current&&u.invalidateQueries({queryKey:w}),I.current=c},[c,u,w]);const M=()=>{h.current&&(clearTimeout(h.current),h.current=null),h.current=setTimeout(()=>{h.current=null,u.invalidateQueries({queryKey:cs.liveData({authToken:r,embedMode:a,projectId:t})})},sc)},F=async({includeGraph:C=!0,includeLiveData:O=!0}={})=>{await Oa(u,{initiativeId:e,projectId:t,authToken:r,embedMode:a,queueQueryKey:w,includeGraph:C,includeSlices:!1,includeLiveData:!1}),O&&M()},b=async(C,O)=>{if(p)return Mu(e);const U=new URLSearchParams;e&&U.set("initiative_id",e),Ts(U,t,{allTokenWhenMissing:!0}),U.set("offset",String(C)),U.set("limit",String(O));let K;try{K=await fetch(`/orgx/api/mission-control/next-up?${U.toString()}`,{headers:Ut({authToken:r,embedMode:a})})}catch(T){throw new Error(Tu(T,"Failed to load next up queue"))}const ye=await pr(K);if(!K.ok){const T=Cu(K,ye,"Failed to load next up queue");throw new Error(T)}const Oe=ye??null;if(!Oe||Oe.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:C,limit:O,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(tu())return qa(Oe);const me=Oe.items.filter(T=>!gi(T.initiativeId));return qa({...Oe,items:me})},A=td({queryKey:w,enabled:l,initialPageParam:g,queryFn:async({pageParam:C})=>{const O=typeof C=="number"&&Number.isFinite(C)?Math.max(0,Math.floor(C)):g;return await b(O,v)},getNextPageParam:C=>{const O=C.pagination;if(!(O!=null&&O.hasMore)||!O.nextCursor)return;const U=Number.parseInt(O.nextCursor,10);if(Number.isFinite(U))return Math.max(0,Math.floor(U))},refetchInterval:C=>{var K;const O=(K=C.state.data)==null?void 0:K.pages;return!O||O.length===0?1e4:O.some(ye=>Array.isArray(ye.items)&&ye.items.some(Oe=>Oe.queueState==="running"))?2500:8e3}}),H=$n({mutationFn:async C=>{if(p)return{ok:!0,initiativeId:C.initiativeId,workstreamId:C.workstreamId,dispatchMode:"slice",sessionId:null};const O=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:Ut({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:C.initiativeId,workstreamId:C.workstreamId,workspaceId:t??void 0,agentId:C.agentId??void 0,scope:C.scope??void 0,maxParallelSlices:typeof C.maxParallelSlices=="number"&&Number.isFinite(C.maxParallelSlices)?Math.max(1,Math.floor(C.maxParallelSlices)):void 0,parallelMode:C.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),U=await pr(O);if(!O.ok)throw xa(O,U,"Failed to dispatch queued workstream");return U??{ok:!0,initiativeId:C.initiativeId,workstreamId:C.workstreamId,agentId:C.agentId??void 0,dispatchMode:"none",sessionId:null}},onMutate:async C=>{await u.cancelQueries({queryKey:w});const O=u.getQueryData(w);return u.setQueryData(w,ri(O,U=>U.initiativeId!==C.initiativeId||U.workstreamId!==C.workstreamId?U:{...U,queueState:"running",playbackState:"running"})),{previous:O}},onError:(C,O,U)=>{U!=null&&U.previous&&u.setQueryData(w,U.previous)},onSuccess:(C,O)=>{O.initiativeId&&y(O.initiativeId,C.dispatchMode==="none"?null:{id:C.sessionId??`${O.initiativeId}:${O.workstreamId}:play`,initiativeId:O.initiativeId,agentId:O.agentId??"auto",agentName:null,tokenBudget:null,tokensUsed:0,status:"running",stopRequested:!1,updatedAt:new Date().toISOString(),startedAt:new Date().toISOString(),stoppedAt:null,lastError:null,lastTaskId:null,lastRunId:C.sessionId??null,activeTaskId:null,activeRunId:C.sessionId??null,stopReason:null,activeSliceRunIds:C.sessionId?[C.sessionId]:[],activeTaskIds:[],maxParallelSlices:O.maxParallelSlices??1,parallelMode:O.parallelMode??"iwmt"}),u.setQueryData(w,U=>ri(U,K=>K.initiativeId!==O.initiativeId||K.workstreamId!==O.workstreamId?K:{...K,queueState:C.dispatchMode==="none"?K.queueState:"running",playbackState:C.dispatchMode==="none"?K.playbackState:"running"})),F({includeGraph:!1})}}),j=$n({mutationFn:async C=>{if(p)return{ok:!0,initiativeId:C.initiativeId,workstreamIds:[C.workstreamId],run:null};const O={initiativeId:C.initiativeId,workspaceId:t??void 0,agentId:C.agentId??void 0,tokenBudgetTokens:C.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};C.scope==="workstream"&&C.workstreamId&&(O.workstreamIds=[C.workstreamId]),typeof C.maxParallelSlices=="number"&&Number.isFinite(C.maxParallelSlices)&&(O.maxParallelSlices=C.maxParallelSlices),C.parallelMode==="iwmt"&&(O.parallelMode=C.parallelMode);const U=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:Ut({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(O)}),K=await pr(U);if(!U.ok){const ye=Nu(K);throw ye||xa(U,K,"Failed to start auto-continue")}return K??{ok:!0,initiativeId:C.initiativeId,workstreamIds:[C.workstreamId],run:null}},onMutate:async C=>{await u.cancelQueries({queryKey:w});const O=u.getQueryData(w);return u.setQueryData(w,ri(O,U=>{var ye,Oe;return U.initiativeId!==C.initiativeId||!(U.workstreamId===C.workstreamId||C.scope!=="workstream")?U:{...U,autoContinue:{...U.autoContinue??{status:"running",activeTaskId:null,activeRunId:null,stopReason:null,maxParallelSlices:C.maxParallelSlices??1,parallelMode:C.parallelMode??"iwmt",updatedAt:new Date().toISOString()},status:"running",stopReason:null,maxParallelSlices:C.maxParallelSlices??((ye=U.autoContinue)==null?void 0:ye.maxParallelSlices)??1,parallelMode:C.parallelMode??((Oe=U.autoContinue)==null?void 0:Oe.parallelMode)??"iwmt",updatedAt:new Date().toISOString()}}})),{previous:O}},onError:(C,O,U)=>{U!=null&&U.previous&&u.setQueryData(w,U.previous)},onSuccess:(C,O)=>{y(O.initiativeId,C.run??null),u.setQueryData(w,U=>ri(U,K=>{var Oe;return K.initiativeId!==O.initiativeId||!(K.workstreamId===O.workstreamId||O.scope!=="workstream")?K:{...K,autoContinue:C.run?{status:C.run.status,activeTaskId:C.run.activeTaskId??null,activeRunId:C.run.activeRunId??((Oe=C.run.activeSliceRunIds)==null?void 0:Oe[0])??C.run.lastRunId??null,stopReason:C.run.stopReason,maxParallelSlices:C.run.maxParallelSlices,parallelMode:C.run.parallelMode,updatedAt:C.run.updatedAt}:K.autoContinue}})),F({includeGraph:!1})}}),P=$n({mutationFn:async C=>{if(p)return{ok:!0,initiativeId:C.initiativeId,run:null};const O=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ut({authToken:r,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:C.initiativeId})}),U=await pr(O);if(!O.ok)throw xa(O,U,"Failed to stop auto-continue");return U??{ok:!0,initiativeId:C.initiativeId,run:null}},onMutate:async C=>{await u.cancelQueries({queryKey:w});const O=u.getQueryData(w);return u.setQueryData(w,ri(O,U=>U.initiativeId!==C.initiativeId||!U.autoContinue?U:{...U,autoContinue:{...U.autoContinue,status:"stopping",updatedAt:new Date().toISOString()}})),{previous:O}},onError:(C,O,U)=>{U!=null&&U.previous&&u.setQueryData(w,U.previous)},onSuccess:(C,O)=>{y(O.initiativeId,C.run??null),u.setQueryData(w,U=>ri(U,K=>{var ye;return K.initiativeId!==O.initiativeId||!K.autoContinue?K:{...K,autoContinue:C.run?{status:C.run.status,activeTaskId:C.run.activeTaskId??null,activeRunId:C.run.activeRunId??((ye=C.run.activeSliceRunIds)==null?void 0:ye[0])??C.run.lastRunId??null,stopReason:C.run.stopReason,maxParallelSlices:C.run.maxParallelSlices,parallelMode:C.run.parallelMode,updatedAt:C.run.updatedAt}:null}})),F({includeGraph:!1})}}),Z=o.useMemo(()=>{var K;const C=((K=A.data)==null?void 0:K.pages)??[];if(C.length===0)return[];const O=new Set,U=[];for(const ye of C)for(const Oe of ye.items){const me=`${Oe.initiativeId}:${Oe.workstreamId}`;O.has(me)||(O.add(me),U.push(Oe))}return U},[(re=A.data)==null?void 0:re.pages]),E=o.useMemo(()=>{var U;const C=((U=A.data)==null?void 0:U.pages)??[];let O=0;for(const K of C)typeof K.total=="number"&&Number.isFinite(K.total)&&(O=Math.max(O,K.total));return Math.max(O,Z.length)},[Z.length,(ne=A.data)==null?void 0:ne.pages]),D=o.useMemo(()=>{var me;const C=((me=A.data)==null?void 0:me.pages)??[];if(C.length===0)return null;const O=C[0],U=C[C.length-1],K=O.pagination,ye=U.pagination,Oe=!!A.hasNextPage;return{offset:K&&Number.isFinite(K.offset)?Math.max(0,Math.floor(K.offset)):g,limit:K&&Number.isFinite(K.limit)?Math.max(1,Math.floor(K.limit)):v,total:E,nextCursor:Oe?(ye==null?void 0:ye.nextCursor)??String(((ye==null?void 0:ye.offset)??g)+((ye==null?void 0:ye.limit)??v)):null,hasMore:Oe}},[E,v,g,(G=A.data)==null?void 0:G.pages,A.hasNextPage]),ee=((De=(ae=A.data)==null?void 0:ae.pages[0])==null?void 0:De.generatedAt)??null,ve=o.useMemo(()=>{var ye,Oe,me,ke,T,be;const C=((ye=A.data)==null?void 0:ye.pages)??[];if(C.length===0)return null;let O=0;const U={queued:0,running:0,blocked:0,idle:0,completed:0};let K=!1;for(const Y of C)Y.summary&&(K=!0,O=Math.max(O,Y.summary.visibleTotal??0),U.queued=Math.max(U.queued,((Oe=Y.summary.stateCounts)==null?void 0:Oe.queued)??0),U.running=Math.max(U.running,((me=Y.summary.stateCounts)==null?void 0:me.running)??0),U.blocked=Math.max(U.blocked,((ke=Y.summary.stateCounts)==null?void 0:ke.blocked)??0),U.idle=Math.max(U.idle,((T=Y.summary.stateCounts)==null?void 0:T.idle)??0),U.completed=Math.max(U.completed,((be=Y.summary.stateCounts)==null?void 0:be.completed)??0));return K?{visibleTotal:O,stateCounts:U}:null},[(Te=A.data)==null?void 0:Te.pages]),Ce=o.useMemo(()=>{var U;const C=((U=A.data)==null?void 0:U.pages)??[],O=new Set;for(const K of C)for(const ye of K.degraded??[])typeof ye=="string"&&ye.trim().length>0&&O.add(ye);return Array.from(O)},[(de=A.data)==null?void 0:de.pages]),pe=o.useMemo(()=>d==="initiative"?$u(Z):[],[Z,d]),Ae=o.useMemo(()=>d==="milestone"?Ou(Z):[],[Z,d]);return{items:Z,total:E,summary:ve,pagination:D,generatedAt:ee,degraded:Ce,isLoading:A.isLoading,isFetching:A.isFetching,isFetchingNextPage:A.isFetchingNextPage,hasNextPage:!!A.hasNextPage,error:((we=A.error)==null?void 0:we.message)??null,refetch:A.refetch,fetchNextPage:A.fetchNextPage,playWorkstream:H.mutateAsync,startWorkstreamAutoContinue:j.mutateAsync,stopInitiativeAutoContinue:P.mutateAsync,isPlaying:H.isPending,isStartingAutoContinue:j.isPending,isStoppingAutoContinue:P.isPending,zoomLevel:d,initiativeGroups:pe,milestoneGroups:Ae}}async function _n(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 Sn(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 en(i)}function Bu(e){const t=e.authToken??null,s=e.embedMode??!1,i=e.projectId??null,r=Kn(),a=Xa(),l=o.useRef(null);o.useEffect(()=>()=>{l.current&&(clearTimeout(l.current),l.current=null)},[]);const c=()=>{l.current&&(clearTimeout(l.current),l.current=null),l.current=setTimeout(()=>{l.current=null,Oa(a,{projectId:i,authToken:t,embedMode:s,includeQueue:!1,includeGraph:!1,includeSlices:!1,includeAutoContinue:!1})},sc)},d=async()=>{await Oa(a,{projectId:i,authToken:t,embedMode:s}),c()},u=async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId,placement:b.placement??"top"};const A=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await _n(A);if(A.ok)return H;if(!di(A,H))throw new Error(Sn(A,H,"Failed to move Next Up item"));const j=new URLSearchParams;Ts(j,i,{allTokenWhenMissing:!0});const P=await fetch(`/orgx/api/mission-control/next-up?${j.toString()}`,{headers:Ut({authToken:t,embedMode:s})}),Z=await _n(P);if(!P.ok)throw new Error(Sn(P,Z,"Failed to read queue for move fallback"));const D=(Array.isArray(Z==null?void 0:Z.items)?Z.items:[]).map(Ae=>{const re=typeof(Ae==null?void 0:Ae.initiativeId)=="string"?Ae.initiativeId:null,ne=typeof(Ae==null?void 0:Ae.workstreamId)=="string"?Ae.workstreamId:null;return!re||!ne?null:{initiativeId:re,workstreamId:ne}}).filter(Ae=>!!Ae);if(D.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const ee=D.findIndex(Ae=>Ae.initiativeId===b.initiativeId&&Ae.workstreamId===b.workstreamId);if(ee===-1)return{ok:!0,fallback:"reorder-move-skip"};const[ve]=D.splice(ee,1);(b.placement??"top")==="bottom"?D.push(ve):D.unshift(ve);const Ce=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:D})}),pe=await _n(Ce);if(!Ce.ok)throw new Error(Sn(Ce,pe,"Failed to move Next Up item with reorder fallback"));return pe??{ok:!0,fallback:"reorder-move"}},p=async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId};const A=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await _n(A);if(A.ok)return H;if(di(A,H)){const j=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),P=await _n(j);if(!j.ok)throw new Error(Sn(j,P,"Failed to remove item from queue with legacy fallback"));return P??{ok:!0,fallback:"next-up-unpin"}}throw new Error(Sn(A,H,"Failed to remove item from queue"))},g=$n({mutationFn:async b=>{if(r)return{ok:!0,demo:!0};const A=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await _n(A);if(!A.ok)throw new Error(Sn(A,H,"Failed to pin Next Up item"))},onSuccess:()=>{d()}}),v=$n({mutationFn:async b=>{if(r)return{ok:!0,demo:!0};const A=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await _n(A);if(!A.ok)throw new Error(Sn(A,H,"Failed to unpin Next Up item"))},onSuccess:()=>{d()}}),h=$n({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,updated:b.order.length};const A=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await _n(A);if(!A.ok)throw new Error(Sn(A,H,"Failed to reorder Next Up queue"))},onSuccess:()=>{d()}}),w=$n({mutationFn:u,onSuccess:()=>{d()}}),y=$n({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId};const A=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await _n(A);if(!A.ok){if(di(A,H)){const j=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:b.initiativeId})}),P=await _n(j);if(!j.ok)throw new Error(Sn(j,P,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(Sn(A,H,"Failed to stop triage"))}return H},onSuccess:()=>{d()}}),I=$n({mutationFn:p,onSuccess:()=>{d()}}),M=$n({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,cleared:!0};const A=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await _n(A);if(!A.ok){if(di(A,H)&&b.initiativeId){const j=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:b.initiativeId})}),P=await _n(j);if(!j.ok)throw new Error(Sn(j,P,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(Sn(A,H,"Failed to clear Next Up lifecycle state"))}return H},onSuccess:()=>{d()}}),F=$n({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,updated:b.items.length,failed:0,errors:[],fallback:"demo"};const A=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:Ut({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),H=await _n(A);if(!A.ok){if(!di(A,H))throw new Error(Sn(A,H,"Failed to apply bulk queue action"));const j=await Promise.all(b.items.map(async D=>{try{return b.action==="remove"?await p(D):await u({initiativeId:D.initiativeId,workstreamId:D.workstreamId,placement:b.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(ee){return{ok:!1,error:ee instanceof Error?ee.message:"Queue action failed"}}})),P=j.filter(D=>D.ok).length,Z=j.length-P,E=j.filter(D=>!D.ok&&D.error).map(D=>D.error);return{ok:Z===0,updated:P,failed:Z,errors:E,fallback:"sequential"}}return H},onSuccess:()=>{d()}});return{pin:g.mutateAsync,unpin:v.mutateAsync,reorder:h.mutateAsync,move:w.mutateAsync,remove:I.mutateAsync,stopTriage:y.mutateAsync,clear:M.mutateAsync,bulk:F.mutateAsync,isPinning:g.isPending,isUnpinning:v.isPending,isReordering:h.isPending,isMoving:w.isPending,isRemoving:I.isPending,isStoppingTriage:y.isPending,isClearing:M.isPending,isBulking:F.isPending}}function ac(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function Fu(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:ac(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(en(String(d)))}return l.json()}async function zu(e,t,s,i){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,l=await fetch(a,{method:"POST",headers:ac(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(en(String(d)))}return l.json()}function Uu(e={}){const{enabled:t=!0,workspaceId:s=null,status:i="open",authToken:r=null,embedMode:a=!1}=e,l=Xa(),c=cs.triageQueue({workspaceId:s,status:i,authToken:r,embedMode:a}),d=Zs({queryKey:c,queryFn:()=>Fu(s,i,r,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=$n({mutationFn:async({itemId:h,payload:w})=>zu(h,w,r,a),onSuccess:()=>{l.invalidateQueries({queryKey:c})}}),p=o.useCallback(async(h,w,y)=>u.mutateAsync({itemId:h,payload:{action:w,note:y==null?void 0:y.note,optionId:y==null?void 0:y.optionId,snoozeDurationMinutes:y==null?void 0:y.snoozeDurationMinutes}}),[u]),g=o.useMemo(()=>{var h,w,y;return{items:((h=d.data)==null?void 0:h.items)??[],total:((w=d.data)==null?void 0:w.total)??0,isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,degraded:((y=d.data)==null?void 0:y.degraded)??[],refetch:d.refetch}},[d]),v=o.useMemo(()=>({performAction:p,isActing:u.isPending,lastActionError:u.error?u.error.message:null}),[p,u.isPending,u.error]);return{model:g,actions:v}}function ue(...e){return e.filter(Boolean).join(" ")}const L={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"},Di={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)"}},oc={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Ba={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 lc(e){if(Ba[e])return{domain:Ba[e],color:oc[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 Za(e){var t;return oc[e]??((t=lc(e))==null?void 0:t.color)??"rgba(255, 255, 255, 0.4)"}function Hi(e){var t;return Ba[e]??((t=lc(e))==null?void 0:t.domain)??null}function Wu(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function Bt(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const Xt={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}},wx={surfaceSwitch:{duration:Xt.durationStandard/1e3,ease:Xt.easingStandard},contentCrossFade:{initial:{opacity:0,y:3},animate:{opacity:1,y:0},exit:{opacity:0,y:-3},transition:{duration:Xt.durationFast/1e3,ease:Xt.easingStandard}},railMorphSpring:{type:"spring",stiffness:340,damping:38,mass:.72},listStaggerStep:.016,listStaggerMaxItems:6,segmentedTap:{whileTap:{scale:.985},transition:{duration:.09}}},fr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{delay:Math.min(e,8)*.04,duration:Xt.durationStandard/1e3,ease:Xt.easingStandard}})},kx={initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.2,ease:Xt.easingStandard}},Jr="/orgx/live/assets/Fm0FhtnV.png";function cc({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 an({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??L.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??L.lime;return n.jsx(cc,{size:s,className:t,stroke:l,strokeWidth:r.strokeWidth,withBackground:!0,backgroundColor:`${l}1A`})}if(e==="milestone"){const l=i??L.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??L.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??L.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??L.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??L.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??L.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??L.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??L.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??L.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 Hu=[{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"}],Dr=[{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."}],Ku=[{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."}],Po="openclaw plugins install @useorgx/openclaw-plugin",Vu=6500;function Gu(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 Xu={hidden:{},visible:{transition:{staggerChildren:.07}}},Ns={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},Qu={initiative:"text-[#A8A0FF]",workstream:"text-lime",milestone:"text-[#43E7D8]",task:"text-primary",session:"text-[#43E7D8]",active:"text-lime",blocked:"text-[#FF6B88]",failed:"text-[#FF6B88]",handoff:"text-[#A8A0FF]",outbox:"text-[#F5D37A]",decision:"text-[#F5D37A]",notification:"text-[#7EEDE1]"};function ya(e){const t=Dr.length;return(e+t)%t}function Yu({state:e,isStarting:t,onConnect:s,onUseManualKey:i,onContinueWithoutOrgX:r}){const a=!!e.lastError,l=e.lastError?en(e.lastError):null,[c,d]=o.useState("idle"),[u,p]=o.useState("idle"),[g,v]=o.useState(0),[h,w]=o.useState(!1),y=e.hasApiKey&&e.keySource&&e.keySource!=="none",I=Dr[g];o.useEffect(()=>{if(c==="idle")return;const b=window.setTimeout(()=>d("idle"),2e3);return()=>window.clearTimeout(b)},[c]),o.useEffect(()=>{if(u==="idle")return;const b=window.setTimeout(()=>p("idle"),2e3);return()=>window.clearTimeout(b)},[u]),o.useEffect(()=>{if(h)return;const b=window.setInterval(()=>{v(A=>ya(A+1))},Vu);return()=>window.clearInterval(b)},[h]);const M=async()=>{try{await navigator.clipboard.writeText(Po),d("ok")}catch{d("error")}},F=async()=>{try{const b={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(b,null,2)),p("ok")}catch{p("error")}};return n.jsxs(ce.section,{variants:Xu,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(ce.div,{variants:Ns,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Jr,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(ce.h2,{variants:Ns,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(an,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(ce.p,{variants:Ns,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(ce.div,{variants:Ns,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:()=>w(!0),onMouseLeave:()=>w(!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(an,{type:"workstream",size:14,className:"text-lime"}),n.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-secondary",children:"Guided Tour"})]}),n.jsxs("span",{className:"chip text-micro",children:[g+1,"/",Dr.length]})]}),n.jsx(Nt,{initial:!1,mode:"wait",children:n.jsxs(ce.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:I.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:I.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:I.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:I.highlights.map(b=>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(an,{type:b.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:b.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:b.detail})]},`${I.id}-${b.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:I.footnote})]},I.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:Dr.map((b,A)=>{const H=A===g;return n.jsx("button",{type:"button",onClick:()=>v(A),"aria-label":`View slide ${A+1}`,className:`h-1.5 rounded-full transition-all ${H?"w-6 bg-lime":"w-2 bg-white/24 hover:bg-white/38"}`},b.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>v(b=>ya(b-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:()=>v(b=>ya(b+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:Hu.map(b=>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 ${Qu[b.iconType]}`,children:n.jsx(an,{type:b.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:b.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:b.desc})]},b.label))}),n.jsxs(ce.div,{variants:Ns,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-lime 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(ce.div,{variants:Ns,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(an,{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(an,{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:Po}),n.jsx("button",{type:"button",onClick:()=>{M()},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: ",Gu(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:Ku.map(b=>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(an,{type:b.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:b.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:b.detail})]},b.label))})]})]})]}),n.jsx(ce.div,{variants:Ns,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 F(),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(ce.div,{variants:Ns,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.jsx("div",{className:"flex flex-wrap items-center gap-3",children:n.jsx("button",{type:"button",onClick:()=>{try{window.localStorage.setItem(Ur,"1"),window.localStorage.removeItem(Wr)}catch{}r()},className:"text-left text-caption text-muted transition hover:text-secondary",children:"Open guided sandbox"})}),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 Ju={hidden:{},visible:{transition:{staggerChildren:.06}}},Us={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function Zu({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 g=/^[a-z]+_/i.test(p)?p:`oxk_${p}`;try{await t(g),r("")}catch(v){const h=v instanceof Error?v.message:"Failed to validate API key.";l(en(h))}},u=a!==null;return n.jsxs(ce.section,{variants:Ju,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(ce.div,{variants:Us,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:Jr,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(ce.h3,{variants:Us,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(ce.p,{variants:Us,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(ce.p,{variants:Us,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(ce.div,{variants:Us,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(ce.div,{variants:Us,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-lime/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(ce.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(ce.div,{variants:Us,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-lime 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 $o="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 em(){const[e,t]=o.useState(()=>qo($o)),[s,i]=o.useState(()=>qo(Oo)),r=(e||"orgx-user")+s,a=o.useCallback(c=>{const d=c.trim();Bo($o,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 tm(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function nm(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 Fo=[L.lime,L.teal,L.iris,L.cyan];function sm(e,t,s,i,r,a){const l=A=>A*Math.PI/180,c=Math.cos,d=Math.sin,u=l(r),p=l(a),g=a-r>180?1:0,v=e+i*c(u),h=t+i*d(u),w=e+i*c(p),y=t+i*d(p),I=e+s*c(p),M=t+s*d(p),F=e+s*c(u),b=t+s*d(u);return[`M ${v} ${h}`,`A ${i} ${i} 0 ${g} 1 ${w} ${y}`,`L ${I} ${M}`,`A ${s} ${s} 0 ${g} 0 ${F} ${b}`,"Z"].join(" ")}function im(e){const t=nm(tm(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,g=1.5+t()*2;for(let v=0;v<u;v++){if(t()<.15)continue;const h=v*p+g/2,w=(v+1)*p-g/2,y=Fo[Math.floor(t()*Fo.length)],I=.25+t()*.55;i.push({d:sm(r,a,c,d,h,w),fill:y,opacity:I})}}return i}function dc({seed:e,size:t,className:s,animate:i=!0}){const r=o.useMemo(()=>im(e),[e]);return n.jsxs(ce.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:Xt.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:L.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:L.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:L.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(ce.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:Xt.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 rm({onComplete:e}){const{displayName:t,updateName:s}=em(),[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(ce.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:Xt.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(dc,{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 am=[{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 om({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"]}),am.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 zo="orgx.user.name-asked";function lm(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 cm(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 dm(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Uo={idle:"bg-white/40",active:"bg-lime",error:"bg-red-400"},ba="orgx.onboarding.mc_hint.dismissed",va={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 um({state:e,isLoading:t,isStarting:s,isSubmittingManual:i,onRefresh:r,onStartPairing:a,onSubmitManualKey:l,onBackToPairing:c,onUseManualKey:d,onSkip:u}){const[p,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(ba)==="1"),[v,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(zo)!=="1"),w=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(zo,"1"),h(!1)},[]);o.useEffect(()=>{typeof window>"u"||(p?window.localStorage.setItem(ba,"1"):window.localStorage.removeItem(ba))},[p]);const y=e.status==="manual_key",I=e.status==="awaiting_browser_auth"||e.status==="pairing",M=dm(e.status),F=M==="active"&&e.status!=="connected",b=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(ce.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(Nt,{mode:"wait",children:e.status==="connected"&&v?n.jsx(ce.div,{...va,children:n.jsx(rm,{onComplete:w})},"welcome-name"):y?n.jsx(ce.div,{...va,children:n.jsx(Zu,{isSubmitting:i,onSubmit:l,onBack:c})},"manual"):n.jsx(ce.div,{...va,children:n.jsx(Yu,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(I||e.status==="connected")&&n.jsxs(ce.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:[F&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Uo[M]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Uo[M]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:lm(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:cm(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&&I&&n.jsx("a",{href:e.connectUrl,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-lime/25 bg-lime/[0.05] px-3 py-1 text-caption font-medium text-lime transition hover:bg-lime/[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"})]})]}),b&&n.jsxs(ce.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-lime/30 bg-lime/15 px-3 py-1 text-caption font-medium text-lime",children:"Open Mission Control"}),n.jsx("button",{type:"button",onClick:()=>g(!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(om,{compact:!0})})]})})}function mm({children:e,color:t,pulse:s,title:i}){const r=t??L.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 Zr({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 w=d.current;if(!w)return;const y=w.querySelector('[data-modal-autofocus="true"]');if(y){y.focus();return}const I=w.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');I.length>0?I[0].focus():w.focus()})();const v=w=>{if(w.key==="Escape"){if(!l)return;if(!c){const A=w.target;if(A&&(A.tagName==="INPUT"||A.tagName==="TEXTAREA"||A.tagName==="SELECT"||A.isContentEditable))return}w.preventDefault(),t();return}if(w.key!=="Tab")return;const y=d.current;if(!y)return;const I=y.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(I.length===0){w.preventDefault(),y.focus();return}const M=I[0],F=I[I.length-1],b=document.activeElement;!w.shiftKey&&b===F?(w.preventDefault(),M.focus()):w.shiftKey&&b===M&&(w.preventDefault(),F.focus())},h=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",v),()=>{var w;document.body.style.overflow=h,document.removeEventListener("keydown",v),(w=u.current)==null||w.focus()}},[e,t,l,c]);const p=n.jsx(Nt,{children:e&&n.jsxs(ce.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.22,ease:[.22,1,.36,1]},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(ce.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:L.cardBgElevated,borderColor:L.cardBorderStrong},onClick:g=>g.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:Zc.createPortal(p,document.body)}const pm=[{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 fm({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:pm.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(ce.span,{layoutId:"mobile-tab-active-pill",className:"absolute inset-0 rounded-[18px] border border-lime/28 bg-lime/[0.1]",transition:{type:"spring",stiffness:420,damping:34,mass:.8}}),n.jsx(ce.span,{layoutId:"mobile-tab-active-line",className:"absolute inset-x-3 top-0.5 h-[2px] rounded-full",style:{backgroundColor:L.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-lime/35 bg-lime/[0.12] text-lime":"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:L.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:ue("relative z-[1] text-micro font-medium",r?"text-lime":"text-secondary"),children:i.label})]},i.id)})})})}function Ss({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 hm={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"},gm={xs:24,sm:32,md:40,lg:64},xm="orgx.user.display-name",ym="orgx.user.avatar-seed-suffix",bm="/orgx/live/",Cn=e=>`${bm.replace(/\/+$/,"/")}${e}`,vm={pace:Cn("brand/product-orchestrator.png"),eli:Cn("brand/engineering-autopilot.png"),mark:Cn("brand/launch-captain.png"),sage:Cn("brand/pipeline-intelligence.png"),orion:Cn("brand/control-tower.png"),dana:Cn("brand/design-codex.png"),xandy:Cn("brand/xandy-orchestrator.png"),nova:Cn("brand/xandy-orchestrator.png"),openclaw:Cn("brand/openclaw-mark.svg"),codex:Cn("brand/openai-mark.svg"),openai:Cn("brand/openai-mark.svg"),anthropic:Cn("brand/anthropic-mark.svg"),orgx:Cn("brand/orgx-logo.png")},wm=[{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 km(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of wm)if(s.test.test(t))return vm[s.key];return null}function Im(e){return typeof e=="string"?e.trim().toLowerCase():""}function Wo(e){const t=Im(e);return t?!!(t==="you"||t==="main"||t==="me"||t==="user"||t==="usr"||t.startsWith("user_")||t.startsWith("usr_")):!1}function Nm(){if(typeof window>"u")return"orgx-user";try{const e=(window.localStorage.getItem(xm)??"").trim(),t=window.localStorage.getItem(ym)??"";return`${e||"orgx-user"}${t}`}catch{return"orgx-user"}}function Zt({name:e,size:t="xs",hint:s,src:i}){const r=Za(e),[a,l]=o.useState(!1),c=o.useMemo(()=>Wo(e)||Wo(s),[s,e]),d=o.useMemo(()=>c?Nm():null,[c]),u=o.useMemo(()=>i&&i.trim()?i:km(e,s),[s,e,i]),p=!!(!c&&u&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${hm[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(dc,{seed:d,size:gm[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"}):Wu(e)})}Zt.displayName="AgentAvatar";const jm={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 Pn({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",jm[t],s),...i,children:e})}function Am(e){var s,i;const t=[];if(e.initiativeId){const r={id:e.initiativeId,label:e.initiativeTitle||Qs(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=uc(e.status),l={id:e.workstreamId,label:e.workstreamTitle||Qs(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||Qs(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,g)=>({id:`${c.id}-task-${g}`,label:`Task ${g+1}`,type:"task",status:g<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:Qs(d,"Task"),type:"task",status:u<c?"done":"pending"}))}r.children.push(l)}t.push(r)}return t}function Ix(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||Qs(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,i=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||Qs(e.workstreamId,"Workstream"),type:"workstream",status:uc(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,r=e.taskId?{id:e.taskId,label:e.taskTitle||Qs(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 Qs(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function uc(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 _m(e){return e==="done"||e==="completed"?"done":e==="active"||e==="running"||e==="in_progress"?"active":e==="blocked"?"blocked":e==="failed"?"failed":"pending"}function Sm(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:_m(s.status)}))}))}function Cm(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 Nx=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?L.teal:`${L.lime}99`}})},r.id)})})}),Tm={active:Di.active,done:Di.done,blocked:Di.blocked,planned:Di.planned};function hr({label:e,count:t,tone:s,nodes:i,defaultOpen:r,compact:a}){const[l,c]=o.useState(r),d=Tm[s]??Di.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(ce.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(Nt,{initial:!1,children:l&&n.jsx(ce.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(fc,{nodes:i,compact:a})})})})]})}const Mm=o.memo(function({nodes:t,compact:s=!1}){const i=Cm(t);return n.jsxs("div",{className:"space-y-2",children:[i.blocked.length>0&&n.jsx(hr,{label:"BLOCKED",count:i.blocked.length,tone:"blocked",nodes:i.blocked,defaultOpen:!0,compact:s}),i.inProgress.length>0&&n.jsx(hr,{label:"IN PROGRESS",count:i.inProgress.length,tone:"active",nodes:i.inProgress,defaultOpen:!0,compact:s}),i.completed.length>0&&n.jsx(hr,{label:"COMPLETED",count:i.completed.length,tone:"done",nodes:i.completed,defaultOpen:!1,compact:s}),i.upcoming.length>0&&n.jsx(hr,{label:"UPCOMING",count:i.upcoming.length,tone:"planned",nodes:i.upcoming,defaultOpen:!1,compact:s})]})});function mc(e){switch(e){case"done":return L.lime;case"active":return L.teal;case"blocked":return L.amber;case"failed":return L.red;default:return"rgba(255,255,255,0.15)"}}function Em(e){const t=mc(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const Rm=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(ce.div,{className:"h-full rounded-full",style:{backgroundColor:i},initial:{width:0},animate:{width:`${r}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),Lm=16,Dm=14,Ho=8,Pm=8,$m=28,Om=24,qm=24,Bm=20,wa="rgba(255,255,255,0.07)";function Fm(e){const t=e?Dm:Lm,s=t+Pm+4;return{iconSz:t,colW:s,rowH:e?qm:$m,rowHTask:e?Bm:Om}}function pc({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,g=e.type==="task",{iconSz:v,colW:h,rowH:w,rowHTask:y}=Fm(r),I=g?y:w,M=e.children??[],F=M.filter(E=>E.type==="task"),b=M.filter(E=>E.type!=="task"),A=F.length>l&&!c,H=A?F.slice(0,l):F,j=F.length-H.length,P=[...b,...H],Z=P.length>0||A;return n.jsxs("div",{className:"relative",style:{minHeight:I},children:[t>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute w-px",style:{backgroundColor:wa,left:(t-1)*h+h/2,top:0,bottom:s?void 0:0,height:s?I/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:wa,left:(t-1)*h+h/2,top:I/2,width:h}})]}),n.jsxs(ce.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:I,paddingLeft:t*h},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:h,height:I},children:g?n.jsx("span",{className:"inline-block rounded-full",style:{...Em(e.status),width:Ho,height:Ho}}):n.jsx(an,{type:e.type,size:v,accent:u?L.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 ${g?`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&&!g&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(Rm,{done:e.progress.done,total:e.progress.total,color:mc(e.status)})})]})]}),Z&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:wa,left:t*h+h/2,top:I/2,height:I/2}}),Z&&n.jsxs("div",{children:[P.map((E,D)=>n.jsx(pc,{node:E,depth:t+1,isLast:D===P.length-1&&!A,activeId:i,compact:r,index:a+D+1,taskLimit:l,expanded:c,onToggleExpand:d},E.id)),A&&n.jsxs(ce.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+P.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:["+",j," more · see all"]}),n.jsx(Nt,{children:c&&F.length>l&&n.jsx(ce.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 fc=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(pc,{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))})}),Fa={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"}},zm=Object.keys(Fa);function Ko(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of zm)if(t.includes(s))return s;return"engineering"}function Vo(e){return Fa[e]??Fa.engineering}const ai={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Ci={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},Go={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},Xo={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 Um(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=Xo[i];if(r){const a=Ci[r]??"";return{name:r,domain:a,color:ai[r]??s.color,displayLabel:a?`${r} (${a})`:r}}for(const[a,l]of Object.entries(Go))if(i.includes(a)){const c=Ci[l]??"";return{name:l,domain:c,color:ai[l]??s.color,displayLabel:c?`${l} (${c})`:l}}}if(t){const i=t.trim();if(ai[i]){const l=Ci[i]??"";return{name:i,domain:l,color:ai[i],displayLabel:l?`${i} (${l})`:i}}const r=i.toLowerCase(),a=Xo[r];if(a){const l=Ci[a]??"";return{name:a,domain:l,color:ai[a]??s.color,displayLabel:l?`${a} (${l})`:a}}for(const[l,c]of Object.entries(Go))if(r.includes(l)){const d=Ci[c]??"";return{name:c,domain:d,color:ai[c]??s.color,displayLabel:d?`${c} (${d})`:c}}}return s}function jx({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(Zt,{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 Wm=new Set(["running","in_progress","working","dispatching"]),Hm=new Set(["running","dispatching"]),Km=3*6e4;function Qo(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=Km:!1}function Vm(e){const t=Bt(e.status??""),s=Bt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:Wm.has(t)?!0:t==="active"||s==="active"?Qo(e.lastHeartbeatAt):t==="queued"||t==="pending"||t==="planning"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?Qo(e.lastHeartbeatAt):!1}function hc(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function Gm(e){const t=Bt(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-lime/24 bg-lime/[0.10] text-lime"}function Xm(e){const t=Bt(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-lime/0 via-lime/70 to-lime/0"}function Qm(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function oi(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ks(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 za(e,t){if(!e)return t;const s=e.trim();return s?Hn(s)?`${t} ${As(s)}`:s:t}const Ym=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),Jm=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function Zm(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?Ym.has(t)||t.startsWith("telegram:"):!1}function ep(e){if(!e)return!1;const t=e.trim();return t?Jm.some(s=>s.test(t)):!1}function gc({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var I,M,F,b,A,H;const i=new Map;for(const j of s)j.id&&i.set(j.id,j.name??j.id);const r=new Map;for(const j of e){const P=(I=j.runId)==null?void 0:I.trim();!P||r.has(P)||r.set(P,j)}const a=new Map;for(const j of e){const P=((M=j.initiativeId)==null?void 0:M.trim())??"",Z=((F=j.workstreamId)==null?void 0:F.trim())??"";if(!P||!Z)continue;const E=`${P}:${Z}`;a.has(E)||a.set(E,j)}const l=new Set;for(const j of e){const P=(b=j.runId)==null?void 0:b.trim();P&&l.add(P)}const c=[];for(const j of t){const P=(j.sliceKind??"").trim().toLowerCase();if(P&&P!=="work_slice"||!Hm.has(j.status))continue;const Z=(j.runId??j.sliceRunId??"").trim();if(!Z)continue;const E=Ks(j.initiativeIds,j.initiativeId),D=Ks(j.workstreamIds,j.workstreamId),ee=E[0]??null,ve=D[0]??null;if(!ee||!ve)continue;const Ce=[];for(const G of E)for(const ae of D)!G||!ae||Ce.push(`${G}:${ae}`);if(!(l.has(Z)||Ce.some(G=>a.has(G))))continue;const Ae=r.get(Z)??(Ce.length>0?Ce.map(G=>a.get(G)??null).find(G=>!!G)??null:null),re=ee?i.get(ee)??ee:null,ne=j.scopeProgress&&typeof j.scopeProgress.totalTasks=="number"&&j.scopeProgress.totalTasks>0?Math.round(j.scopeProgress.completedTasks/j.scopeProgress.totalTasks*100):null;c.push({key:`slice:${j.sliceRunId}`,source:"slice",session:Ae??null,runId:Z,status:Bt(j.status),title:j.workstreamTitle??(Ae==null?void 0:Ae.title)??`Work slice ${j.sliceRunId.slice(0,8)}`,subtitle:j.statusExplainer??j.lastEventSummary??(Ae==null?void 0:Ae.lastEventSummary)??null,progress:ne??(Ae==null?void 0:Ae.progress)??null,initiativeId:ee,initiativeIds:E,initiativeTitle:re,workstreamId:ve,workstreamIds:D,iwmtId:j.iwmtId??null,iwmtIds:Ks(j.iwmtIds,j.iwmtId),workstreamTitle:j.workstreamTitle??(Ae==null?void 0:Ae.title)??null,taskIds:Array.isArray(j.taskIds)?j.taskIds:[],milestoneIds:Array.isArray(j.milestoneIds)?j.milestoneIds:[],artifactCount:j.artifactCount??0,decisionCount:j.blockingDecisionCount??j.decisionCount??0,updatedAt:j.updatedAt??j.lastEventAt??(Ae==null?void 0:Ae.updatedAt)??null,scope:j.scope,milestoneProgress:(A=j.scopeProgress)==null?void 0:A.milestones})}c.sort((j,P)=>oi(P.updatedAt)-oi(j.updatedAt));const d=[],u=new Set,p=new Set,g=new Set;for(const j of c){const P=j.initiativeId??((H=j.initiativeIds)==null?void 0:H[0])??"none",Z=j.workstreamId?`scope:${P}:${j.workstreamId}`:null,E=Z??(j.runId?`run:${j.runId}`:j.key);u.has(E)||(u.add(E),j.runId&&p.add(j.runId),Z&&g.add(Z),d.push(j))}const v=e.filter(j=>{if(!Vm(j))return!1;const P=(j.initiativeId??"").trim(),Z=(j.workstreamId??"").trim();if(P.length===0||Z.length===0)return!1;const E=(j.runId??"").trim();return E&&p.has(E)?!1:!g.has(`scope:${P}:${Z}`)});v.sort((j,P)=>{const Z=oi(j.updatedAt??j.lastEventAt??j.startedAt);return oi(P.updatedAt??P.lastEventAt??P.startedAt)-Z});const h=[],w=new Set;for(const j of v){const P=j.workstreamId&&j.workstreamId.trim().length>0?`${j.initiativeId??"none"}:${j.workstreamId}`:j.runId;w.has(P)||(w.add(P),h.push(j))}const y=h.map(j=>{var P;return{key:`session:${j.id}`,source:"session",session:j,runId:j.runId,status:Bt(j.status??""),title:j.title,subtitle:(P=j.lastEventSummary)!=null&&P.trim()?j.lastEventSummary.trim():null,progress:j.progress,initiativeId:j.initiativeId,initiativeIds:Ks(void 0,j.initiativeId),initiativeTitle:j.initiativeId?i.get(j.initiativeId)??j.groupLabel??null:j.groupLabel??null,workstreamId:j.workstreamId,workstreamIds:Ks(void 0,j.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:j.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:j.updatedAt??j.lastEventAt??j.startedAt??null}});return[...d,...y].sort((j,P)=>oi(P.updatedAt)-oi(j.updatedAt))}const tp=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:g,onPlayWorkstream:v,onPauseWorkstream:h,onResumeWorkstream:w,onRestartSession:y,onIntervene:I,onOpenSliceDetail:M}){const[F,b]=o.useState(null),[A,H]=o.useState(null),[j,P]=o.useState(null),[Z,E]=o.useState(null),D=o.useMemo(()=>{const G=new Map;if(!Array.isArray(s))return G;for(const ae of s){const De=Ks(ae.initiativeIds,ae.initiativeId),Te=Ks(ae.workstreamIds,ae.workstreamId);for(const we of De)for(const C of Te){if(!we||!C)continue;const O=`${we}:${C}`;G.has(O)||G.set(O,ae)}const de=(ae.runId??ae.sliceRunId??"").trim();de&&!G.has(`run:${de}`)&&G.set(`run:${de}`,ae)}return G},[s]),ee=o.useMemo(()=>gc({sessions:t,sliceRuns:s,initiatives:i}),[i,t,s]),ve=o.useMemo(()=>{const G=new Map;for(const ae of ee){const De=Bt(ae.status);G.set(De,(G.get(De)??0)+1)}return Array.from(G.entries()).sort((ae,De)=>De[1]-ae[1]).map(([ae,De])=>({status:ae,count:De}))},[ee]),Ce=o.useMemo(()=>F?ee.filter(G=>Bt(G.status)===F):ee,[F,ee]),pe=o.useMemo(()=>{var Te,de;const G=new Map,ae=[];for(const we of Ce){const C=(((Te=we.initiativeIds)==null?void 0:Te[0])??we.initiativeId??"").trim(),O=(((de=we.workstreamIds)==null?void 0:de[0])??we.workstreamId??"").trim();if(!C){ae.push(we);continue}let U=G.get(C);U||(U={title:we.initiativeTitle??C,wsMap:new Map},G.set(C,U));const K=O||"__none__";let ye=U.wsMap.get(K);ye||(ye={title:we.workstreamTitle??(O||"Unassigned"),rows:[],completedCount:0,lastActivity:null},U.wsMap.set(K,ye));const Oe=Bt(we.status);if(Oe==="completed"||Oe==="done"?ye.completedCount+=1:ye.rows.push(we),we.updatedAt){const me=Date.parse(we.updatedAt),ke=ye.lastActivity?Date.parse(ye.lastActivity):0;Number.isFinite(me)&&me>ke&&(ye.lastActivity=we.updatedAt)}}const De=[];for(const[we,C]of G){const O=[];for(const[U,K]of C.wsMap)O.push({workstreamId:U,workstreamTitle:K.title,rows:K.rows,completedCount:K.completedCount,lastActivityAt:K.lastActivity});O.sort((U,K)=>{const ye=U.lastActivityAt?Date.parse(U.lastActivityAt):0;return(K.lastActivityAt?Date.parse(K.lastActivityAt):0)-ye}),De.push({initiativeId:we,initiativeTitle:C.title,workstreams:O})}return De.sort((we,C)=>{const O=Math.max(0,...we.workstreams.map(K=>K.lastActivityAt?Date.parse(K.lastActivityAt):0));return Math.max(0,...C.workstreams.map(K=>K.lastActivityAt?Date.parse(K.lastActivityAt):0))-O}),{groups:De,ungrouped:ae}},[Ce]),[Ae,re]=o.useState(new Set),ne=async(G,ae,De)=>{if(G.session){E(null),H(G.session.id);try{await ae(G.session),E(De)}catch(Te){const de=Te instanceof Error?Te.message:"";E(de?en(de):"Workstream action failed")}finally{H(null)}}};return n.jsxs(Ss,{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:ee.length})]})}):null,ve.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:()=>b(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${F===null?"border-lime/30 bg-lime/12 text-lime":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:["All",n.jsx("span",{className:"tabular-nums opacity-70",children:ee.length})]}),ve.map(({status:G,count:ae})=>n.jsxs("button",{type:"button",onClick:()=>b(De=>De===G?null:G),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${F===G?"border-lime/30 bg-lime/12 text-lime":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[hc(G),n.jsx("span",{className:"tabular-nums opacity-70",children:ae})]},G))]}),Z&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:Z}),Ce.length===0?ee.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:ee.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(ce.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[pe.groups.map(G=>n.jsxs("div",{children:[n.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[n.jsx(an,{type:"initiative",size:13,className:"opacity-90"}),n.jsx("h3",{className:"text-[15px] font-semibold text-white/90",children:Wt(G.initiativeTitle&&!Hn(G.initiativeTitle)?G.initiativeTitle:za(G.initiativeId,"Initiative"))})]}),G.workstreams.map(ae=>{const De=`${G.initiativeId}:${ae.workstreamId}`,Te=Ae.has(De);return n.jsxs("div",{className:"pl-4 border-l border-white/[0.08] mb-3",children:[n.jsx("div",{className:"space-y-2",children:ae.rows.map((de,we)=>n.jsx(Yo,{row:de,index:we,sliceRunByScope:D,busySessionId:A,expandedRowKey:j,setExpandedRowKey:P,onOpenSession:p,onFocusRunId:g,onPauseWorkstream:h,onResumeWorkstream:w,onRestartSession:y,onPlayWorkstream:v,onIntervene:I,onOpenSliceDetail:M,runWorkstreamAction:ne,showInitiativeLabel:!1},de.key))}),ae.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>re(de=>{const we=new Set(de);return we.has(De)?we.delete(De):we.add(De),we}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:Te?`Hide ${ae.completedCount} completed`:`${ae.completedCount} completed`})})]},ae.workstreamId)})]},G.initiativeId)),pe.ungrouped.length>0&&n.jsxs("div",{children:[pe.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:pe.ungrouped.map((G,ae)=>n.jsx(Yo,{row:G,index:ae,sliceRunByScope:D,busySessionId:A,expandedRowKey:j,setExpandedRowKey:P,onOpenSession:p,onFocusRunId:g,onPauseWorkstream:h,onResumeWorkstream:w,onRestartSession:y,onPlayWorkstream:v,onIntervene:I,onOpenSliceDetail:M,runWorkstreamAction:ne,showInitiativeLabel:!0},G.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:g,onIntervene:v,onOpenSliceDetail:h,runWorkstreamAction:w,showInitiativeLabel:y=!0}){var De,Te,de,we,C,O,U,K,ye,Oe;const I=Bt(e.status??""),M=e.updatedAt,F=e.subtitle?e.subtitle:M?`Updated ${qt(M)}`:null,b=y&&(e.initiativeTitle||e.initiativeId)?Wt(e.initiativeTitle&&!Hn(e.initiativeTitle)?e.initiativeTitle:za(e.initiativeId,"Initiative")):null,A=(De=e.title)!=null&&De.trim()?e.title:"",H=Zm(A)&&((Te=e.workstreamTitle)!=null&&Te.trim())?e.workstreamTitle:A||e.workstreamTitle||"",j=za(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),P=Wt(H&&!Hn(H)?H:j),Z=F&&!ep(F)?Wt(F):null,E=Qm(e.progress),D=["running","active","in_progress","working","planning","dispatching"].includes(I),ee=["paused","blocked","queued","pending"].includes(I),ve=p??g,Ce=E===null&&["running","active","in_progress","working","planning","dispatching"].includes(I),pe=e.session?i===e.session.id:!1,Ae=r===e.key,re=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),ne=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),G=e.scope==="task"?"task":e.scope==="milestone"?"milestone":e.scope==="workstream"||e.source==="slice"?"workstream":"session",ae=Um((de=e.session)==null?void 0:de.agentId,(we=e.session)==null?void 0:we.agentName);return n.jsxs(ce.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,scale:.97,y:-6},layout:!0,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,ne),role:"button",tabIndex:0,onKeyDown:me=>{(me.key==="Enter"||me.key===" ")&&(me.preventDefault(),h==null||h(e,ne))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${Xm(I)}`,"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":ae.color}:void 0,children:n.jsx(Zt,{name:((C=e.session)==null?void 0:C.agentName)??"OrgX",hint:((O=e.session)==null?void 0:O.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[b?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:b}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(an,{type:G,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:P,children:P})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(Pn,{tone:e.scope==="milestone"?"cyan":"lime",children:e.scope}),n.jsx("span",{className:`inline-flex rounded-full border px-2 py-0.5 text-micro font-semibold uppercase tracking-[0.08em] ${Gm(I)}`,children:hc(I)}),M&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:id(new Date(M),{addSuffix:!0})})]}),Z?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:Z,children:Z}):null,null,(E!==null||Ce)&&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:E===null?"Live":`${E}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${E===100?" shimmer-on-complete":""}`,children:E===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,E)}%`,background:`linear-gradient(90deg, ${Vo(Ko((U=e.session)==null?void 0:U.agentId)).gradient[0]}, ${Vo(Ko((K=e.session)==null?void 0:K.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(fc,{nodes:Am({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((me,ke)=>me+ke.total,0),completedTasks:e.milestoneProgress.reduce((me,ke)=>me+ke.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((ye=e.session)==null?void 0:ye.agentName)??null,agentId:((Oe=e.session)==null?void 0:Oe.agentId)??null}),activeId:e.workstreamId,compact:!0})}),re?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:me=>{me.stopPropagation(),a(ke=>ke===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:Ae?"Hide details":"Slice details"}),Ae?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:me=>me.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&&D&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:pe,onClick:()=>void w(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&&ee&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:pe,onClick:()=>void w(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&&ve&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:pe,onClick:()=>void w(e,ve,`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&&v&&n.jsx("button",{type:"button",disabled:pe,onClick:()=>void w(e,v,`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 np={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 ea({icon:e="inbox",headline:t,description:s,primaryAction:i,secondaryAction:r,className:a}){return n.jsxs(ce.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(ce.div,{className:"flex h-12 w-12 items-center justify-center rounded-xl border border-white/[0.08] bg-white/[0.04]",variants:fr,custom:0,children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",className:"text-secondary",children:np[e]})}),n.jsx(ce.h4,{className:"mt-5 text-heading font-semibold text-white",variants:fr,custom:1,children:t}),n.jsx(ce.p,{className:"mt-2 text-body text-secondary leading-relaxed",variants:fr,custom:2,children:s}),(i||r)&&n.jsxs(ce.div,{className:"mt-5 flex items-center gap-2",variants:fr,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 sp=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 ip(e){return e.sliceRunId}function xc(e){const t=e.filter(i=>sp.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=ip(i),a=s.get(r);if(!a){s.set(r,{item:i,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function rp(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-lime/30 bg-lime/12 text-lime"}function ap(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function op(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-lime/0 via-lime/70 to-lime/0"}function lp(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 cp(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 Ua(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return Hn(s)?`${t} ${As(s)}`:s}function dp(e){if(!e)return null;const t=Wt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function up(e,t,s){const i=(t==null?void 0:t.trim())??"";if(i&&!Hn(i)){const a=Wt(i);if(a!=="Untitled session")return a}const r=dp(e.statusExplainer);return r||(s?Ua(s,"Workstream"):Ua(e.sliceRunId,"Slice"))}const mp=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 g=o.useMemo(()=>xc(t),[t]),v=o.useMemo(()=>{const y=new Map;for(const I of s)I.id&&y.set(I.id,I.name??I.id);return y},[s]),h=o.useMemo(()=>{const y=new Map;for(const I of s)for(const M of I.workstreams??[])M.id&&(y.has(M.id)||y.set(M.id,M.name??M.id));return y},[s]),w=y=>{var I;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 M=(I=y.artifacts.find(F=>F.url))==null?void 0:I.url;if(M&&typeof window<"u"){window.open(M,"_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(Ss,{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:g.length})]})}):null,g.length===0?n.jsx(ea,{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:n.jsx(Nt,{mode:"popLayout",children:g.map(({item:y,duplicateCount:I},M)=>{var Ce;const F=(Array.isArray(y.initiativeIds)&&y.initiativeIds.length>0?y.initiativeIds[0]:y.initiativeId)??null,b=(Array.isArray(y.workstreamIds)&&y.workstreamIds.length>0?y.workstreamIds[0]:y.workstreamId)??null,A=(F?v.get(F):null)??Ua(F,"Initiative"),H=y.workstreamTitle??(b?h.get(b)??null:null),j=up(y,H,b),P=(Ce=y.statusExplainer)!=null&&Ce.trim().length?y.statusExplainer:"Review this slice to continue execution.",Z=Wt(cp(y)),E=Wt(P),D=Wt(A),ee=y.scope?y.scope.replace(/_/g," "):null,ve=y.updatedAt??y.lastEventAt??null;return n.jsxs(ce.article,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,scale:.97,y:-6},transition:{duration:.24,delay:Math.min(M,7)*.022,ease:[.22,1,.36,1]},layout:!0,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:pe=>{(pe.key==="Enter"||pe.key===" ")&&(pe.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 ${op(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(an,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:D})]}),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:j,children:[n.jsx(an,{type:"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:j})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:Z,children:Z}),E!==Z&&n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:E,children:E})]}),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] ${rp(y.status)}`,children:ap(y.status)}),ee?n.jsx("span",{className:"chip text-micro capitalize",children:ee}):null]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[I>1&&n.jsxs("span",{className:"chip text-micro",children:[I," 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"]}),ve&&n.jsxs("span",{children:["Updated ",qt(ve)]})]}),y.decisionOptions&&y.decisionOptions.length>0&&y.decisionOptions.length<=3&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",onClick:pe=>pe.stopPropagation(),children:y.decisionOptions.slice(0,3).map(pe=>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:pe.description??pe.label,children:pe.label},pe.id))}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:pe=>pe.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:()=>w(y),className:"control-pill h-7 px-2.5 text-micro font-semibold","data-tone":y.status==="failed"?"teal":void 0,children:lp(y)})]})]},y.sliceRunId)})})})]})});function pp(e){if(!e)return"Unknown";const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toLocaleString():"Unknown"}function Zo(e){return e?qt(e):"unknown"}const fp={run_completed:"text-lime",milestone_completed:"text-teal-200",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 hp(e){var s;const t=(s=e.title)==null?void 0:s.trim();return t||e.type.replace(/_/g," ")}const gp=o.memo(function({className:t,rows:s,onFocusRunId:i,onOpenNextUp:r}){return s.length===0?n.jsx(Ss,{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,l)=>n.jsxs(ce.section,{initial:{opacity:0,y:10,scale:.985},animate:{opacity:1,y:0,scale:1},transition:{duration:.26,delay:Math.min(l,6)*.035,ease:[.22,1,.36,1]},className:"rounded-2xl border border-subtle bg-white/[0.02] px-3 py-2.5",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:Wt(a.title)}),n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Completed ",Zo(a.completedAt)," · ",pp(a.completedAt)]}),a.statusExplainer?n.jsx("p",{className:"mt-0.5 truncate text-micro text-muted",children:Wt(a.statusExplainer)}):null]}),n.jsx(Pn,{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.5",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:Wt([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.5",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(c=>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:Wt(c.title)}),n.jsxs("p",{className:"text-micro text-secondary",children:[c.type??"artifact"," · ",Zo(c.createdAt)]})]}),c.url?n.jsx("a",{href:c.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}:${c.id??c.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.5",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((c,d)=>{const u=fp[c.type]??"text-primary";return n.jsxs(ce.li,{initial:{opacity:0,x:-4},animate:{opacity:1,x:0},transition:{duration:.2,delay:Math.min(d,8)*.025,ease:[.22,1,.36,1]},className:"flex items-start justify-between gap-2 text-caption",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:`truncate ${u}`,children:Wt(hp(c))}),c.description?n.jsx("p",{className:"truncate text-micro text-secondary",children:Wt(c.description)}):null]}),n.jsx("span",{className:"whitespace-nowrap text-micro text-muted",children:qt(c.timestamp)})]},`${a.key}:event:${c.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-lime/28 bg-lime/12 px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/18",children:"Connect back to Next Up"}):null]})]},a.key))})});function xp(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function yp(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 bp(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function vp(e){return{id:e.id,name:e.title,status:xp(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:yp(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,wp=12;function tl(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function kp(){const e=new Date,t=864e5;return[{id:"init-1",name:"Content Engine: Dogfood the Larry Playbook",status:"active",rawStatus:"active",priority:"critical",health:56,daysRemaining:9,targetDate:new Date(e.getTime()+9*t).toISOString(),createdAt:new Date(e.getTime()-24*t).toISOString(),updatedAt:new Date(e.getTime()-4*6e4).toISOString(),activeAgents:3,totalAgents:4,description:"Drafting long-form content, clearing legal review, and preparing distribution schedule."},{id:"init-2",name:"Live View UX Redesign — The Conductor's Display",status:"active",rawStatus:"active",priority:"high",health:44,daysRemaining:6,targetDate:new Date(e.getTime()+6*t).toISOString(),createdAt:new Date(e.getTime()-17*t).toISOString(),updatedAt:new Date(e.getTime()-3*6e4).toISOString(),activeAgents:3,totalAgents:4,description:"Improving activity readability, developer-mode gating, and collapse-state spacing quality."},{id:"init-3",name:"Directory Submissions & External References",status:"active",rawStatus:"active",priority:"medium",health:49,daysRemaining:12,targetDate:new Date(e.getTime()+12*t).toISOString(),createdAt:new Date(e.getTime()-19*t).toISOString(),updatedAt:new Date(e.getTime()-1*6e4).toISOString(),activeAgents:4,totalAgents:5,description:"Parallel directory import, reference QA, and partner outreach with active artifact production."},{id:"init-4",name:"Revenue Expansion Q2",status:"completed",rawStatus:"completed",priority:"low",health:100,daysRemaining:0,targetDate:new Date(e.getTime()-1*t).toISOString(),createdAt:new Date(e.getTime()-45*t).toISOString(),updatedAt:new Date(e.getTime()-42*6e4).toISOString(),activeAgents:0,totalAgents:2,description:"Completed closeout package with reconciled variance sheet and executive sign-off trail."},{id:"init-5",name:"Incident Replay & Reliability",status:"blocked",rawStatus:"blocked",priority:"critical",health:24,daysRemaining:3,targetDate:new Date(e.getTime()+3*t).toISOString(),createdAt:new Date(e.getTime()-13*t).toISOString(),updatedAt:new Date(e.getTime()-25*6e4).toISOString(),activeAgents:1,totalAgents:2,description:"Replay pipeline is blocked on archive restore approval and backup snapshot decision."}]}function yc(e,t=null){return Zs({queryKey:cs.entities({type:"initiative",projectId:t}),queryFn:async()=>{var c;if(Kn())return kp();const s=[],i=(t==null?void 0:t.trim())??"";let r=0;for(let d=0;d<wp;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(el),offset:String(r)});i&&Ts(u,i);const p=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:Ut({workspaceId:i})});if(!p.ok)break;const g=await p.json(),v=g.data??[];if(s.push(...v),!!!((c=g.pagination)!=null&&c.has_more)||v.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=>bp(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(vp)},enabled:e,staleTime:6e4})}const gr=50,nl=8;function Ip(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Np(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function jp(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Ap(e){const t=jp(e.sequence);return{id:e.id,name:e.title,status:Ip(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 _p(e,t=null){return Zs({queryKey:cs.liveInitiatives({limit:gr*nl,projectId:t}),queryFn:async()=>{var l;if(Kn())return[];const s=[];let i=0;for(let c=0;c<nl;c+=1){const d=new URLSearchParams({limit:String(gr),offset:String(i)});t&&t.trim().length>0&&Ts(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:Ut({workspaceId:t})});if(!u.ok)break;const p=await u.json(),g=p.initiatives??[];s.push(...g);const v=typeof p.total=="number"?p.total:null,h=(l=p.pagination)==null?void 0:l.has_more;if(!(typeof h=="boolean"?h:v!==null?i+g.length<v:g.length===gr)||g.length===0)break;i+=gr}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=>Np(c.status)).map(Ap)},enabled:e,staleTime:3e4})}const bc=o.createContext(null);function Sp({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(bc.Provider,{value:{state:t,open:i,close:r},children:e})}function vc(){const e=o.useContext(bc);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Cp(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:L.lime,clickable:!0,onClick:c}:{text:"Nothing running."}]};if(t===0&&d===0)return{key:"idle-done",segments:[{text:`${r} done today`,color:L.teal},{text:" · all caught up"}]};if(s>0&&i>0){const u=`${s} blocked`;return{key:`blocked-decisions-${s}-${i}-${t}`,segments:[...t>0?[{text:`${t} running · `}]:[],{text:u,color:L.textMuted,clickable:!0,onClick:l},{text:" · "},{text:`${i} decisions`,color:L.amber,clickable:!0,onClick:a}]}}if(s>0){const u=`${s} blocked`;return{key:`blocked-${s}-${t}`,segments:[{text:u,color:L.textMuted,clickable:!0,onClick:l},...t>0?[{text:` · ${t} running`}]:[]]}}return i>0?{key:`decisions-${i}-${t}`,segments:[...t>0?[{text:`${t} running`,color:L.lime},{text:" · "}]:[],{text:`${i} decisions`,color:L.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:L.lime},{text:" · all systems go"}]}}function sl(e){const{className:t}=e,{key:s,segments:i}=Cp(e);return n.jsx("div",{className:`flex items-center gap-1.5 whitespace-nowrap text-body ${t??""}`,children:n.jsx(Nt,{mode:"wait",children:n.jsx(ce.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 Ax={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"},Tp={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"},_x=e=>Tp[Bt(e)]??"text-white/60 bg-white/5 border-white/10",Sx=e=>{const t=Bt(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"},Cx=e=>{const t=Bt(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"},Tx=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Mx=e=>{const t=Bt(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},Vs=e=>{const t=Bt(e);return t==="blocked"||t==="failed"||t==="cancelled"?L.red:t==="active"||t==="in_progress"||t==="running"?L.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?L.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?L.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},Hr={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:L.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:L.teal,tint:"rgba(20, 184, 166, 0.18)"}},Mp=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Pr(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)Pr(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"?(Mp.some(c=>l.includes(c))||l.startsWith("meta")||l.endsWith("id"))&&Pr(a,t,s+1,i):typeof a=="object"&&a!==null&&Pr(a,t,s+1,i)}}}}function Ep(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 _s(...e){const t=[],s=new Set;for(const i of e)Pr(i,t,0,s);for(const i of t){const r=Ep(i);if(r)return Hr[r]}return Hr.unknown}function Rp(e){return Hr[e]??Hr.unknown}const Lp=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","canceled","stopped","deleted"]),Dp=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),Pp=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff","review"]),$p=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping","stalled","awaiting_input","needs_review","needs_decision","review_required"]);function Ex(e){return Lp.has(Bt(e))}function Op(e){return Dp.has(Bt(e))}function eo(e){return Pp.has(Bt(e))}function qp(e){return $p.has(Bt(e))}const Bp={xs:18,sm:24,md:30};function Fp({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:Jr,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 pi({provider:e,size:t="sm",className:s,showRing:i=!0}){const r=Rp(e),a=Bp[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(Fp,{provider:e})})})}function wc({running:e,blocked:t,paused:s,size:i=36,children:r}){const a=xs(),l=e+t+s,c=o.useMemo(()=>{if(l===0)return[];const h=[];return e>0&&h.push({color:L.lime,fraction:e/l}),t>0&&h.push({color:L.red,fraction:t/l}),s>0&&h.push({color:L.amber,fraction:s/l}),h},[e,t,s,l]),d=2.5,u=(i-d)/2,p=2*Math.PI*u,g=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:g,cy:g,r:u,fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:d})}),n.jsx("div",{className:"relative z-10",children:r})]});let v=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:g,cy:g,r:u,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),c.map((h,w)=>{const y=h.fraction*p,I=-v;return v+=y,n.jsx(ce.circle,{cx:g,cy:g,r:u,fill:"none",stroke:h.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${y} ${p-y}`,strokeDashoffset:I,initial:a?!1:{strokeDasharray:`0 ${p}`},animate:{strokeDasharray:`${y} ${p-y}`},transition:{duration:.5,delay:w*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},w)})]}),n.jsx("div",{className:"relative z-10",children:r})]})}const xr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function to(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function no(e,t){if(typeof t=="number")return`${e}${t+1}`}const zp=(e,t)=>{const s=to(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:no("W",s)}},Up=(e,t)=>{const s=to(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:no("M",s)}},Wp=(e,t)=>{const s=to(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:no("T",s)}};function ka(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 Hp(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 Kp({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:i=!0}){var c;const r=nu(e),a=o.useMemo(()=>cs.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),l=Zs({queryKey:a,enabled:i&&!!e&&r,queryFn:async()=>{if(!e)return xr;if(Kn())return Hp(e);if(!r)return{...xr,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 M=>{try{const F=new URLSearchParams({type:M,initiative_id:e,limit:"100"}),b=await fetch(`/orgx/api/entities?${F.toString()}`,{headers:u});return b.ok?await b.json():{data:[]}}catch{return{data:[]}}},[g,v,h]=await Promise.all([p("workstream"),p("milestone"),p("task")]),w=Array.isArray(g.data)?ka(g.data.map(M=>zp(M,e))):[],y=Array.isArray(v.data)?ka(v.data.map(M=>Up(M,e))):[],I=Array.isArray(h.data)?ka(h.data.map(M=>Wp(M,e))):[];return{initiativeId:e,workstreams:w,milestones:y,tasks:I}}});return{details:(r?l.data:null)??(e?{...xr,initiativeId:e}:xr),isLoading:r?l.isLoading:!1,error:r?((c=l.error)==null?void 0:c.message)??null:null,refetch:l.refetch}}function Vp(){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 so({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return Zs({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Kn())return Vp();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 Ti(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:L.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:L.iris,bg:"rgba(124,124,255,0.10)"}}function Gp(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function Xp(e,t){return[...t?e.tasks.filter(i=>i.workstreamId===t):e.tasks].sort((i,r)=>i.title.localeCompare(r.title))}function Qp({open:e,onClose:t,onLaunched:s}){var U,K,ye,Oe,me,ke;const i=so({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:r}=yc(e),[a,l]=o.useState(""),[c,d]=o.useState(""),[u,p]=o.useState(""),[g,v]=o.useState(""),[h,w]=o.useState("auto"),[y,I]=o.useState(""),[M,F]=o.useState(null),[b,A]=o.useState(null),[H,j]=o.useState("starter"),[P,Z]=o.useState(!1),[E,D]=o.useState(1),ee=Kn(),ve=o.useMemo(()=>{const T=c.trim();return T?(r==null?void 0:r.find(be=>be.id===T))??null:null},[r,c]),{details:Ce}=Kp({initiativeId:ve?ve.id:null,enabled:e&&!!ve}),pe=o.useMemo(()=>Gp(Ce),[Ce]),Ae=o.useMemo(()=>Xp(Ce,u||null),[Ce,u]),re=((U=i.data)==null?void 0:U.agents)??[],ne=o.useMemo(()=>{const T=a.trim();return T?re.find(be=>be.id===T)??null:null},[re,a]);o.useEffect(()=>{var be,Y;if(!e)return;const T=((be=re.find(Ee=>Ee.isDefault))==null?void 0:be.id)??((Y=re[0])==null?void 0:Y.id)??"";!a&&T&&l(T)},[re,e,a]),o.useEffect(()=>{if(!e||c.trim())return;const T=r??[],be=T.length===1?T[0]:null;be&&d(be.id)},[r,e,c]),o.useEffect(()=>{if(!e)return;const T=(ne==null?void 0:ne.model)??"",be=T.includes("openrouter")?"openrouter":T.includes("anthropic")?"anthropic":T.includes("openai")?"openai":"auto";w(be)},[e,ne==null?void 0:ne.model,a]),o.useEffect(()=>{e&&(F(null),A(null),j("starter"),D(1))},[e]),o.useEffect(()=>{p(""),v("")},[c]),o.useEffect(()=>{v("")},[u]),o.useEffect(()=>{e&&(y.trim().length>0||ve&&I(`Kick off: ${ve.name}`))},[y,e,ve]);const G=!!a.trim()&&!!c.trim(),ae=E===1?!!a.trim():E===2?!!c.trim():G,De=async()=>{var Be;const T=(b==null?void 0:b.checkout)??"/orgx/api/billing/checkout",be=H&&H.trim().length>0?H.trim():"starter",Ee=await(await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:be,billingCycle:"monthly"})})).json().catch(()=>null),ze=((Be=Ee==null?void 0:Ee.data)==null?void 0:Be.url)??(Ee==null?void 0:Ee.url)??null;if(!ze)throw new Error((Ee==null?void 0:Ee.error)??"Checkout unavailable");window.open(ze,"_blank","noopener,noreferrer")},Te=async()=>{var ze;const T=(b==null?void 0:b.portal)??"/orgx/api/billing/portal",Y=await(await fetch(T,{method:"POST"})).json().catch(()=>null),Ee=((ze=Y==null?void 0:Y.data)==null?void 0:ze.url)??(Y==null?void 0:Y.url)??null;if(!Ee)throw new Error((Y==null?void 0:Y.error)??"Billing portal unavailable");window.open(Ee,"_blank","noopener,noreferrer")},de=async()=>{if(!(!G||P)){if(ee){t(),s==null||s();return}F(null),A(null),Z(!0);try{const T={agentId:a.trim(),message:y.trim()?y.trim():void 0,initiativeId:c.trim(),initiativeTitle:(ve==null?void 0:ve.name)??null,workstreamId:u.trim()?u.trim():null,taskId:g.trim()?g.trim():null,provider:h!=="auto"?h:null},be=new URLSearchParams;be.set("agentId",T.agentId),be.set("initiativeId",T.initiativeId),T.initiativeTitle&&be.set("initiativeTitle",T.initiativeTitle),T.workstreamId&&be.set("workstreamId",T.workstreamId),T.taskId&&be.set("taskId",T.taskId),T.message&&be.set("message",T.message),T.provider&&be.set("provider",T.provider);const Y=await fetch(`/orgx/api/agents/launch?${be.toString()}`,{method:"POST"}),Ee=await Y.json().catch(()=>null);if(!Y.ok||!(Ee!=null&&Ee.ok))throw(Ee==null?void 0:Ee.code)==="upgrade_required"&&(A(Ee.actions??null),j(Ee.requiredPlan??"starter")),new Error((Ee==null?void 0:Ee.error)??`Launch failed (${Y.status})`);t(),s==null||s()}catch(T){F(T instanceof Error?T.message:"Launch failed")}finally{Z(!1)}}},we=!!((K=ne==null?void 0:ne.run)!=null&&K.runId)&&!!((ye=ne==null?void 0:ne.run)!=null&&ye.pid),C=async()=>{var T;if(!(!((T=ne==null?void 0:ne.run)!=null&&T.runId)||!we||P)&&!ee){F(null),Z(!0);try{const be=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(ne.run.runId)}`,{method:"POST"}),Y=await be.json().catch(()=>null);if(!be.ok||!(Y!=null&&Y.ok))throw new Error((Y==null?void 0:Y.error)??`Stop failed (${be.status})`);await i.refetch()}catch(be){F(be instanceof Error?be.message:"Stop failed")}finally{Z(!1)}}},O=async()=>{var T;if(!(!((T=ne==null?void 0:ne.run)!=null&&T.runId)||P)){if(ee){t(),s==null||s();return}F(null),Z(!0);try{const be=new URLSearchParams;be.set("runId",ne.run.runId),y.trim()&&be.set("message",y.trim()),h&&h!=="auto"&&be.set("provider",h);const Y=await fetch(`/orgx/api/agents/restart?${be.toString()}`,{method:"POST"}),Ee=await Y.json().catch(()=>null);if(!Y.ok||!(Ee!=null&&Ee.ok))throw new Error((Ee==null?void 0:Ee.error)??`Restart failed (${Y.status})`);t(),s==null||s()}catch(be){F(be instanceof Error?be.message:"Restart failed")}finally{Z(!1)}}};return e?n.jsx(Zr,{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(([T,be])=>n.jsxs("button",{type:"button",onClick:()=>D(T),className:ue("rounded-full px-3 py-1 transition-colors",E===T?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[T,". ",be]},T))})]}),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(Nt,{mode:"wait",children:n.jsxs(ce.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:[E===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:T=>l(T.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-lime/30",children:re.map(T=>{const be=Ti(T.status);return n.jsxs("option",{value:T.id,children:[T.name," (",T.id,") · ",be.label]},T.id)})})]}),ne&&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:ne.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${Ti(ne.status).color}55`,color:Ti(ne.status).color,backgroundColor:Ti(ne.status).bg},children:Ti(ne.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:"})," ",ne.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",ne.workspace??"unknown"]}),((Oe=ne.context)==null?void 0:Oe.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",ne.context.initiativeTitle??ne.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:T=>w(T.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-lime/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."})]}),ne.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",ne.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",ne.run.status,")"]})]}),ne.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:C,disabled:!we||P,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:O,disabled:P,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"})]})]})]})]}),E===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:T=>d(T.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-lime/30",children:[n.jsx("option",{value:"",children:"Select an initiative…"}),(r??[]).map(T=>n.jsx("option",{value:T.id,children:T.name},T.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:T=>p(T.target.value),disabled:!ve,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-lime/30",!ve&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),pe.map(T=>n.jsx("option",{value:T.id,children:T.name},T.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task (optional)"}),n.jsxs("select",{value:g,onChange:T=>v(T.target.value),disabled:!ve,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-lime/30",!ve&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),Ae.slice(0,80).map(T=>n.jsx("option",{value:T.id,children:T.title},T.id))]}),Ae.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),E===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:T=>I(T.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-lime/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:((ne==null?void 0:ne.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:((ve==null?void 0:ve.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()?((me=pe.find(T=>T.id===u))==null?void 0:me.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:g.trim()?((ke=Ae.find(T=>T.id===g))==null?void 0:ke.title)??g:"Any"})]})]})]})]})]},E)}),M&&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:M}),b&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void De().catch(T=>F(T instanceof Error?T.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 Te().catch(T=>F(T instanceof Error?T.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"}),b.pricing&&n.jsx("a",{href:b.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:E===1?"Pick an agent to configure.":E===2?"Select an initiative scope (required).":G?"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:[E>1&&n.jsx("button",{type:"button",onClick:()=>D(T=>T>1?T-1:T),disabled:P,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"}),E<3?n.jsx("button",{type:"button",onClick:()=>D(T=>T<3?T+1:T),disabled:!ae||P,className:ue("rounded-xl px-4 py-2 text-body font-semibold transition-colors",ae&&!P?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:ae&&!P?{backgroundColor:L.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:de,disabled:!G||P,className:ue("rounded-xl px-4 py-2 text-body font-semibold transition-colors",G&&!P?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:G&&!P?{backgroundColor:L.lime}:void 0,children:P?"Launching…":"Launch"})]})]})]})}):null}function Yp({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(an,{type:t.icon,size:11,className:"opacity-90"}),t.label]})]}),n.jsx(ce.button,{type:"button",onClick:s,"aria-label":"Close detail",whileHover:{scale:1.06},whileTap:{scale:.92},transition:{duration:.12},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 Ia=10,Jp=20;function Zp(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:L.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:L.iris,bg:"rgba(124,124,255,0.10)"}}function ef(e){return e?e.includes("error")||e.includes("fail")?L.red:e.includes("decision")||e.includes("block")?L.amber:e.includes("complete")||e.includes("success")?L.teal:e.includes("start")||e.includes("launch")?L.lime:L.iris:L.iris}const tf={hidden:{opacity:0,y:-4},visible:e=>({opacity:1,y:0,transition:{duration:.28,delay:e*.04,ease:[.16,1,.3,1]}})},yr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{duration:.22,delay:e*.04,ease:[.22,1,.36,1]}})};function nf(){return n.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"})}function sf({open:e,onClose:t,agentName:s,catalogAgent:i,sessions:r,activity:a,onSelectSession:l,onRefresh:c}){var D,ee,ve,Ce,pe,Ae;const[d,u]=o.useState(!1),[p,g]=o.useState(!1),[v,h]=o.useState(null),w=Hi(s),y=Zp((i==null?void 0:i.status)??null),I=Za(s),M=o.useMemo(()=>{let re=0,ne=0,G=0,ae=0;for(const De of r)De.status==="running"||De.status==="queued"||De.status==="pending"?re++:De.status==="blocked"?ne++:De.status==="failed"||De.status==="cancelled"?G++:(De.status==="completed"||De.status==="archived")&&ae++;return{running:re,blocked:ne,failed:G,completed:ae}},[r]),F=o.useMemo(()=>[...r].sort((re,ne)=>Date.parse(ne.updatedAt??ne.lastEventAt??ne.startedAt??"")-Date.parse(re.updatedAt??re.lastEventAt??re.startedAt??"")),[r]),b=d?F:F.slice(0,Ia),A=F.length>Ia,H=o.useMemo(()=>[...a].sort((re,ne)=>Date.parse(ne.timestamp)-Date.parse(re.timestamp)).slice(0,Jp),[a]),j=!!((D=i==null?void 0:i.run)!=null&&D.runId)&&!!((ee=i==null?void 0:i.run)!=null&&ee.pid),P=async()=>{var re;if(!(!((re=i==null?void 0:i.run)!=null&&re.runId)||!j||p)){h(null),g(!0);try{const ne=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(i.run.runId)}`,{method:"POST"}),G=await ne.json().catch(()=>null);if(!ne.ok||!(G!=null&&G.ok))throw new Error((G==null?void 0:G.error)??`Stop failed (${ne.status})`);c==null||c()}catch(ne){h(ne instanceof Error?ne.message:"Stop failed")}finally{g(!1)}}},Z=async()=>{var re;if(!(!((re=i==null?void 0:i.run)!=null&&re.runId)||p)){h(null),g(!0);try{const ne=new URLSearchParams;ne.set("runId",i.run.runId);const G=await fetch(`/orgx/api/agents/restart?${ne.toString()}`,{method:"POST"}),ae=await G.json().catch(()=>null);if(!G.ok||!(ae!=null&&ae.ok))throw new Error((ae==null?void 0:ae.error)??`Restart failed (${G.status})`);c==null||c()}catch(ne){h(ne instanceof Error?ne.message:"Restart failed")}finally{g(!1)}}};if(!e)return null;const E=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:P,disabled:!j||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:Z,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(Zr,{open:e,onClose:t,maxWidth:"max-w-3xl",children:[n.jsx("div",{className:"h-[2px] rounded-t-xl",style:{background:`linear-gradient(90deg, ${I}, transparent)`}}),n.jsx(Yp,{breadcrumbs:[{label:"Agents"},{label:s}],onClose:t,footer:E,children:n.jsxs("div",{className:"px-8 py-6 space-y-8",children:[n.jsxs(ce.div,{className:"flex items-start gap-5",variants:tf,initial:"hidden",animate:"visible",custom:0,children:[n.jsx(wc,{running:M.running,blocked:M.blocked+M.failed,paused:0,size:72,children:n.jsx(Zt,{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-display 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})]}),w&&n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted mt-2",children:w})]})]}),n.jsx(ce.div,{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",variants:yr,initial:"hidden",animate:"visible",custom:1,children:[{label:"Running",value:M.running,color:L.lime},{label:"Blocked",value:M.blocked,color:L.red},{label:"Failed",value:M.failed,color:L.amber},{label:"Completed",value:M.completed,color:L.teal}].map(re=>n.jsxs("div",{children:[n.jsx("p",{className:"section-kicker",children:re.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:re.value>0?re.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:re.value})]},re.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs(ce.div,{variants:yr,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:[b.map(re=>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:Vs(re.status)}}),n.jsxs("button",{onClick:()=>{l(re.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:re.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:qt(re.updatedAt??re.lastEventAt??re.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:re.status}),re.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(re.progress),"%"]})]})]})]})]},re.id)),A&&n.jsx("button",{type:"button",onClick:()=>u(re=>!re),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${F.length-Ia} older sessions`})]})]}),n.jsxs(ce.div,{variants:yr,initial:"hidden",animate:"visible",custom:3,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Live Activity"}),H.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:H.map((re,ne)=>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:ef(re.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:re.title??re.summary??re.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:qt(re.timestamp)})]})]},re.id??ne))})]})]}),n.jsx(nf,{}),i&&n.jsxs(ce.div,{variants:yr,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:(ve=i.model)!=null&&ve.includes("openrouter")?"OpenRouter":(Ce=i.model)!=null&&Ce.includes("anthropic")?"Anthropic":(pe=i.model)!=null&&pe.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})]}),((Ae=i.context)==null?void 0:Ae.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})]})]})]}),v&&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:v})]})})]})}const br=120,il=10,rf=24,rl=520,af=58,of=56,lf=20,cf=8,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,Wa=[{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 kt(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function Mn(e,t){const s=kt(e),i=kt(t);if(!s&&!i)return null;const r=[s,i].filter(Boolean).join(" ");if(!r)return null;for(const a of Wa)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=Mn(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=Mn(null,i);if(r)return r}return null}function ff(e){const t=kt(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 kc(e){const t=pf(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=kt(e.agentId),i=kt(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=kc(e),s=kt(t.agentId);if(s)return`id:${s}`;const i=kt(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 Kr(e){const t=(e??"").trim();return t?gi(t):!1}function xf(e){var t,s;return!!(Kr((t=e.context)==null?void 0:t.initiativeId)||Kr(((s=e.run)==null?void 0:s.initiativeId)??null))}function vr(e){if(Mn(e.agentId,e.agentName))return!0;const s=kt(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function Tn(e){const t=Bt(e.status??"")||"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=Bt(e.phase??"");if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const i=Bt(e.state??"");return i==="error"?"failed":i==="stopped"?"paused":i==="stale"?"queued":eo(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function Ha(e){const t=Bt(e??"");return!!t&&(eo(t)||qp(t)||Op(t))}function al(e){const t=Bt(e??"");return!!t&&eo(t)}function li(e){return e?!!(Ha(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 Un(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function wr(e,t){return Un(t.updatedAt??t.lastEventAt??t.startedAt)-Un(e.updatedAt??e.lastEventAt??e.startedAt)}function vf({status:e,nodes:t,onSelectSession:s,selectedSessionId:i}){const[r,a]=o.useState(!1),l=Vs(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(ce.span,{animate:{rotate:r?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(Nt,{children:r&&n.jsx(ce.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,g=_s(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(ce.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(pi,{provider:g.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:qt(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:g=[],showSyntheticEntities:v=!1,autopilotState:h=null}){var Q;const[w,y]=o.useState(new Set),[I,M]=o.useState(!1),[F,b]=o.useState(!1),[A,H]=o.useState(0),[j,P]=o.useState(null),[Z,E]=o.useState(!1),D=so({enabled:!0}),ee=((Q=D.data)==null?void 0:Q.agents)??[],ve=o.useMemo(()=>Vi(a),[a]),Ce=o.useMemo(()=>ve===null?s:s.filter(q=>Un(q.timestamp)>=ve),[s,ve]);o.useMemo(()=>{var le,$e,Ve;const q=new Map,te=[...Ce].sort((Ye,fe)=>Un(fe.timestamp)-Un(Ye.timestamp));for(const Ye of te){const fe=Ye.runId;if(!fe||q.has(fe))continue;const Qe=((le=Ye.summary)==null?void 0:le.trim())??(($e=Ye.description)==null?void 0:$e.trim())??((Ve=Ye.title)==null?void 0:Ve.trim())??"";Qe.length>0&&q.set(fe,Qe)}return q},[Ce]);const{agents:pe,hiddenGroupCount:Ae,filteredOutGroupsByDate:re,filteredOutSessionsByDate:ne,visibleSessionCount:G,archivedGroups:ae,sessionCountInScope:De}=o.useMemo(()=>{var jt;const q=v?t.nodes:t.nodes.filter(X=>!Kr(X.initiativeId)),te=v?ee:ee.filter(X=>!xf(X)),le=v?g:g.filter(X=>!Kr(X.initiativeId)),$e=new Map,Ve=new Map,Ye=[...le].sort((X,he)=>Un(he.lastEventAt??he.lastHeartbeatAt)-Un(X.lastEventAt??X.lastHeartbeatAt));for(const X of Ye){X.runId&&!$e.has(X.runId)&&$e.set(X.runId,X);const he=Mn(X.agentId,X.agentName??X.displayName),qe=kt((he==null?void 0:he.agentId)??X.agentId);if(qe){const nt=Ve.get(qe)??[];nt.push(X),Ve.set(qe,nt)}}const fe=new Map;for(const X of q){const he=kc(X),qe=hf(X),nt=kt(he.agentId),Ke=kt(he.agentName);let Xe=fe.get(qe)??null;if(!Xe&&nt&&Ke){const He=`name:${Ke}`,xt=fe.get(He);xt&&(fe.delete(He),xt.groupKey=qe,fe.set(qe,xt),Xe=xt)}if(!Xe&&Ke){const He=Array.from(fe.values()).find(xt=>kt(xt.agentName)===Ke);He&&(Xe=He)}Xe?(Xe.nodes.push(X),!Xe.agentId&&he.agentId&&(Xe.agentId=he.agentId),(Xe.agentName==="OrgX"||!Xe.agentName)&&he.agentName&&(Xe.agentName=he.agentName)):fe.set(qe,{groupKey:qe,agentId:he.agentId,agentName:he.agentName??he.agentId??"OrgX",nodes:[X],latest:X,runtime:null,runtimeActiveCount:0})}for(const X of te){const he=Mn(X.id,X.name),qe=(he==null?void 0:he.agentId)??X.id,nt=(he==null?void 0:he.agentName)??X.name,Ke=kt(qe),Xe=kt(nt),He=Ke?`id:${Ke}`:null,xt=Xe?`name:${Xe}`:null;let Qt=null;if(He&&fe.has(He))Qt=He;else if(xt&&fe.has(xt))Qt=xt;else{const wt=Array.from(fe.entries()).find(([,At])=>Ke&&kt(At.agentId)===Ke||Xe&&kt(At.agentName)===Xe);Qt=(wt==null?void 0:wt[0])??null}if(Qt){const wt=fe.get(Qt);wt.catalogAgent=X,!wt.agentId&&qe&&(wt.agentId=qe),(wt.agentName==="OrgX"||!wt.agentName)&&nt&&(wt.agentName=nt),He&&wt.groupKey!==He&&!fe.has(He)&&(fe.delete(wt.groupKey),wt.groupKey=He,fe.set(He,wt))}else{const wt=He??xt??`catalog:${nt.toLowerCase()}`;fe.set(wt,{groupKey:wt,agentId:qe,agentName:nt,nodes:[],latest:null,catalogAgent:X,runtime:null,runtimeActiveCount:0})}}for(const X of Wa){const he=`orgx:${X.id}`,qe=`id:${he}`;let nt=fe.get(qe)??null;if(!nt){const Ke=Array.from(fe.entries()).find(([,Xe])=>{const He=Mn(Xe.agentId,Xe.agentName);return kt(He==null?void 0:He.agentId)===kt(he)});Ke&&(fe.delete(Ke[0]),nt=Ke[1],nt.groupKey=qe,fe.set(qe,nt))}if(nt||(nt={groupKey:qe,agentId:he,agentName:X.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},fe.set(qe,nt)),nt.agentId=he,nt.agentName=X.name,!nt.catalogAgent){const Ke=te.find(Xe=>{const He=Mn(Xe.id,Xe.name);return kt(He==null?void 0:He.agentId)===kt(he)});Ke&&(nt.catalogAgent=Ke)}}const Qe=new Map(Wa.map((X,he)=>[kt(`orgx:${X.id}`),he]));for(const X of fe.values()){X.nodes.length>0&&(X.nodes.sort(wr),X.latest=X.nodes[0]);const he=[],qe=new Set;if((jt=X.latest)!=null&&jt.runId){const Ke=$e.get(X.latest.runId);Ke&&!qe.has(Ke.id)&&(he.push(Ke),qe.add(Ke.id))}for(const Ke of X.nodes){if(!Ke.runId)continue;const Xe=$e.get(Ke.runId);Xe&&!qe.has(Xe.id)&&(he.push(Xe),qe.add(Xe.id))}const nt=kt(X.agentId);if(nt)for(const Ke of Ve.get(nt)??[])qe.has(Ke.id)||(he.push(Ke),qe.add(Ke.id));he.sort((Ke,Xe)=>Un(Xe.lastEventAt??Xe.lastHeartbeatAt)-Un(Ke.lastEventAt??Ke.lastHeartbeatAt)),X.runtime=he[0]??null,X.runtimeActiveCount=he.filter(Ke=>yf(Ke)).length}const ie=Array.from(fe.values()).sort((X,he)=>{const qe=vr(X),nt=vr(he);if(qe!==nt)return qe?-1:1;if(qe&&nt){const Ke=X.nodes.length>0||(X.runtimeActiveCount??0)>0,Xe=he.nodes.length>0||(he.runtimeActiveCount??0)>0;if(Ke!==Xe)return Ke?-1:1;if(Ke&&Xe){if(X.latest&&he.latest)return wr(X.latest,he.latest);if(X.latest&&!he.latest)return-1;if(!X.latest&&he.latest)return 1}const He=Mn(X.agentId,X.agentName),xt=Mn(he.agentId,he.agentName),Qt=Qe.get(kt((He==null?void 0:He.agentId)??X.agentId))??999,wt=Qe.get(kt((xt==null?void 0:xt.agentId)??he.agentId))??999;if(Qt!==wt)return Qt-wt}return X.latest&&he.latest?wr(X.latest,he.latest):X.latest&&!he.latest?-1:!X.latest&&he.latest?1:X.agentName.localeCompare(he.agentName)}),V=Zl(a),Re=V.id==="live",et=V.minutes===null||Re?null:Date.now()-V.minutes*6e4,ct=[],gt=[];let mt=0,vt=0;for(const X of ie){const he=(X.runtimeActiveCount??0)>0,qe=vr(X);if(X.nodes.length===0){const He=li(X.catalogAgent);(qe||Re&&(He||he))&&ct.push(X);continue}if(Re){const He=X.nodes.filter(wt=>Ha(Tn(wt))),xt=X.nodes.filter(wt=>!Ha(Tn(wt))),Qt=li(X.catalogAgent);if(He.length===0){qe||Qt||he?ct.push({...X,nodes:[],latest:null}):(mt+=1,vt+=X.nodes.length,gt.push(X));continue}vt+=xt.length,xt.length>0&&gt.push({...X,nodes:xt,latest:xt[0]??null}),ct.push({...X,nodes:He,latest:He[0]??null});continue}if(et===null){ct.push(X);continue}const nt=X.nodes.filter(He=>al(Tn(He))?!0:Un(He.updatedAt??He.lastEventAt??He.startedAt)>=et),Ke=li(X.catalogAgent);if(nt.length===0){qe||Ke||he?ct.push({...X,nodes:[],latest:null}):(mt+=1,vt+=X.nodes.length,gt.push(X));continue}const Xe=X.nodes.filter(He=>al(Tn(He))?!1:Un(He.updatedAt??He.lastEventAt??He.startedAt)<et);vt+=Xe.length,Xe.length>0&&gt.push({...X,nodes:Xe,latest:Xe[0]}),ct.push({...X,nodes:nt,latest:nt[0]})}return{agents:ct.slice(0,br),hiddenGroupCount:Math.max(0,ct.length-br),filteredOutGroupsByDate:mt,filteredOutSessionsByDate:vt,visibleSessionCount:ct.slice(0,br).reduce((X,he)=>X+he.nodes.length,0),archivedGroups:gt,sessionCountInScope:q.length}},[a,t.nodes,ee,g,v]);o.useEffect(()=>{b(!1),H(0)},[a]);const Te=o.useMemo(()=>ae.reduce((q,te)=>q+te.nodes.length,0),[ae]),de=o.useMemo(()=>pe.filter(q=>q.nodes.length>0).map(q=>q.groupKey),[pe]),{activeAgents:we,idleOrgxAgents:C,activeAgentCount:O}=o.useMemo(()=>{const q=[],te=[];for(const le of pe)le.nodes.length>0||(le.runtimeActiveCount??0)>0||li(le.catalogAgent)?q.push(le):vr(le)?te.push(le):q.push(le);return{activeAgents:q,idleOrgxAgents:te,activeAgentCount:q.filter(le=>le.nodes.length>0||(le.runtimeActiveCount??0)>0||li(le.catalogAgent)).length}},[pe]),U=o.useMemo(()=>{if(de.length===0)return{allCollapsed:!1,allExpanded:!0};let q=0;for(const te of de)w.has(te)&&(q+=1);return{allCollapsed:q===de.length,allExpanded:q===0}},[w,de]),K=o.useMemo(()=>{const q=[];for(const te of ae)for(const le of te.nodes)q.push({node:le,agentName:te.agentName});return q.sort((te,le)=>wr(te.node,le.node)),q.slice(0,(A+1)*df)},[ae,A]),ye=q=>{y(te=>{const le=new Set(te);return le.has(q)?le.delete(q):le.add(q),le})},Oe=()=>{y(()=>U.allCollapsed?new Set:new Set(de))},me=o.useMemo(()=>j?pe.find(q=>q.groupKey===j)??null:null,[pe,j]),ke=o.useMemo(()=>(me==null?void 0:me.nodes)??[],[me]),T=o.useMemo(()=>{if(!me)return[];const q=kt(me.agentName),te=kt(me.agentId),le=Mn(me.agentId,me.agentName);return Ce.filter($e=>{const Ve=kt($e.agentName),Ye=kt($e.agentId),fe=Mn($e.agentId,$e.agentName);return q!==null&&Ve===q||te!==null&&Ye===te||le!==null&&fe!==null&&kt(le.agentId)===kt(fe.agentId)})},[Ce,me]),be=De===0,Y=ee.length>0,Ee=o.useRef(null),[ze,Be]=o.useState(0),[ft,Me]=o.useState(0),Se=o.useCallback(q=>{const te=q.currentTarget.scrollTop;Be(le=>Math.abs(le-te)<1?le:te)},[]);o.useEffect(()=>{const q=Ee.current;if(!q)return;const te=()=>{const le=q.clientHeight,$e=q.scrollTop;Me(Ve=>Ve===le?Ve:le),Be(Ve=>Math.abs(Ve-$e)<1?Ve:$e)};if(te(),typeof ResizeObserver<"u"){const le=new ResizeObserver(()=>te());return le.observe(q),()=>le.disconnect()}return window.addEventListener("resize",te),()=>window.removeEventListener("resize",te)},[we.length]);const{visibleAgentGroups:J,topVirtualSpacerPx:ht,bottomVirtualSpacerPx:It,virtualizationEnabled:We}=o.useMemo(()=>{if(!(we.length>rf&&ft>0))return{visibleAgentGroups:we,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const te=we.map(ie=>{const Re=w.has(ie.groupKey)?0:Math.min(ie.nodes.length,il);let et=af;return Re>0&&(et+=lf+Re*of,ie.nodes.length>Re&&(et+=20)),et+cf}),le=new Array(te.length+1).fill(0);for(let ie=0;ie<te.length;ie+=1)le[ie+1]=le[ie]+te[ie];const $e=le[le.length-1],Ve=Math.max(0,ze-rl),Ye=ze+ft+rl;let fe=0;for(;fe<we.length&&le[fe+1]<Ve;)fe+=1;let Qe=fe;for(;Qe<we.length&&le[Qe]<Ye;)Qe+=1;return Qe<=fe&&(Qe=Math.min(we.length,fe+1)),{visibleAgentGroups:we.slice(fe,Qe),topVirtualSpacerPx:le[fe],bottomVirtualSpacerPx:Math.max(0,$e-le[Qe]),virtualizationEnabled:!0}},[we,w,ze,ft]);return n.jsxs(Ss,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(Qp,{open:I,onClose:()=>M(!1),onLaunched:()=>{D.refetch(),u==null||u()}}),n.jsx(sf,{open:j!==null,onClose:()=>P(null),agentName:(me==null?void 0:me.agentName)??"",catalogAgent:(me==null?void 0:me.catalogAgent)??null,sessions:ke,activity:T,onSelectSession:r,onRefresh:()=>D.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:[O," active"]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:Oe,disabled:de.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:U.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:U.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>M(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:Ee,onScroll:Se,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[pe.length===0&&!be&&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."})]}),pe.length===0&&be&&!d&&n.jsx(ea,{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:[We&&ht>0&&n.jsx("div",{"aria-hidden":"true",style:{height:ht}}),J.map(q=>{var wt;const te=q.groupKey,le=w.has(te),$e=q.latest,Ve=$e?Tn($e):null,Ye=(h==null?void 0:h.activeRunId)!=null&&($e==null?void 0:$e.runId)!=null&&h.activeRunId===$e.runId,fe=Ye&&(h==null?void 0:h.state)==="running"?"running":Ve,Qe=Ye&&(h==null?void 0:h.state)==="running"&&h.activeWorkstreamTitle?`Working on ${h.activeWorkstreamTitle}`:null,ie=q.nodes.length>0,V=q.nodes.length===1,Re=li(q.catalogAgent),et=q.runtime??null,ct=(q.runtimeActiveCount??0)>0,gt=!ie&&ct&&et!==null,mt=ie||gt,vt=$e?i===$e.id:!1,jt=q.agentName||((wt=q.catalogAgent)==null?void 0:wt.name)||q.agentId||"OrgX",X=Mn(q.agentId,jt),he=(X==null?void 0:X.agentName)??gf(jt),qe=(X==null?void 0:X.role)??Hi(he),nt=_s(q.agentId,he,et==null?void 0:et.displayName,$e==null?void 0:$e.runtimeProvider,$e==null?void 0:$e.runtimeClient),Ke=X===null&&(nt.id==="codex"||nt.id==="openai"||nt.id==="anthropic"||nt.id==="openclaw"),Xe=qe?`${jt} — ${qe}`:jt,He=le?[]:ie?q.nodes.slice(0,il):[],xt=Math.max(0,ie?q.nodes.length-He.length:0),Qt=kt(c)===kt(he)||kt(c)===kt(Xe);return n.jsxs(ce.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",vt&&"border-white/20 bg-white/[0.05]",Qt&&"border-[#0AD4C4]/30",!ie&&!Re&&!ct&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{V?r(q.nodes[0].id):gt?ye(te):!ie&&Re?P(te):l?l(Qt?null:he):$e&&r($e.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:[Ke?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(pi,{provider:nt.id,size:"sm",showRing:!1})}):n.jsx(wc,{running:q.nodes.filter(At=>{const Pt=Tn(At);return Pt==="running"||Pt==="handoff"||Pt==="review"}).length,blocked:q.nodes.filter(At=>{const Pt=Tn(At);return Pt==="blocked"||Pt==="failed"}).length,paused:q.nodes.filter(At=>{const Pt=Tn(At);return Pt==="paused"||Pt==="cancelled"}).length,size:36,children:n.jsx(Zt,{name:he,size:"sm",hint:`${q.agentId??""} ${he}`})}),X&&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"})}),$e&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Vs(fe??$e.status),borderColor:L.cardBg}}),!$e&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Re?Vs("running"):"rgba(255,255,255,0.2)",borderColor:L.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:qe?`${jt} — ${qe}`:jt,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[he,qe&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",qe]})]})}),Qe&&n.jsx("p",{className:"truncate text-micro text-teal-400",title:Qe,children:Qe}),n.jsx("div",{className:"flex items-center gap-1.5",children:ie?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const At={};for(const Pt of q.nodes){const Kt=Tn(Pt);At[Kt]=(At[Kt]??0)+1}return Object.entries(At).map(([Pt,Kt])=>`${Kt} ${Pt}`).join(" · ")})(),children:(()=>{const At={};for(const Kt of q.nodes){const at=Tn(Kt);At[at]=(At[at]??0)+1}const Pt=q.nodes.length;return Object.entries(At).map(([Kt,at])=>n.jsx("span",{style:{width:`${at/Pt*100}%`,backgroundColor:Vs(Kt)}},Kt))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:q.nodes.length})]}):Re||ct?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:Vs("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:()=>P(te),"aria-label":`View ${he} 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:()=>{mt&&ye(te)},disabled:!mt,"aria-label":mt?le?"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",mt?"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",mt&&!le?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(Nt,{initial:!1,children:mt&&!le&&n.jsx(ce.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 At=new Map,Pt=[];for(const st of He){const Ft=Tn(st);if(Ft==="blocked"||Ft==="paused"||Ft==="failed"){const Rt=`${Ft}:${st.blockerReason??""}`,$t=At.get(Rt)??[];$t.push(st),At.set(Rt,$t)}else Pt.push(st)}const Kt=[];for(const[st,Ft]of At)Ft.length>3?Kt.push({status:st.split(":")[0],nodes:Ft}):Pt.push(...Ft);const at=(st,Ft)=>{const Rt=i===st.id,$t=Tn(st),Dt=_s(st.agentName,st.title,st.lastEventSummary,st);return n.jsx(ce.button,{onClick:()=>r(st.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(Ft*.015,.12)},className:ue("w-full rounded-lg px-2.5 py-2 text-left transition-colors",Rt?"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(pi,{provider:Dt.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:st.title,children:st.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:Dt.accent},children:Dt.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:$t}),n.jsx("span",{title:Br(st.updatedAt??st.lastEventAt??st.startedAt??Date.now()),children:qt(st.updatedAt??st.lastEventAt??st.startedAt??Date.now())})]}),st.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(st.progress)}%`,background:`linear-gradient(90deg, ${L.lime}, ${L.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:Vs($t)},"aria-label":$t,title:$t})]})},st.id)};return n.jsxs(n.Fragment,{children:[Pt.map((st,Ft)=>at(st,Ft)),Kt.map(st=>n.jsx(vf,{status:st.status,nodes:st.nodes,onSelectSession:r,selectedSessionId:i},`cg-${st.status}-${st.nodes.length}`))]})})(),xt>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",xt," older sessions hidden"]})]})})})]},te)}),We&&It>0&&n.jsx("div",{"aria-hidden":"true",style:{height:It}})]}),C.length>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02]",children:[n.jsxs("button",{onClick:()=>E(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",Z?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[C.length," idle agent",C.length===1?"":"s"]})]}),n.jsx(Nt,{initial:!1,children:Z&&n.jsx(ce.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:C.map(q=>{const te=Mn(q.agentId,q.agentName),le=(te==null?void 0:te.agentName)??q.agentName,$e=(te==null?void 0:te.role)??Hi(le);return n.jsxs("button",{type:"button",onClick:()=>P(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(Zt,{name:le,size:"sm",hint:`${q.agentId??""} ${le}`}),te&&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:[le,$e&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",$e]})]})}),n.jsx("span",{className:"text-micro text-muted",children:"Idle"})]},q.groupKey)})})})})]}),Ae>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",br," most recent agent groups (",Ae," 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))})]}),ne>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{b(q=>!q),F&&H(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",F?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[Te," archived session",Te===1?"":"s",re>0?` across ${re} agent${re===1?"":"s"}`:""]})]}),n.jsx(Nt,{initial:!1,children:F&&n.jsx(ce.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:[K.map(({node:q,agentName:te})=>{const le=Tn(q),$e=q.runtimeProvider?{id:bf(q.runtimeProvider)}:_s(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(pi,{provider:$e.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:te}),n.jsx("span",{className:"text-micro text-muted",title:Br(q.updatedAt??q.lastEventAt??q.startedAt??Date.now()),children:qt(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:le})]})]},q.id)}),K.length<Te&&n.jsxs("button",{onClick:()=>H(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 (",Te-K.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?Bt(e):""}function Na(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 fs(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(A=>A.length>0),u=Na(e.blockingDecisionCount),p=Na(e.nonBlockingDecisionCount),g=Na(e.blockerCount),v=c==="run_failed",h=c==="run_completed"||c==="milestone_completed"||c==="decision_resolved",w=v||_f(d),y=Sf(d)||c==="decision_requested"||u>0||e.decisionRequired===!0,I=Cf(d)||g>0,M=h||Tf(d),F=Mf(d)||c==="run_started";if(w)return fs("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(M&&!y&&!w&&g===0&&!e.blockerReason)return p>0?fs("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):fs("completed","Execution completed successfully.",{tone:"positive"});if(y||I)return u>0||e.decisionRequired===!0||c==="decision_requested"?fs("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):fs("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:I?"critical":"warning"});if(M)return p>0?fs("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):fs("completed","Execution completed successfully.",{tone:"positive"});if(F){const A=p>0?`Running with ${p} optional decision${p===1?"":"s"} available.`:"Running.";return fs("in_progress",A,{tone:"neutral"})}return fs("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const ja=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Rf(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Gs(e,t){const s=[];let i=0,r=0;ja.lastIndex=0;for(let a=ja.exec(e);a;a=ja.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],g=a[3],v=a[4],h=a[5],w=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)):g?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:g},d)):v||h?s.push(n.jsx("strong",{className:"font-semibold text-white",children:v??h},d)):w||y?s.push(n.jsx("em",{className:"italic text-bright",children:w??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(...Gs(r,`${t}-line-${a}`)),a<s.length-1&&i.push(n.jsx("br",{},`${t}-br-${a}`))}),i}function $r(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Df(e){const t=$r(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function Pf(e){const t=e.trim(),s=t.startsWith(":"),i=t.endsWith(":");return s&&i?"center":i?"right":"left"}function $f(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 v=$r(r),w=$r(c).map(I=>Pf(I));i+=2;const y=[];for(;i<t.length;){const I=t[i]??"";if(!I.trim()||!I.includes("|"))break;y.push($r(I)),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:v.map((I,M)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:w[M]??"left"},children:Gs(I,`tbl-h-${i}-${M}`)},`tbl-h-${M}`))})}),n.jsx("tbody",{children:y.map((I,M)=>n.jsx("tr",{className:M<y.length-1?"border-b border-subtle":void 0,children:v.map((F,b)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:w[b]??"left"},children:Gs(I[b]??"",`tbl-r-${i}-${M}-${b}`)},`tbl-r-${M}-c-${b}`))},`tbl-r-${M}`))})]})},`tbl-${i}`));continue}if(a.startsWith("```")){const v=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:[v&&n.jsx("p",{className:"mb-1 text-micro uppercase tracking-[0.12em] text-muted",children:v}),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 v=d[1].length,h=d[2],w=v===1?"text-title font-semibold":v===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:ue("tracking-[-0.01em] text-white",w),children:Gs(h,`h-${i}`)},`h-${i}`)),i+=1;continue}if(r.match(/^\s*[-*]\s+(.+)$/)){const v=[];for(;i<t.length;){const w=(t[i]??"").match(/^\s*[-*]\s+(.+)$/);if(!w)break;v.push(w[1]),i+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:v.map((h,w)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:Gs(h,`ul-${i}-${w}`)},`ul-${i}-${w}`))},`ul-${i}`));continue}if(r.match(/^\s*\d+\.\s+(.+)$/)){const v=[];for(;i<t.length;){const w=(t[i]??"").match(/^\s*\d+\.\s+(.+)$/);if(!w)break;v.push(w[1]),i+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:v.map((h,w)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:Gs(h,`ol-${i}-${w}`)},`ol-${i}-${w}`))},`ol-${i}`));continue}const g=[];for(;i<t.length;){const v=t[i]??"",h=v.trim();if(!h||/^(#{1,3})\s+/.test(h)||/^\s*[-*]\s+/.test(v)||/^\s*\d+\.\s+/.test(v)||h.startsWith("```"))break;g.push(v),i+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Lf(g.join(`
208
+ `),`p-${i}`)},`p-${i}`))}return s}function qi({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:Gs(i,"inline")}):n.jsx("div",{className:ue("space-y-2",s),children:$f(i)}):null}function Ic(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Of(e){if(!e)return;const t=Ic(e.metadata);return t?{...e,...t}:e}const Nc={run_started:{icon:"play",label:"Run started",color:L.teal},run_completed:{icon:"check_circle",label:"Run completed",color:L.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:L.red},artifact_created:{icon:"file",label:"Artifact",color:L.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:L.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:L.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:L.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:L.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:L.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:L.red},milestone_completed:{icon:"flag",label:"Milestone",color:L.cyan},delegation:{icon:"workflow",label:"Delegation",color:L.iris}};function ls(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 Ka(e){return e?e.toLowerCase():""}function qf(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,ls(t,["source","event","eventType","artifact_type","action","kind"]),ls(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function Bf(e,t){const s=Ka(ls(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:L.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:L.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:L.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:L.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:L.cyan}:Nc.artifact_created}function Ff(e){const t=Of(Ic(e.metadata)),s=qf(e,t),i=Ka(ls(t,["source"])),r=Ka(ls(t,["action"])),a=ls(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"&&ls(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:L.teal};if(a==="auto_continue_stopped"){const c=ls(t,["stop_reason"]);return c==="error"||c==="blocked"?{icon:"infinity",label:"Needs attention",color:L.red}:c==="budget_exhausted"?{icon:"infinity",label:"Paused",color:L.amber}:{icon:"infinity",label:"Paused",color:L.amber}}if(a==="autopilot_transition"){const c=ls(t,["new_state"]);return c==="blocked"||c==="error"?{icon:"infinity",label:"Needs attention",color:L.red}:{icon:"infinity",label:"In progress",color:L.teal}}const l=ls(t,["parsed_status","status"]);return l==="completed"||l==="success"?{icon:"check_circle",label:"Completed",color:L.lime}:l==="blocked"||l==="needs_decision"?{icon:"infinity",label:"Needs attention",color:L.amber}:{icon:"infinity",label:"In progress",color:L.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:L.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:L.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:L.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:L.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:L.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:L.iris};if(i==="local_openclaw")return{icon:"terminal",label:"Local",color:L.teal};if(e.type==="artifact_created")return Bf(t,s);if(e.type==="decision_resolved")return r==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:L.red}:{icon:"shield_check",label:"Decision approved",color:L.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Started",color:L.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:L.teal}}return Nc[e.type]??{icon:"message",label:"Activity",color:L.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(cc,{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 Vr(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Va(e){if(!e)return;const t=Vr(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=Va(Vr(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,w)=>Date.parse(h.timestamp)-Date.parse(w.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]),g=o.useMemo(()=>{let h=null,w=null,y=null,I=null,M=null;for(const b of d){const A=Va(Vr(b.metadata));if(A&&(!h&&typeof A.domain=="string"&&(h=A.domain),!w&&typeof A.provider=="string"&&(w=A.provider),!y&&typeof A.model=="string"&&(y=A.model),!I&&typeof A.spawn_guard_model_tier=="string"&&(I=A.spawn_guard_model_tier),!M&&typeof A.kickoff_context_hash=="string"&&(M=A.kickoff_context_hash),h&&(w||y)&&I&&M))break}return!(h||w||y||I||M)?null:{domain:h,provider:w,model:y,modelTier:I,kickoffContextHash:M}},[d]),v=(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:L.lime,boxShadow:`0 0 12px ${L.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:rt(v)})]}),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(Zt,{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}),(g==null?void 0:g.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:rt(g.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"?`${L.lime}20`:s.status==="failed"?`${L.red}20`:`${L.teal}20`,color:s.status==="running"?L.lime:s.status==="failed"?L.red:L.teal},children:s.status}),g&&(g.provider||g.model||g.modelTier||g.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&&g&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(g.provider||g.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[g.provider?`${rt(g.provider)} · `:"",g.model?zi(g.model):"—"]}),g.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",rt(g.modelTier)]}),g.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 ",g.kickoffContextHash.slice(0,8),"…"]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:[n.jsx(Nt,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${L.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((h,w)=>{var P;const y=Ff(h),I=y.color,M=(P=Va(Vr(h.metadata)))==null?void 0:P.model,F=typeof M=="string"?zi(M):null,b=rt(h.title??""),A=h.type==="run_failed",H=h.type==="artifact_created",j=h.type==="decision_requested"||h.type==="decision_resolved";return n.jsxs(ce.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:w*.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-lime/35 focus-visible:ring-offset-1 focus-visible:ring-offset-background",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:`${I}20`,color:I,border:`1px solid ${I}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 ${A?"text-red-400":j?"text-amber-300":H?"text-cyan-300":"text-bright"}`,children:b}),h.summary&&h.summary!==b&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:rt(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:Br(h.timestamp),children:Uf(h.timestamp)}),F&&n.jsx("span",{className:"text-micro text-faint",children:F})]})]},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:Br(d[d.length-1].timestamp),children:qt(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(Nt,{children:i&&n.jsx(ce.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:`${L.teal}08`,border:`1px solid ${L.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}},Pi={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")?Pi.pr:t.includes("doc")||t.includes("spec")?Pi.doc:t.includes("test")?Pi.test:Pi.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:g,isRecent:v,enableMotion:h,onOpen:w,ariaLabel:y,artifactSnippet:I,evidenceChips:M,actorCategory:F,queuePosition:b}){const A=(M==null?void 0:M.slice(0,2))??[],H=((M==null?void 0:M.length)??0)-A.length,j="group w-full rounded-2xl border border-white/[0.08] bg-white/[0.02] px-3 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-lime/45 cv-auto",P=F==="system",Z=n.jsxs("div",{className:ue("flex items-start gap-3",P&&"opacity-55"),children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(Zt,{name:F==="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",v&&!P&&"pulse-soft"),style:{backgroundColor:l,boxShadow:P?"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",P?"text-muted italic":"text-secondary"),title:i,children:P?`OrgX · ${i}`:i}),n.jsx("p",{className:ue("mt-0.5 line-clamp-1 break-words text-body font-semibold leading-snug",P?"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:g}),n.jsx("span",{className:"text-micro text-muted",children:p})]})]}),I?n.jsxs("div",{className:"mt-2 flex items-center gap-2 rounded-lg border px-2.5 py-1.5",style:{borderColor:`${ol(I.typeBadge)}33`,backgroundColor:`${ol(I.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:[I.typeBadge&&n.jsxs("span",{className:"mr-1.5 text-micro font-semibold uppercase tracking-wider opacity-70",children:["[",I.typeBadge,"]"]}),n.jsx("span",{className:"font-semibold text-bright",children:I.title??I.label}),I.preview&&!I.title&&n.jsx("span",{className:"ml-1.5 opacity-60",children:I.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(qi,{mode:"inline",text:r})}):null,A.length>0&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[A.map(E=>{const D=Pi[E.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:D,backgroundColor:`${D}14`,border:`1px solid ${D}30`},children:[E.kind==="pr"&&"PR",E.kind==="commit"&&"Commit",E.kind==="test"&&"Tests",E.kind==="doc"&&"Doc",E.kind==="artifact"&&"Artifact",n.jsx("span",{className:"font-normal normal-case tracking-normal",style:{color:`${D}CC`},children:E.label})]},`${E.kind}-${E.label}`)}),H>0&&n.jsxs("span",{className:"text-[10px] text-muted",children:["+",H," 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})}),b&&(()=>{const E=Gf[b.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:`${E}55`,backgroundColor:`${E}1A`,color:E},children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:E}}),b.state==="running"?"Active":`#${b.rank}`]})})()]})]})]});return h?n.jsx(ce.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:w,className:j,"aria-label":y,children:Z},e):n.jsx("button",{type:"button",onClick:w,className:ue(j,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":y,children:Z},e)}function Qf({open:e,onClose:t,children:s}){return n.jsx(Zr,{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 p,g,v;const s=o.useMemo(()=>gd(e),[e]),i=Yf(e),r=Jf[i],a=typeof((p=e.metadata)==null?void 0:p.agent_name)=="string"?e.metadata.agent_name:typeof((g=e.metadata)==null?void 0:g.agentName)=="string"?e.metadata.agentName:e.agentName??"OrgX",l=((v=e.type)==null?void 0:v.replace(/_/g," "))??"activity",d=s.taskDescription||s.outcomeDescription||s.nextStep?null:`${a} recorded a ${l}`,u=[s.taskDescription||d?{label:"Task",value:s.taskDescription??d}:null,s.outcomeDescription?{label:"Outcome",value:s.outcomeDescription}:null,s.nextStep?{label:"Next step",value:s.nextStep}:null].filter(Boolean);return n.jsx(ce.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.3,ease:[.22,1,.36,1]},className:`rounded-lg border ${r.border} ${r.bg} p-6 space-y-5 ${t??""}`,children:u.map((h,w)=>n.jsx(ce.div,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},transition:{duration:.25,delay:.08+w*.06,ease:[.22,1,.36,1]},children:n.jsx(eh,{label:h.label,value:h.value,styles:r})},h.label))})}function eh({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"]),th=[{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"}],Mi=[{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 fn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function nh(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 Ei(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?Wt(en(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function sh(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function ih(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 Gr(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function fi(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 jc(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function rh(e){return e==="agent"?"assistant":e}function ah(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function oh(e,t){return t.map(s=>({id:s.id,role:rh(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function Ac(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function hi(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Or(e){const t=hi(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const i=hi(t.latestMessage),r=hi(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 lh(e){const t=hi(e);if(!t)return null;const s=Or({...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=>hi(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=>hi(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)=>fn(a.createdAt)-fn(l.createdAt)),launches:r.sort((a,l)=>fn(l.requestedAt)-fn(a.requestedAt))}}function ch(e,t,s){const i=fn(e.lastActivityAt);if(!i)return!1;if(t==="custom"){const a=fn(s.startIso),l=fn(s.endIso);return!(a&&i<a||l&&i>l)}const r=Vi(t,Date.now());return r?i>=r:!0}async function Ri(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 Aa(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)=>fn(r.lastActivityAt??r.updatedAt)-fn(i.lastActivityAt??i.updatedAt))}function dh(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)=>fn(r.lastActivityAt??r.updatedAt)-fn(i.lastActivityAt??i.updatedAt))}const _c=o.createContext(null),Sc=o.createContext(null);function io(){const e=o.useContext(_c);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function ro(){const e=o.useContext(Sc);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function uh({children:e,sessions:t,initiatives:s,workspaceId:i,query:r,statusFilter:a,sortOrder:l,timeFilterId:c,customTimeRange:d,snapshot:u,onRequestRefresh:p}){const[g,v]=o.useState((u==null?void 0:u.threads)??[]),[h,w]=o.useState(null),[y,I]=o.useState(null),[M,F]=o.useState(!1),[b,A]=o.useState(null),[H,j]=o.useState("resting"),[P,Z]=o.useState(""),[E,D]=o.useState(!1),[ee,ve]=o.useState(!1),[Ce,pe]=o.useState(null),[Ae,re]=o.useState(null),[ne,G]=o.useState([]),[ae,De]=o.useState(""),[Te,de]=o.useState([]),[we,C]=o.useState(""),[O,U]=o.useState(null),[K,ye]=o.useState(""),[Oe,me]=o.useState(!1),[ke,T]=o.useState(""),[be,Y]=o.useState([]),[Ee,ze]=o.useState(!1),[Be,ft]=o.useState("auto"),[Me,Se]=o.useState(!1),[J,ht]=o.useState(!1),[It,We]=o.useState(!1),Q=o.useRef(null),q=o.useRef(null),te=o.useRef(null),le=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&v(z=>dh(z,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{h&&v(z=>z.sort((ge,xe)=>fn(xe.lastActivityAt)-fn(ge.lastActivityAt)))},[h]);const{data:$e}=so({enabled:!0,refetchInterval:8e3}),Ve=o.useMemo(()=>{var ge,xe;const z=new Map;for(const Fe of th)z.set(Fe.id,{id:Fe.id,name:Fe.name,handle:Fe.handle,domain:Fe.domain,domainLabel:Fe.domainLabel,role:Fe.role,status:"idle",currentTask:null,isSystem:!1});if($e!=null&&$e.agents)for(const Fe of $e.agents){const _t=z.get(Fe.id);_t?(_t.status=Fe.status==="running"?"running":(ge=Fe.blockers)!=null&&ge.length?"blocked":"idle",_t.currentTask=Fe.currentTask??null):z.set(Fe.id,{id:Fe.id,name:Fe.name,handle:Fe.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:Fe.status==="running"?"running":(xe=Fe.blockers)!=null&&xe.length?"blocked":"idle",currentTask:Fe.currentTask??null,isSystem:ll.has(Fe.id)})}for(const Fe of t){const _t=(Fe.agentId??"").trim(),Ct=(Fe.agentName??"").trim();!_t||!Ct||z.has(_t)||z.set(_t,{id:_t,name:Ct,handle:_t,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:ll.has(_t)})}return Array.from(z.values()).filter(Fe=>!Fe.isSystem).sort((Fe,_t)=>Fe.name.localeCompare(_t.name))},[$e,t]),Ye=o.useMemo(()=>s.map(z=>({id:z.id,name:z.name})).sort((z,ge)=>z.name.localeCompare(ge.name)),[s]),fe=o.useMemo(()=>Ve.find(z=>z.id===ae)??null,[Ve,ae]),Qe=o.useMemo(()=>{const z=new Set(Te);return Ve.filter(ge=>z.has(ge.id))},[Ve,Te]),ie=o.useMemo(()=>Ye.find(z=>z.id===we)??null,[Ye,we]);o.useEffect(()=>{ae&&de(z=>z.filter(ge=>ge!==ae))},[ae]);const V=o.useMemo(()=>Ve.slice(0,8),[Ve]),Re=o.useMemo(()=>{const z=K.trim().toLowerCase();return z?Ve.filter(ge=>ge.name.toLowerCase().includes(z)||ge.handle.toLowerCase().includes(z)||ge.domain.toLowerCase().includes(z)||ge.role.toLowerCase().includes(z)):Ve},[Ve,K]),et=o.useMemo(()=>{const z=ke.trim().toLowerCase();return z?Ye.filter(ge=>ge.name.toLowerCase().includes(z)):Ye},[Ye,ke]),ct=o.useMemo(()=>{const z=r.trim().toLowerCase(),ge=g.filter(xe=>!ih(xe,a)||!ch(xe,c,d)?!1:z.length===0?!0:sh(xe).includes(z));return ge.sort((xe,Fe)=>{const _t=fn(Fe.lastActivityAt)-fn(xe.lastActivityAt);return l==="newest"?_t:-_t}),ge},[d,r,l,a,g,c]),gt=o.useMemo(()=>{if(!h||ct.some(ge=>ge.id===h))return ct;const z=g.find(ge=>ge.id===h);return z?[z,...ct]:ct},[h,ct,g]),mt=o.useMemo(()=>g.find(z=>z.id===h)??null,[h,g]),vt=o.useMemo(()=>ne.filter(z=>z.status!=="ready").length,[ne]),X=P.trim().length>0&&!E,he=o.useMemo(()=>vt>0?`${vt} attachment(s) still processing.`:"Press Enter to send.",[vt]),qe=o.useMemo(()=>E?"Sending…":ee?"Launching…":"Send",[ee,E]),nt=o.useMemo(()=>new rd({api:"/orgx/api/chat/usechat"}),[]),{messages:Ke,setMessages:Xe,sendMessage:He,status:xt,error:Qt,clearError:wt}=ad({id:`orgx-chat-guidance-${i??"global"}`,transport:nt,onError:z=>{pe(Ei((z==null?void 0:z.message)??null,"send"))}});o.useEffect(()=>{if(!y){Xe([]);return}Xe(oh(y.id,y.messages))},[y,Xe]);const At=o.useMemo(()=>{const z=[...Ke].reverse().find(xe=>xe.role==="assistant");if(!z)return null;const ge=ah(z);return ge.length>0?ge:null},[Ke]),Pt=o.useRef(null);o.useEffect(()=>{if(xt!=="ready"&&xt!=="error"||!At)return;const z=[...Ke].reverse().find(ge=>ge.role==="assistant");!z||z.id===Pt.current||(Pt.current=z.id,Y(ge=>[...ge,{id:`guidance_${z.id}`,role:"agent",body:At,timestamp:new Date().toISOString()}]))},[xt,At,Ke]);const Kt=o.useCallback(()=>{Z(""),G([]),ht(!1),We(!1),pe(null),re(null)},[]),at=o.useCallback(z=>{Y(ge=>[...ge,{...z,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),st=o.useCallback(()=>Y([]),[]),Ft=o.useCallback(()=>ze(z=>!z),[]),Rt=o.useMemo(()=>Mi.find(z=>z.id===Be)??Mi[0],[Be]),$t=o.useCallback(()=>{ft(z=>{const ge=Mi.findIndex(xe=>xe.id===z);return Mi[(ge+1)%Mi.length].id})},[]),Dt=o.useCallback(async()=>{typeof p=="function"&&await p()},[p]),Yt=o.useCallback(async z=>{var Fe;F(!0),A(null);const ge=await Ri(`/orgx/api/chat/threads/${encodeURIComponent(z)}`);if(!ge.ok||!((Fe=ge.data)!=null&&Fe.thread))return F(!1),A(Ei(ge.error,"load")),null;const xe=lh(ge.data.thread);return xe?(I(xe),F(!1),xe):(F(!1),A("Thread detail payload was invalid."),null)},[]),kn=o.useCallback(async(z,ge)=>{ge&&(te.current=ge),w(z),await Yt(z),requestAnimationFrame(()=>{var xe;return(xe=q.current)==null?void 0:xe.focus()})},[Yt]),ys=o.useCallback(()=>{var z;w(null),I(null),A(null),F(!1),(z=te.current)==null||z.focus()},[]),Vn=o.useCallback(z=>{window.setTimeout(()=>{G(ge=>ge.map(xe=>xe.id===z?{...xe,status:"indexing",updatedAt:new Date().toISOString()}:xe))},80),window.setTimeout(()=>{G(ge=>ge.map(xe=>{var Ct;if(xe.id!==z)return xe;const Fe=((Ct=xe.mimeType)==null?void 0:Ct.toLowerCase())==="application/x-msdownload"||xe.name.toLowerCase().endsWith(".exe"),_t=(xe.sizeBytes??0)>25*1024*1024;return Fe?{...xe,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:_t?{...xe,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...xe,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Gn=o.useCallback(z=>{if(!z||z.length===0)return;const ge=new Date().toISOString(),xe=Array.from(z).map(Fe=>({id:`draft_att_${crypto.randomUUID()}`,name:Fe.name,mimeType:Fe.type||null,sizeBytes:Number.isFinite(Fe.size)?Fe.size:null,status:"preparing",error:null,masked:!1,createdAt:ge,updatedAt:ge}));G(Fe=>Fe.concat(xe)),xe.forEach(Fe=>Vn(Fe.id)),Is("chat_attachment_state_changed",{count:xe.length,state:"preparing"})},[Vn]),Xn=o.useCallback(z=>{G(ge=>ge.map(xe=>xe.id===z?{...xe,status:"preparing",error:null,updatedAt:new Date().toISOString()}:xe)),Vn(z),Is("chat_attachment_state_changed",{state:"retry"})},[Vn]),Qn=o.useCallback(z=>{De(ge=>ge===z?"":z),de(ge=>ge.filter(xe=>xe!==z)),U(null),ye("")},[]),Ms=o.useCallback(z=>{de(ge=>ge.includes(z)?ge.filter(xe=>xe!==z):ge.concat(z))},[]),In=o.useCallback(()=>{me(!1),T(""),U(z=>z==="assignee"?null:"assignee"),ye("")},[]),tn=o.useCallback(()=>{me(!1),T(""),U(z=>z==="watcher"?null:"watcher"),ye("")},[]),dn=o.useCallback(()=>{U(null),ye(""),me(z=>!z),T("")},[]),hn=o.useCallback(async(z,ge)=>{var Ct;Se(!0);const xe=Ye.find(ot=>ot.id===ge)??null,Fe=await Ri("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:z,project_id:i??void 0,initiativeId:(xe==null?void 0:xe.id)??null,initiativeTitle:(xe==null?void 0:xe.name)??null,relinked:!0})});if(Se(!1),!Fe.ok||!((Ct=Fe.data)!=null&&Ct.thread)){A(Fe.error??"Scope link failed.");return}const _t=Or(Fe.data.thread);_t&&v(ot=>Aa(ot,_t)),await Yt(z),await Dt(),Is("chat_thread_linked_initiative",{threadId:z,initiativeId:(xe==null?void 0:xe.id)??null})},[Ye,Yt,Dt,i]),Es=o.useCallback(async z=>{wt(),await He({text:z.prompt},{body:{threadId:z.thread.id,project_id:i??void 0,initiativeId:z.thread.initiativeId??(ie==null?void 0:ie.id)??void 0,initiativeTitle:z.thread.initiativeTitle??(ie==null?void 0:ie.name)??void 0,assigneeId:(fe==null?void 0:fe.id)??z.thread.assigneeId??void 0,assigneeName:(fe==null?void 0:fe.name)??z.thread.assigneeName??void 0,watcherIds:Qe.map(ge=>ge.id),watcherNames:Qe.map(ge=>ge.name)}}),await Dt(),await Yt(z.thread.id)},[wt,Yt,Dt,fe==null?void 0:fe.id,fe==null?void 0:fe.name,ie==null?void 0:ie.id,ie==null?void 0:ie.name,Qe,He,i]),Yn=o.useCallback(async()=>{var _t,Ct;const z=P.trim();if(!z)return pe("Write a message before sending."),{thread:null,messageId:null};pe(null),re(null),D(!0);const ge=await Ri("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:h??void 0,project_id:i??void 0,initiativeId:(ie==null?void 0:ie.id)??(y==null?void 0:y.initiativeId)??void 0,initiativeTitle:(ie==null?void 0:ie.name)??(y==null?void 0:y.initiativeTitle)??void 0,assigneeId:(fe==null?void 0:fe.id)??(y==null?void 0:y.assigneeId)??void 0,assigneeName:(fe==null?void 0:fe.name)??(y==null?void 0:y.assigneeName)??void 0,watcherIds:Qe.map(ot=>ot.id),watcherNames:Qe.map(ot=>ot.name),body:z,attachments:ne.map(ot=>({id:ot.id,name:ot.name,mimeType:ot.mimeType,sizeBytes:ot.sizeBytes,status:ot.status,error:ot.error,masked:ot.masked}))})});if(D(!1),!ge.ok||!((_t=ge.data)!=null&&_t.thread))return pe(Ei(ge.error,"send")),Is("chat_message_send_failed",{reason:ge.error??"unknown"}),{thread:null,messageId:null};const xe=Or(ge.data.thread);if(!xe)return pe("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};v(ot=>Aa(ot,xe)),at({role:"user",body:z}),Be!=="auto"&&fe&&at({role:"system",body:`Routing to ${fe.name} via ${Rt.label}`}),Is("chat_message_sent",{threadId:xe.id,watcherCount:xe.watcherIds.length}),await Dt();const Fe=ge.data.message&&typeof ge.data.message.id=="string"?ge.data.message.id:((Ct=xe.latestMessage)==null?void 0:Ct.id)??null;return w(xe.id),await Yt(xe.id),Es({thread:xe,prompt:z}).catch(ot=>{at({role:"error",body:Ei(ot instanceof Error?ot.message:String(ot??""),"send")})}),Kt(),j("reviewing"),{thread:xe,messageId:Fe}},[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,P,ne,Yt,Dt,Kt,Es,fe==null?void 0:fe.id,fe==null?void 0:fe.name,ie==null?void 0:ie.id,ie==null?void 0:ie.name,Be,Rt,Qe,i]),bs=o.useCallback(async(z,ge)=>{var es,Ot,pn,ds,ts,Ls,Ds;if(!ge){at({role:"error",body:"Send a message first to launch."});return}if(!fe){at({role:"error",body:"Pick an agent with @ before launching."});return}if(vt>0&&!It){ht(!0),at({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}ve(!0),pe(null),re(null);const xe=await Ri("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:fe.id,message:P.trim().length>0?P.trim():z.lastSnippet??z.title,initiativeId:z.initiativeId??(ie==null?void 0:ie.id)??void 0,initiativeTitle:z.initiativeTitle??(ie==null?void 0:ie.name)??void 0,workstreamId:z.workstreamId??void 0,taskId:z.taskId??void 0,provider:Be!=="auto"?Be:void 0})}),Fe=((es=xe.data)==null?void 0:es.sessionId)??((Ot=xe.data)==null?void 0:Ot.runId)??null,_t=xe.ok&&Fe?"running":xe.ok?"queued":"blocked",Ct=xe.ok?null:xe.error??"Launch request failed before queueing.",ot=await Ri("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:z.id,messageId:ge,assigneeId:fe.id,assigneeName:fe.name,watcherIds:Qe.map(us=>us.id),watcherNames:Qe.map(us=>us.name),executionMode:"local_queue",provider:((pn=xe.data)==null?void 0:pn.provider)??(Be!=="auto"?Be:"openclaw"),runId:Fe??void 0,status:_t,blockedReason:Ct??void 0,warnings:vt>0?[`${vt} attachment(s) were not ready at launch.`]:[]})});if(ve(!1),We(!1),ht(!1),!ot.ok||!((ds=ot.data)!=null&&ds.thread)){pe(ot.error?Ei(ot.error,"launch"):Ct??"Launch state could not be persisted. Message remained saved."),Is("chat_launch_failed",{threadId:z.id,reason:ot.error??Ct??"unknown"});return}const nn=Or(ot.data.thread);if(nn&&v(us=>Aa(us,nn)),await Yt(z.id),await Dt(),!xe.ok){pe(`Launch blocked: ${Ct??"Set assignee and retry."}`),Is("chat_launch_blocked",{threadId:z.id,reason:Ct??"unknown"});return}const Tt=((ts=xe.data)==null?void 0:ts.provider)==="anthropic"?"Claude Code":((Ls=xe.data)==null?void 0:Ls.provider)==="openai"?"Codex":Rt.shortLabel,Zn=(Ds=xe.data)!=null&&Ds.model?` (${xe.data.model})`:"";re(Fe?`Launch started via ${Tt}${Zn}. Thread timeline now tracks execution state.`:`Launch queued locally via ${Tt}. Run starts when a worker is available.`),Is(Fe?"chat_launch_started":"chat_launch_queued",{threadId:z.id,runId:Fe,assigneeId:fe.id})},[P,It,Yt,Dt,fe,ie==null?void 0:ie.id,ie==null?void 0:ie.name,Be,Rt,Qe,vt]),ei=o.useCallback(async()=>{var ge;const z=await Yn();(ge=z.thread)!=null&&ge.id&&await kn(z.thread.id)},[kn,Yn]),Rs=o.useCallback(async()=>{const z=await Yn();z.thread&&(await bs(z.thread,z.messageId),await kn(z.thread.id))},[bs,kn,Yn]),Jt=o.useCallback(async()=>{if(X){if(fe){await Rs();return}await ei()}},[X,Rs,ei,fe]),En=o.useMemo(()=>({threads:g,activeThreadId:h,activeThread:y,activeThreadSummary:mt,displayedThreads:gt,composerMode:H,draft:P,draftAttachments:ne,sending:E,launching:ee,composerError:Ce,composerNotice:Ae,selectedAssigneeId:ae,selectedAssignee:fe,selectedWatcherIds:Te,selectedWatchers:Qe,selectedInitiativeId:we,selectedInitiative:ie,agentOptions:Ve,quickAssigneeOptions:V,initiativeOptions:Ye,agentPickerMode:O,agentPickerQuery:K,filteredAgentOptions:Re,scopePickerOpen:Oe,scopePickerQuery:ke,filteredInitiativeOptions:et,panelLoading:M,panelError:b,scopeSaving:Me,launchWarningOpen:J,launchWarningAccepted:It,unresolvedAttachmentCount:vt,canSend:X,composerGuidance:he,primaryActionLabel:qe,guidanceStatus:xt,guidancePreview:At,guidanceError:Qt??null,inlineMessages:be,threadSidebarOpen:Ee,workspaceId:i,selectedProvider:Be,selectedProviderDef:Rt}),[g,h,y,mt,gt,H,P,ne,E,ee,Ce,Ae,ae,fe,Te,Qe,we,ie,Ve,V,Ye,O,K,Re,Oe,ke,et,M,b,Me,J,It,vt,X,he,qe,xt,At,Qt,be,Ee,i,Be,Rt]),Jn=o.useMemo(()=>({setDraft:Z,setComposerMode:j,setDraftAttachments:G,selectAssignee:Qn,toggleWatcher:Ms,setSelectedInitiativeId:C,toggleAssigneePicker:In,toggleWatcherPicker:tn,toggleScopePicker:dn,setAgentPickerQuery:ye,setScopePickerQuery:T,setAgentPickerMode:U,setScopePickerOpen:me,handlePrimaryAction:Jt,handleFilesAdded:Gn,handleRetryAttachment:Xn,openThreadPanel:kn,closeThreadPanel:ys,loadThreadDetail:Yt,applyScopeLink:hn,resetComposer:Kt,setComposerError:pe,setComposerNotice:re,setLaunchWarningAccepted:We,pushInlineMessage:at,clearInlineMessages:st,toggleThreadSidebar:Ft,setSelectedProvider:ft,cycleProvider:$t,fileInputRef:Q,panelHeadingRef:q,composerShellRef:le}),[Qn,Ms,In,tn,dn,Jt,Gn,Xn,kn,ys,Yt,hn,Kt,at,st,Ft,$t]);return n.jsx(_c.Provider,{value:En,children:n.jsx(Sc.Provider,{value:Jn,children:e})})}const mh={type:"spring",stiffness:500,damping:35,mass:.5};function ph({messages:e,isStreaming:t,collapsed:s,onClick:i}){var c;const r=xs(),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(ce.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(Nt,{initial:!1,children:l.map(d=>n.jsx(ce.div,{initial:r?!1:{opacity:0,y:8,scale:.97},animate:r?{}:{opacity:1,y:0,scale:1},transition:r?void 0:mh,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:qt(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=xs(),{displayedThreads:i,activeThreadId:r,activeThread:a,activeThreadSummary:l,panelLoading:c,panelError:d,scopeSaving:u,initiativeOptions:p}=io(),{openThreadPanel:g,closeThreadPanel:v,loadThreadDetail:h,applyScopeLink:w,panelHeadingRef:y}=ro(),I=(a==null?void 0:a.id)??(l==null?void 0:l.id)??null,M=o.useCallback((b,A)=>{g(b,A)},[g]),F=o.useCallback(()=>{v(),t()},[v,t]);return n.jsx(Nt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(ce.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:F,className:"fixed inset-0 z-[24] bg-black/30"}),n.jsxs(ce.section,{initial:s?!1:{y:"100%"},animate:s?{}:{y:0},exit:s?{}:{y:"100%"},transition:s?void 0:{duration:Xt.durationEntrance/1e3,ease:Xt.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:F,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(ea,{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(b=>n.jsxs("button",{type:"button",onClick:A=>M(b.id,A.currentTarget),className:ue("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",r===b.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:b.lastSnippet?`"${b.lastSnippet.length>40?b.lastSnippet.slice(0,40)+"...":b.lastSnippet}"`:b.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:b.lastActivityAt,children:qt(b.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[b.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",b.assigneeName]}),n.jsx("span",{children:b.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",fi(b.status)),children:Gr(b.status)})]})]},b.id))})}),n.jsx(Nt,{initial:!1,children:r&&n.jsxs(ce.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:Xt.durationStandard/1e3,ease:Xt.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",fi((l==null?void 0:l.status)??"message_only")),children:Gr((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}),I&&n.jsx("button",{type:"button",onClick:()=>void h(I),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(b=>n.jsx("article",{className:ue("flex",b.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:ue("max-w-[90%] rounded-xl border px-2.5 py-1.5",b.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":b.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:b.senderName??jc(b.role)}),n.jsx("time",{dateTime:b.createdAt,children:qt(b.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:b.body})]})},b.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(b=>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",fi(Ac(b.status))),children:b.status}),n.jsx("span",{children:b.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:b.requestedAt,children:qt(b.requestedAt)})]},b.id))]})]})})]})]})]})})}function ml(){const e=xs(),{displayedThreads:t,activeThreadId:s,activeThread:i,activeThreadSummary:r,panelLoading:a,panelError:l,scopeSaving:c,initiativeOptions:d,threadSidebarOpen:u}=io(),{openThreadPanel:p,closeThreadPanel:g,loadThreadDetail:v,applyScopeLink:h,setComposerMode:w,toggleThreadSidebar:y,panelHeadingRef:I}=ro(),M=(i==null?void 0:i.id)??(r==null?void 0:r.id)??null,F=o.useCallback(()=>{y()},[y]);return u?n.jsx(Nt,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(ce.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:F,className:"fixed inset-0 z-[24] bg-black/30"},"sidebar-backdrop"),n.jsxs(ce.section,{initial:e?!1:{x:"-100%"},animate:e?{}:{x:0},exit:e?{}:{x:"-100%"},transition:e?void 0:{duration:Xt.durationEntrance/1e3,ease:Xt.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:F,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(ce.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:dl,transition:cl,onClick:()=>{F(),w("focused"),requestAnimationFrame(()=>{const b=document.getElementById("chat-dock-input");b instanceof HTMLTextAreaElement&&b.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((b,A)=>n.jsxs(ce.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:cl,delay:e?0:Math.min(A*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:dl,onClick:H=>void p(b.id,H.currentTarget),className:ue("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===b.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:b.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:b.lastActivityAt,children:qt(b.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:b.lastSnippet??b.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[b.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Zt,{name:b.assigneeName,hint:b.assigneeName,size:"xs"}),n.jsx("span",{children:b.assigneeName})]}),n.jsx("span",{children:b.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",fi(b.status)),children:Gr(b.status)})]})]},b.id))})}),n.jsx(Nt,{initial:!1,children:s&&n.jsxs(ce.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:Xt.durationStandard/1e3,ease:Xt.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:I,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",fi((r==null?void 0:r.status)??"message_only")),children:Gr((r==null?void 0:r.status)??"message_only")}),n.jsx("button",{type:"button",onClick:g,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}),M&&n.jsx("button",{type:"button",onClick:()=>void v(M),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(b=>n.jsx("article",{className:ue("flex",b.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:ue("max-w-[90%] rounded-xl border px-2.5 py-1.5",b.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":b.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:b.senderName??jc(b.role)}),n.jsx("time",{dateTime:b.createdAt,children:qt(b.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:b.body})]})},b.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(b=>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",fi(Ac(b.status))),children:b.status}),n.jsx("span",{children:b.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:b.requestedAt,children:qt(b.requestedAt)})]},b.id))]})]})})]},"sidebar-panel")]})}):null}const fh={type:"spring",stiffness:500,damping:30,mass:.5};function hh({open:e,agents:t,query:s,activeIndex:i,onSelect:r}){const a=xs(),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(Nt,{children:n.jsx(ce.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:fh,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 g=p===i;return n.jsxs("button",{type:"button",role:"option","aria-selected":g,"data-active":g,onClick:()=>r(u),onMouseDown:v=>v.preventDefault(),className:ue("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",g?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Zt,{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 gh={type:"spring",stiffness:500,damping:30,mass:.5};function xh({open:e,initiatives:t,query:s,activeIndex:i,onSelect:r}){const a=xs(),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(Nt,{children:n.jsx(ce.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:gh,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 g=p+1===i;return n.jsx("button",{type:"button",role:"option","aria-selected":g,"data-active":g,onClick:()=>r(u),onMouseDown:v=>v.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]",g?"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 yh({open:e,mode:t,agents:s,quickAgents:i,query:r,selectedAssigneeId:a,selectedWatcherIds:l,onQueryChange:c,onSelectAssignee:d,onToggleWatcher:u,onClose:p,onSwitchMode:g,anchorRef:v}){const h=xs();return n.jsx(Nt,{children:e&&n.jsxs(ce.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:Xt.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:()=>g("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:()=>g("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(w=>{const y=a===w.id;return n.jsx("button",{type:"button",onClick:()=>d(w.id),title:w.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 ${w.name} as assignee`,children:n.jsx(Zt,{name:w.name,hint:w.name,size:"xs"})},w.id)})}),n.jsx("input",{value:r,onChange:w=>c(w.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(w=>{const y=a===w.id,I=l.includes(w.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(w.id);return}y||u(w.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]":I?"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(Zt,{name:w.name,hint:w.name,size:"xs"}),n.jsx("span",{children:w.name})]}),n.jsx("span",{className:"text-micro",children:y?"Assignee":I?"Watcher":"Select"})]},w.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 bh(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 Ga="orgx-chat-dock-collapsed";function vh(){try{return localStorage.getItem(Ga)==="1"}catch{return!1}}function wh(){const e=io(),t=ro(),s=xs(),i=o.useRef(null),r=o.useRef(null),[a,l]=o.useState(vh),c=o.useCallback(()=>{l(V=>{const Re=!V;try{localStorage.setItem(Ga,Re?"1":"0")}catch{}return Re})},[]),[d,u]=o.useState(!1),[p,g]=o.useState(!1),v=o.useRef(null),[h,w]=o.useState(!1),[y,I]=o.useState(""),[M,F]=o.useState(0),[b,A]=o.useState(-1),[H,j]=o.useState(!1),[P,Z]=o.useState(""),[E,D]=o.useState(0),[ee,ve]=o.useState(-1),{composerMode:Ce,draft:pe,draftAttachments:Ae,sending:re,launching:ne,selectedAssigneeId:G,selectedAssignee:ae,selectedWatcherIds:De,selectedInitiative:Te,agentOptions:de,quickAssigneeOptions:we,agentPickerMode:C,agentPickerQuery:O,filteredAgentOptions:U,initiativeOptions:K,canSend:ye,activeThreadId:Oe,guidanceStatus:me,inlineMessages:ke,displayedThreads:T,launchWarningOpen:be,launchWarningAccepted:Y,selectedProvider:Ee,selectedProviderDef:ze}=e,Be=pe.trim(),ft=ke.length>0;Be.length>0;const Me=o.useCallback(()=>{const V=i.current;if(!V)return;V.style.height="0";const Re=Math.min(Math.max(V.scrollHeight,pl),fl);V.style.height=`${Re}px`},[]);o.useLayoutEffect(()=>{Me()},[pe,Me]);const Se=o.useMemo(()=>{if(!h)return de;const V=y.toLowerCase();return V?de.filter(Re=>Re.name.toLowerCase().includes(V)||Re.handle.toLowerCase().includes(V)||Re.domain.toLowerCase().includes(V)||Re.role.toLowerCase().includes(V)):de},[de,h,y]),J=o.useMemo(()=>{if(!H)return K;const V=P.toLowerCase();return V?K.filter(Re=>Re.name.toLowerCase().includes(V)):K},[K,H,P]);o.useEffect(()=>{if(v.current&&clearTimeout(v.current),ke.length<=2){g(!1);return}return g(!1),v.current=window.setTimeout(()=>{g(!0)},5e3),()=>{v.current&&clearTimeout(v.current)}},[ke.length]),o.useEffect(()=>{const V=Re=>{if((Re.metaKey||Re.ctrlKey)&&Re.key==="k"){if(Re.preventDefault(),a){l(!1);try{localStorage.setItem(Ga,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var et;return(et=i.current)==null?void 0:et.focus()})}};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[t,a]);const ht=o.useCallback(()=>{Ce==="resting"&&t.setComposerMode("focused")},[Ce,t]),It=o.useCallback(()=>{window.setTimeout(()=>{Be.length===0&&!ft&&!h&&!H&&Ae.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),w(!1),j(!1))},100)},[Be,ft,h,H,Ae.length,t]),We=o.useCallback(V=>{const Re=V.target.value,et=V.target.selectionStart??Re.length;t.setDraft(Re),(Ce==="resting"||Ce==="focused")&&t.setComposerMode("composing");const ct=Re.slice(0,et),gt=ct.match(/@(\w*)$/);if(gt){w(!0),I(gt[1]),F(0),A(et-gt[0].length),j(!1);return}const mt=ct.match(/#(\w*)$/);if(mt){j(!0),Z(mt[1]),D(0),ve(et-mt[0].length),w(!1);return}h&&w(!1),H&&j(!1)},[Ce,t,h,H]),Q=o.useCallback(V=>{var gt;const Re=pe.slice(0,b),et=pe.slice(((gt=i.current)==null?void 0:gt.selectionStart)??pe.length),ct=`${Re}@${V.name} ${et}`;t.setDraft(ct),t.selectAssignee(V.id),w(!1),I(""),requestAnimationFrame(()=>{if(i.current){const mt=Re.length+V.name.length+2;i.current.setSelectionRange(mt,mt),i.current.focus()}})},[pe,b,t]),q=o.useCallback(V=>{var ct;const Re=pe.slice(0,ee),et=pe.slice(((ct=i.current)==null?void 0:ct.selectionStart)??pe.length);if(V){const gt=`${Re}#${V.name} ${et}`;t.setDraft(gt),t.setSelectedInitiativeId(V.id),requestAnimationFrame(()=>{if(i.current){const mt=Re.length+V.name.length+2;i.current.setSelectionRange(mt,mt),i.current.focus()}})}else{const gt=`${Re}${et}`;t.setDraft(gt),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{i.current&&(i.current.setSelectionRange(Re.length,Re.length),i.current.focus())})}j(!1),Z("")},[pe,ee,t]),te=o.useCallback(V=>{if(h&&Se.length>0){if(V.key==="ArrowDown"){V.preventDefault(),F(Re=>(Re+1)%Se.length);return}if(V.key==="ArrowUp"){V.preventDefault(),F(Re=>(Re-1+Se.length)%Se.length);return}if(V.key==="Enter"||V.key==="Tab"){V.preventDefault(),Q(Se[M]);return}if(V.key==="Escape"){V.preventDefault(),w(!1);return}}if(H){const Re=J.length+1;if(V.key==="ArrowDown"){V.preventDefault(),D(et=>(et+1)%Re);return}if(V.key==="ArrowUp"){V.preventDefault(),D(et=>(et-1+Re)%Re);return}if(V.key==="Enter"||V.key==="Tab"){V.preventDefault(),q(E===0?null:J[E-1]);return}if(V.key==="Escape"){V.preventDefault(),j(!1);return}}if(V.key==="Enter"&&!V.shiftKey){V.preventDefault(),t.handlePrimaryAction();return}V.key==="Escape"&&(V.preventDefault(),C?t.setAgentPickerMode(null):ft?t.clearInlineMessages():(t.setComposerMode("resting"),V.target.blur()))},[t,C,ft,h,Se,M,Q,H,J,E,q]),le=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),$e=re||ne?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"})]}),Ve=(Ce==="reviewing"||ft)&&ke.length>0,Ye=me==="submitted"||me==="streaming",fe=o.useRef(ke.length),[Qe,ie]=o.useState(0);return o.useEffect(()=>{if(!a){fe.current=ke.length,ie(0);return}const V=ke.length-fe.current;V>0&&ie(V)},[a,ke.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(ce.button,{type:"button",onClick:()=>{c(),requestAnimationFrame(()=>{var V;return(V=i.current)==null?void 0:V.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(Nt,{children:Qe>0&&n.jsx(ce.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:Qe>9?"9+":Qe},"unread")}),Oe&&Qe===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:V=>{t.composerShellRef.current=V},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(Nt,{children:be&&n.jsxs(ce.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:V=>t.setLaunchWarningAccepted(V.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(yh,{open:C!==null,mode:C??"assignee",agents:U,quickAgents:we,query:O,selectedAssigneeId:G,selectedWatcherIds:De,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:r})}),n.jsxs(ce.section,{"data-testid":"chat-dock","data-state":Ce,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:Xt.durationEntrance/1e3,ease:Xt.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",Ce!=="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:V=>{t.fileInputRef.current=V},type:"file",multiple:!0,className:"hidden",onChange:V=>{t.handleFilesAdded(V.target.files),V.currentTarget.value=""}}),n.jsx(Nt,{children:Ve&&n.jsx(ph,{messages:ke,isStreaming:Ye,collapsed:p,onClick:le})}),n.jsxs("div",{className:"relative",children:[n.jsx(hh,{open:h,agents:Se,query:y,activeIndex:M,anchorRect:null,onSelect:Q,onClose:()=>w(!1)}),n.jsx(xh,{open:H,initiatives:J,query:P,activeIndex:E,onSelect:q,onClose:()=>j(!1)})]}),n.jsx(Nt,{initial:!1,children:Ae.length>0&&n.jsx(ce.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:Ae.map(V=>n.jsxs("div",{className:ue("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",V.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(V.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:hl(V.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:V.name}),n.jsxs("p",{className:"text-micro text-muted",children:[bh(V.mimeType,V.name),V.sizeBytes?` · ${nh(V.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments(Re=>Re.filter(et=>et.id!==V.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 ${V.name}`,children:"×"}),V.status!=="ready"&&V.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]"})}),V.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(V.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"})]},V.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var V;return(V=t.fileInputRef.current)==null?void 0:V.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(ce.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",Ee==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":Ee==="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: ${ze.label}. Click to switch.`,"aria-label":`Current provider: ${ze.label}. Click to cycle.`,children:[n.jsx(gl,{icon:ze.icon}),n.jsx("span",{children:ze.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:pe,onFocus:ht,onBlur:It,onChange:We,onKeyDown:te,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":Ce!=="resting"})]}),T.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":`${T.length} thread${T.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"})}),T.length]}),n.jsx(ce.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!ye,"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",ye?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:ae?`Send to ${ae.name} via ${ze.shortLabel}`:`Send via ${ze.shortLabel}`,"aria-label":ae?`Send to ${ae.name} via ${ze.shortLabel}`:`Send message via ${ze.shortLabel}`,children:$e})]}),n.jsx(Nt,{children:(ae||Te)&&Ce!=="resting"&&n.jsxs(ce.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:[ae&&n.jsxs("button",{ref:V=>{r.current=V},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(Zt,{name:ae.name,hint:ae.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",ae.name]}),ae.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),Te&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",Te.name]}),Ee!=="auto"&&n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro",style:{color:ze.accent},children:[n.jsx(gl,{icon:ze.icon}),ze.shortLabel]})]})})]})]})]})}const xl={completed:L.lime,needs_attention:L.amber,in_progress:L.teal,blocked:L.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,g)=>(p[g.status]=(p[g.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:L.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:L.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:L.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:L.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:L.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(Nt,{children:a&&n.jsx(ce.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,g)=>n.jsxs(ce.button,{type:"button",initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{delay:g*.04,duration:.15},onClick:()=>r==null?void 0:r(g),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:qt(p.timestamp)})]},`burst-${g}`))})})})]})}const _a=50,kh=50,Li=20,bl=3600,vl=12e3,Ih=o.memo(function({startMs:t,endMs:s,isTerminal:i}){const[r,a]=o.useState(()=>Date.now());o.useEffect(()=>{if(!t||s||i)return;const c=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(c)},[s,i,t]);const l=o.useMemo(()=>{if(!t)return null;const c=s??(i?null:r);if(!c)return null;const d=Math.max(0,c-t);return d<6e4?`${Math.round(d/1e3)}s`:`${Math.floor(d/6e4)}m ${Math.round(d%6e4/1e3)}s`},[s,i,r,t]);return l?n.jsx(n.Fragment,{children:l}):null});function kr(e,t,s){if(!t)return;const i=e.get(t);if(i){i.push(s);return}e.set(t,[s])}function Nh(e,t){const s=new Set,i=[];for(const r of t){const a=e.get(r);if(a)for(const l of a)s.has(l.item.id)||(s.add(l.item.id),i.push(l))}return i}const Ir={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 jh(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 gs(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Nr(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function jr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Sa(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 Gt(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function ao(e){if(!e)return;let t={...e},s=Gt(t.metadata),i=0;for(;s&&i<4;)t={...t,...s},s=Gt(s.metadata),i+=1;return t}function ut(e){const t=Gt(e==null?void 0:e.metadata);return ao(t)}function Ah(e){const t=ao(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=ut(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 Xs(e){const t=ut(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 _h=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Sh=/^[0-9a-f]{20,}$/i,Cc=/^\d+$/,Tc=/^(user|usr|clerk)_[a-z0-9]+$/i;function vn(e){if(!e)return null;const t=e.trim();return!t||_h.test(t)||Sh.test(t)||Cc.test(t)||Tc.test(t)?null:t}const Ch=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function Th(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return Ch.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=vn(Al(e[a]));if(l){i=l;break}}let r=null;for(const a of s){const l=vn(Al(e[a]));if(l){r=l;break}}return!i&&!r?null:{id:i,name:r,label:r??i??"OrgX"}}function Mh(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=ut(e),s=Xs(e),i=Ki(e),r=vn(s.agentId),a=vn(s.agentName),l=vn(e.requesterAgentId??null),c=vn(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=vn(e.executorAgentId??null),g=vn(e.executorAgentName??null),h=(p||g?{id:p,name:g,label:g??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?Mh(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:vn(e.agentName??null)??vn(e.agentId??null)??"OrgX",subtitle:vn(e.agentName??null)??vn(e.agentId??null)??"OrgX"}}function Cl(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}const Eh=new Set(["autopilot_slice_dispatched","auto_continue_started","auto_continue_stopped","autopilot_transition","orchestrator_selection","orchestrator_dispatch"]),Rh=new Set(["heartbeat","spawn_guard_blocked","spawn_guard_rate_limited"]);function Lh(e,t){var a;if(e.requesterAgentId==="main"||e.agentId==="main")return"user";const s=ut(e),i=oe(s,["event","event_name","eventName"])??"";return(oe(s,["source"])??"")==="user"?"user":Eh.has(i)||(a=t.primaryLabel)!=null&&a.toLowerCase().includes("xandy")?"orchestrator":t.mode==="system"||Rh.has(i)?"system":"agent"}const Dh={user:L.lime,system:"rgba(255,255,255,0.15)",orchestrator:L.iris,agent:""};function Ph(e){switch(e){case"user":return"You";case"system":return"OrgX";case"orchestrator":return"Xandy";case"agent":return""}}function Hs(e){const t=ut(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 Ar(e){const t=ut(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 _r(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function Mc(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 Ys(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 $h(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 Oh(e){const t=ut(e),s=_r(e.kind)??_r(t==null?void 0:t.activity_bucket)??_r(t==null?void 0:t.activityBucket)??_r(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=$h(t),r=e.decisionRequired===!0||Mc(t,["decision_required","decisionRequired"])===!0,a=Ys(t,["artifacts","artifact_count","artifactCount"])??0,l=Ys(t,["decisions","decision_count","decisionCount"])??0,c=Ys(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Ys(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=On(oe(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 qh(e,t){if(e.type==="run_completed"||e.type==="milestone_completed"||e.type==="decision_resolved")return!0;const s=oe(t,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]);if(Gi(s))return!0;const i=oe(t,["stop_reason","stopReason"]);if(On(i)==="completed")return!0;const r=t?Ec(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]):null,a=e.decisionRequired===!0||Mc(t,["decision_required","decisionRequired"])===!0,l=Ys(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0;return r!==null&&r>=100&&!a&&l===0}function Bi(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 Bh(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 Ca(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function Ta(e){return e==="completed"?L.lime:e==="needs_input"?L.amber:e==="issue"?L.red:L.teal}function zh(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=ut(i.item),a=oe(r,["workstream_title","workstreamTitle","dispatch_workstream_title"]);a&&(t=a);const c=oe(r,["task_title","taskTitle","dispatch_task_title"])??Ki(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 Cs(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 wn(e){const t=Cs(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=Cs(s.count??s.total??s.size);if(i!==null)return Math.max(0,Math.round(i))}return null}function Uh(e){const t=Cs(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 Ec(e,t){for(const s of t){const i=Uh(e[s]);if(i!==null)return i}return null}function Sr(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 Rc(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=Sr(e,["blocking_decision_ids","blockingDecisionIds"]),s=Sr(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),i=Sr(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=Sr(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 Lc(e){if(!e)return null;const t=ut(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=Xs(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):[],g=eg(p),v=t.task_ids??t.taskIds,h=Array.isArray(v)?v.filter(Y=>typeof Y=="string"&&Y.trim().length>0):[],w=t.milestone_ids??t.milestoneIds,y=Array.isArray(w)?w.filter(Y=>typeof Y=="string"&&Y.trim().length>0):[],I=oe(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),M=oe(t,["initiative_title","initiativeTitle"]),F=oe(t,["initiative_status","initiativeStatus"]),b=Hs(e),A=oe(t,["workstream_title","workstreamTitle"]),H=oe(t,["workstream_status","workstreamStatus"]),j=oe(t,["task_title","taskTitle"]),P=oe(t,["milestone_title","milestoneTitle"]),Z=oe(t,["domain"]),E=oe(t,["phase","slice_phase","slicePhase"]),D=oe(t,["next_step","nextStep"]),ee=Ec(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),ve=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,Ce=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,pe=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,Ae=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,re=typeof t.error=="string"?t.error:null,ne=wn(t.artifacts??t.artifact_count??t.artifactCount),G=wn(t.decisions??t.decision_count??t.decisionCount),ae=Rc(t),De=t.decisions_needed??t.decisionsNeeded;let Te=wn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),de=wn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((Te===null||de===null)&&Array.isArray(De)){let Y=0,Ee=0;for(const ze of De){if(!ze||typeof ze!="object"||Array.isArray(ze))continue;ze.blocking===!1?Ee+=1:Y+=1}Te===null&&(Te=Y),de===null&&(de=Ee)}Te===null&&G!==null&&e.decisionRequired===!0&&(Te=G>0?G:1),de===null&&G!==null&&Te!==null&&(de=Math.max(0,G-Te)),Te===null&&G!==null&&de!==null&&(Te=Math.max(0,G-de));const we=wn(t.status_updates_applied??t.statusUpdatesApplied),C=wn(t.task_updates??t.taskUpdates),O=wn(t.milestone_updates??t.milestoneUpdates),U=we??(C!==null||O!==null?(C??0)+(O??0):null),K=wn(t.status_updates_buffered??t.statusUpdatesBuffered),ye=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,Oe=Cs(t.token_budget??t.tokenBudget),me=Cs(t.tokens_used??t.tokensUsed),ke=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),T=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)??g,be=g&&!a.agentName?null:ke;return{event:s,agentId:be,agentName:T,requesterAgentId:l,requesterAgentName:c,dispatcherClient:d,initiativeId:I,domain:Z,phase:E,progressPct:ee,nextStep:D,requiredSkills:p,initiativeStatus:F,initiativeTitle:M,workstreamId:b,workstreamStatus:H,workstreamTitle:A,taskTitle:j,milestoneTitle:P,taskIds:h,milestoneIds:y,parsedStatus:ve,hasOutput:Ce,artifacts:ne,decisions:G,blockingDecisions:Te,nonBlockingDecisions:de,decisionIds:ae.decisionIds,blockingDecisionIds:ae.blockingDecisionIds,nonBlockingDecisionIds:ae.nonBlockingDecisionIds,statusUpdatesApplied:U,statusUpdatesBuffered:K,stopReason:ye,tokenBudget:Oe,tokensUsed:me,logPath:pe,outputPath:Ae,error:re}}function qr(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function Wh(e){const t=ao(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),g=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,v=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,w=typeof s.provider=="string"?s.provider:null,y=typeof s.model=="string"?s.model:null,I=typeof s.domain=="string"?s.domain:null,M=s.required_skills??s.requiredSkills,F=Array.isArray(M)?M.filter(A=>typeof A=="string"&&A.trim().length>0):[];return!!l||!!(c||d||u)||!!g||!!(h||w||y||I)||F.length>0?{pluginVersion:l,skillPack:c||d||u||p?{name:c,version:d,checksum:u,source:p}:null,kickoffContextHash:g,kickoffContextSource:v,modelTier:h,provider:w,model:y,domain:I,requiredSkills:F}:null}function Dc(e){if(!e)return null;const t=ut(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 Xr(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":rt(e)}function Hh(e){const t=ut(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),i=Dc(e);if(!i&&!s)return null;const r=oe(t,["artifact_type","artifactType","atomic_unit_type"]),a=oe(t,["artifact_title","title","name"]),l=oe(t,["url","pr_url","commit_url"]),c=Xr(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 g=Object.keys(p);u=g.length<=4?g.join(", "):`${g.length} fields`}}return{label:d,preview:u,hasRegisteredId:s,title:a,typeBadge:c,url:l}}function Kh(e){const t=ut(e);if(!t)return[];const s=[],i=t.outcomes&&typeof t.outcomes=="object"?t.outcomes:null,r=oe(t,["pr_url"])??(i?oe(i,["pr_url"]):null),a=oe(t,["pr_number"])??(i?oe(i,["pr_number"]):null);(a||r)&&s.push({kind:"pr",label:a?`#${a}`:"linked",url:r});const l=oe(t,["commit_sha"])??(i?oe(i,["commit_sha"]):null),c=oe(t,["commit_url"])??(i?oe(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 g=d,v=typeof g.passed=="number"?g.passed:null,h=typeof g.failed=="number"?g.failed:null;if(v!==null||h!==null){const w=[];v!==null&&w.push(`${v} passed`),h!==null&&h>0&&w.push(`${h} failed`),s.push({kind:"test",label:w.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 g=p[0],v=g&&typeof g=="object"&&typeof g.title=="string"?g.title:null;s.push({kind:"doc",label:v??`${p.length} artifact${p.length===1?"":"s"}`})}return s}function ta(e){if(!e)return[];const t=Gt(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=Gt(d);if(!u)continue;const p=l==="Task"?["task_id","taskId","id"]:["milestone_id","milestoneId","id"],g=l==="Task"?["task_title","taskTitle","title","name"]:["milestone_title","milestoneTitle","title","name"],v=oe(u,p),h=oe(u,g)??(v&&!Hn(v)?v:null)??l,w=js(h,v)??rt(h),y=oe(u,["status","state"]),I=Ht(oe(u,["reason","summary","description","note"])),M=`${l}|${w.toLowerCase()}|${(y??"").toLowerCase()}|${(I??"").toLowerCase()}`;r.has(M)||(r.add(M),i.push({scope:l,label:w,status:y?rt(y):null,reason:I}))}};for(const l of s)a("Task",l.task_updates??l.taskUpdates),a("Milestone",l.milestone_updates??l.milestoneUpdates);return i}function Vh(e){var c;const t=ut(e);if(!t)return null;const s=((c=oe(t,["event","event_name","eventName"]))==null?void 0:c.toLowerCase())??"",i=ta(t),r=wn(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 Gh(e){if(!e)return!1;const t=ut(e);if(!t)return!1;const s=Gt(t.outcomes),i=Gt(s==null?void 0:s.tests),r=ta(t),a=wn(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 Pc(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=ut(e);if(!t)return[];const s=[],i=new Set,r=(l,c)=>{if(typeof c!="string")return;const d=c.trim();if(!d||!Pc(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 g=c?`${c}.${u}`:u,v=u.toLowerCase();if(v.includes("path")||v==="url"||v==="uri"||v.endsWith("url")||v.endsWith("_file")||v.endsWith("file")||v.includes("artifact"))if(Array.isArray(p))for(const w of p)r(g,w);else r(g,p);p&&typeof p=="object"&&!Array.isArray(p)&&a(p,g,d+1)}};return a(t),s}function oe(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 Xh=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,Qh=/\b[0-9a-f]{20,}\b/gi;function Oc(e){let t=e.replace(Xh,"").replace(Qh,"").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 Yh(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 js(e,t){if(typeof e!="string")return null;const s=Oc(e.trim());if(!s)return null;const i=typeof t=="string"?t.trim().toLowerCase():"";if(i&&s.toLowerCase()===i||Hn(s))return null;const r=rt(s).trim();return r.length>0?r:null}function Cr(e){for(const t of e){const s=js(t.value,t.idHint);if(s)return s}return null}function Jh(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 Zh(e,t){if(!e)return null;const s=ut(e);if(!s)return null;const i=oe(s,["event","event_name","eventName"]),r=Gt(s.spawn_guard),a=Gt(r==null?void 0:r.checks),l=Gt((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),c=oe(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=Jh(c),u=Cs(l==null?void 0:l.current)??d.domainCurrent,p=Cs(l==null?void 0:l.max)??d.domainMax,g=d.totalCurrent,v=d.totalMax,h=typeof(l==null?void 0:l.passed)=="boolean"?l.passed:null,w=((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)&&!w&&!r&&!c?null:{event:i,blockedReason:c,domain:oe(s,["domain"])??oe(r,["domain","task_domain"]),modelTier:oe(s,["spawn_guard_model_tier","model_tier"])??oe(r,["modelTier","model_tier"]),domainCurrent:u,domainMax:p,totalCurrent:g,totalMax:v,retryAt:oe(s,["next_retry_at","nextRetryAt"]),retryInMs:Cs(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:w}}function eg(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 ${rt(r)}`}return null}function tg(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 Ma(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&&tg(i)?a:i??a;if(l)return oa(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"?oa(r):$i.test(r)||ng.test(r)||Cc.test(r)||Tc.test(r)?"OrgX":oa(r)}const $i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ng=/^[0-9a-f]{20,}$/i,sg=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function Qr(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(sg)??[]){const c=l.trim().toLowerCase();$i.test(c)&&t.add(c)}typeof e.runId=="string"&&$i.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=ut(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();$i.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();$i.test(d)&&t.add(d)}}return t}function ig(e){if(!e)return[];const t=ut(e);return Rc(t).decisionIds}function rg(e,t,s){if(!e)return[];const i=ut(e),r=oe(i,["workstream_id","workstreamId"]),a=oe(i,["initiative_id","initiativeId"]),l=Qr(e);if(!r&&!a&&l.size===0)return[];const c=gs(e.timestamp),d=[];for(const v of t){if(v.id===e.id)continue;const h=ut(v);if(!h)continue;const w=oe(h,["workstream_id","workstreamId"]),y=oe(h,["initiative_id","initiativeId"]),I=Qr(v),M=l.size>0&&Array.from(l).some(P=>I.has(P)),F=!!r&&!!w&&r===w;if(!M&&!F&&!(!!a&&!!y&&a===y))continue;const A=$c(v).filter(P=>!s.has(P.path));if(A.length===0)continue;const H=Math.abs(gs(v.timestamp)-c);if(!M&&H>7200*1e3)continue;const j=M?0:F?1:2;!M&&H>1200*1e3||d.push({priority:j,delta:H,evidence:A})}if(d.length===0)return[];d.sort((v,h)=>v.priority!==h.priority?v.priority-h.priority:v.delta-h.delta);const u=[],p=new Set(s),g=d[0].priority;for(const v of d){if(v.priority!==g)break;for(const h of v.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 ag(e,t){if(!e)return null;const s=ut(e),i=oe(s,["workstream_id","workstreamId"]),r=oe(s,["initiative_id","initiativeId"]),a=Qr(e);if(!i&&!r&&a.size===0)return null;const l=gs(e.timestamp),c=[];for(const u of t){if(u.id===e.id)continue;const p=Lc(u);if(!p)continue;const g=ut(u);if(!g)continue;const v=oe(g,["workstream_id","workstreamId"]),h=oe(g,["initiative_id","initiativeId"]),w=Qr(u),y=a.size>0&&Array.from(a).some(H=>w.has(H)),I=!!i&&!!v&&i===v;if(!y&&!I&&!(!!r&&!!h&&r===h))continue;const F=Math.abs(gs(u.timestamp)-l);if(!y&&F>1200*1e3)continue;const b=y?"shared_id":I?"workstream":"initiative",A=b==="shared_id"?0:b==="workstream"?1:2;c.push({priority:A,delta:F,relation:b,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 On(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function Gi(e){const t=On(e);return["done","complete","completed","stopped","success"].includes(t)}function og(e){const t=On(e.parsedStatus),s=On(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":Gi(t)||e.stopReason==="completed"?"positive":"neutral"}function lg(e){if(Gi(e.parsedStatus)||e.stopReason==="completed")return 100;const t=On(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 qc(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function cg(e,t){if(!e&&t===null)return null;const s=e?og(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=qc(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=lg(e);if(a===null)return null;const l=i(a);return{pct:a,source:"lifecycle",label:l?r:"Progress",tone:s,terminalStop:l}}function dg(e,t,s,i=null){var M;const r=ut(e),a=On(oe(r,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),l=On(e.state??e.phase??e.kind??e.type),c=On((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??l),d=On((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=oe(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),g=Math.max(0,(s==null?void 0:s.blockingDecisions)??(t==null?void 0:t.blockingDecisions)??(e.decisionRequired===!0?Math.max(1,p):0)),v=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,p-g)),h=e.decisionRequired===!0||e.type==="decision_requested"||g>0||c==="needs_decision"&&v===0,w=e.type==="run_completed"||e.type==="milestone_completed"||Gi(c)||d==="completed",y=a.includes("spawn_guard_rate_limited")||!!(u&&/rate limit/i.test(u)),I=a.includes("spawn_guard_blocked");if(a==="auto_continue_started")return{label:"Autopilot on",summary:Ht(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 F=typeof(r==null?void 0:r.tasks_completed)=="number"?r.tasks_completed:null;return{label:"All done",summary:F?`All queued work complete — ${F} task${F===1?"":"s"} finished`:"All queued work complete",hint:null,tone:"positive"}}if(d==="stopped")return{label:"Stopped",summary:Ht(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:Ht(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:Ht(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 F=String((r==null?void 0:r.new_state)??"");return F==="running"?{label:"Resumed",summary:"Resumed — dispatching work",hint:"Autopilot is actively working through the queue.",tone:"positive"}:F==="blocked"||F==="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(I)return{label:"Waiting on system",summary:u?Ht(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:v>0?"Completed + follow-up":"Completed",summary:v>0?`Execution completed. ${v} non-blocking decision${v===1?"":"s"} were logged for optional follow-up.`:i.sentence,hint:i.nextAction,tone:"positive"};if(i.status==="failed")return{label:"Failed",summary:u?Ht(u)??i.sentence:i.sentence,hint:i.nextAction,tone:"critical"};if(i.status==="needs_attention"){const F=h||(((M=i.nextAction)==null?void 0:M.toLowerCase().includes("decision"))??!1);return{label:F?"Needs decision":"Needs attention",summary:i.sentence,hint:i.nextAction??(F?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:F?"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?Ht(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"}:w&&v>0?{label:"Completed + follow-up",summary:`Execution completed. ${v} non-blocking decision${v===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"}:w?{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 Bc(e){if(typeof e=="string")return n.jsx(qi,{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:Bc(t)},`artifact-list-${s}`))});if(e&&typeof e=="object"){const t=pg(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:rt(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 ug(e){if(!e)return null;const t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^file:\/\//i.test(t)||!Pc(t)?null:qr(t):null}function mg(e){const t=Gt(e);if(!t)return null;const s=Gt(t.result),i=Gt(t.outcomes),r=[s,i,t].filter(E=>!!E),a=E=>{for(const D of r)for(const ee of E){if(!(ee in D))continue;const ve=D[ee];if(ve!=null)return ve}return null},l=E=>{for(const D of r){const ee=oe(D,E);if(ee)return ee}return null},c=Ht(l(["summary","user_summary","description","message"])),d=[],u=new Set,p=E=>{if(!E)return;const D=E.trim();if(!D)return;const ee=D.toLowerCase();u.has(ee)||(u.add(ee),d.push(D))},g=(E,D)=>{if(Array.isArray(E))for(const ee of E){const ve=Gt(ee);if(!ve)continue;const Ce=oe(ve,[`${D.toLowerCase()}_id`,`${D.toLowerCase()}Id`,"id"]),pe=oe(ve,[`${D.toLowerCase()}_title`,`${D.toLowerCase()}Title`,"title","name"])??(Ce&&!Hn(Ce)?Ce:null),Ae=oe(ve,["status","state"]),re=Ht(oe(ve,["reason","summary","description","note"])),ne=pe?js(pe,Ce)??rt(pe):D,G=Ae?rt(Ae):null,ae=[ne];G&&ae.push(`→ ${G}`),re&&ae.push(`· ${re}`),p(ae.join(" "))}};for(const E of r)g(E.task_updates??E.taskUpdates,"Task"),g(E.milestone_updates??E.milestoneUpdates,"Milestone");const v=wn(a(["status_updates_applied","statusUpdatesApplied"]));v!==null&&v>0&&p(`${v} status update${v===1?"":"s"} applied`);const h=a(["status_updates_buffered","statusUpdatesBuffered"]),w=wn(h);(h===!0||w!==null&&w>0)&&p("Status updates buffered for sync");const I=[],M=new Set,F=E=>{const D=Ht(E);if(!D)return;const ee=D.toLowerCase();M.has(ee)||(M.add(ee),I.push(D))};F(l(["next_step","nextStep"]));for(const E of r){const D=E.next_actions??E.nextActions;if(Array.isArray(D))for(const ee of D)typeof ee=="string"&&F(ee)}const b=[],A=new Set,H=(E,D,ee)=>{const ve=`${E.toLowerCase()}|${(D??"").toLowerCase()}|${ee??""}`;A.has(ve)||(A.add(ve),b.push({title:E,type:D,url:ee}))},j=E=>{const D=Array.isArray(E)?E:E?[E]:[];for(const ee of D){const ve=Gt(ee);if(!ve){if(typeof ee=="string"&&ee.trim().length>0){const re=Ht(ee)??rt(ee);re&&H(re,null,null)}continue}const Ce=oe(ve,["artifact_type","artifactType","type"]),pe=oe(ve,["url","source_pointer","sourcePointer","path"]),Ae=oe(ve,["name","title","artifact_title","artifactTitle"])??(pe?Wn(pe):Xr(Ce));H(rt(Ae),Ce,pe)}};for(const E of r)j(E.artifacts??E.artifact);const P=l(["artifact_type","artifactType"]),Z=l(["url","artifact_url","artifactUrl"]);if(b.length===0&&(P||Z)){const E=Z?Wn(Z):Xr(P);H(rt(E),P,Z)}return!c&&d.length===0&&b.length===0&&I.length===0?null:{summary:c,updatesApplied:d,artifactsCreated:b,nextUp:I}}function pg(e){const t=mg(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=ug(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:Xr(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:Wn(s.url)})}):n.jsx("p",{className:"mt-1 truncate text-micro text-secondary",children:Wn(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 Ht(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=zi(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:rt(t)}const fg=[/^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 hg(e){return fg.some(t=>t.test(e))}function Fc(e){const t=ut(e);if(!t)return null;const s=oe(t,["user_summary","userSummary"]);if(s)return s;const i=oe(t,["task_title","taskTitle","dispatch_task_title"])??oe(t,["workstream_title","workstreamTitle","dispatch_workstream_title"]),r=oe(t,["event","event_name","eventName"]),a=oe(t,["parsed_status","status"]),l=oe(t,["stop_reason","stopReason"]),c=oe(t,["artifact_type","artifactType"]),d=oe(t,["artifact_title","title","name"]),u=oe(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=ta(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?rt(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=oe(t,["decision_title","decisionTitle","title"]);return p?`Decision needed: ${p}`:"Decision needed"}if(r==="decision_resolved"){const p=oe(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 gg(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 Ki(e){const t=Fc(e);if(t)return{title:t,isSystem:!1};const s=e.title??"";if(!hg(s)){const i=Yh(rt(Oc(s)));if(i&&i!=="Untitled session")return{title:i,isSystem:!1};const r=e.metadata,a=hd(r);return a!=="Activity event"?{title:a,isSystem:!1}:{title:rt(Bi(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 xg=new Set(["autopilot_transition","heartbeat","orchestrator_selection","orchestrator_dispatch","spawn_guard_blocked","spawn_guard_rate_limited","delegation_flow_started","delegation_flow_completed"]),yg=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 Fi(e){const t=ut(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&&yg.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||!Fi(e))return null;const t=ut(e),s=wn((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=oe(t,["entity_type","entityType"])??r??(e.type==="milestone_completed"?"milestone":null),l=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",c=a?` for ${rt(a).toLowerCase()}`:"";return`${l}${c} were synced from local replay.`}function Ea(e){if(!Fi(e))return null;const t=ut(e);if(!t)return null;const s=oe(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const i=oe(t,["event","event_name","eventName"])??"",r=oe(t,["changeset_id","changesetId"])??"",a=oe(t,["entity_type","entityType"])??"",l=oe(t,["entity_id","entityId"])??"",c=ui(e)??"",d=Ki(e).title.trim().toLowerCase();return`fallback:${i.toLowerCase()}:${r.toLowerCase()}:${a.toLowerCase()}:${l.toLowerCase()}:${c.toLowerCase()}:${d}`}function bg(e){if(!e)return null;const t=ut(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 vg=[/^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=Fc(e);if(s)return s;let r=(Ht(t??e.summary)??Ht(e.description)??rt(e.title||Bi(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 vg)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 wg=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:g="live",onTimeFilterChange:v,customTimeRange:h={startIso:null,endIso:null},onCustomTimeRangeChange:w,hasMore:y=!1,isLoadingMore:I=!1,onLoadMore:M,onClearSelection:F,onClearWorkstreamFilter:b,onClearAgentFilter:A,onFocusRunId:H,onOpenDecision:j,onResolveDecision:P,requestedActivityItemId:Z=null,onActivityItemRequestHandled:E,onPlayNextUp:D,onStartAutopilot:ee,onPauseWorkstream:ve,onCreateInitiative:Ce,onOpenMissionControl:pe,onOpenSettings:Ae,workspaceId:re=null,chatSnapshot:ne,onRefreshData:G,isLoading:ae=!1,onOpenNextUp:De,devMode:Te=!1,nextUpQueue:de,autopilotState:we=null}){var _e;const C=xs(),{open:O}=vc(),U=o.useMemo(()=>{if(!de)return new Map;const m=new Map;for(let x=0;x<de.length;x++){const k=de[x];m.set(k.workstreamId,{rank:x+1,title:k.workstreamTitle,state:k.queueState})}return m},[de]),[K,ye]=o.useState("all"),[Oe,me]=o.useState(!1),[ke,T]=o.useState(""),[be,Y]=o.useState(new Set),[Ee,ze]=o.useState({}),[Be,ft]=o.useState("oldest"),[Me,Se]=o.useState(!1),[J,ht]=o.useState(!1),[It,We]=o.useState(_a),[Q,q]=o.useState(null),[te,le]=o.useState(null),[$e,Ve]=o.useState(!1),[Ye,fe]=o.useState(1),[Qe,ie]=o.useState("structured"),[V,Re]=o.useState(null),[et,ct]=o.useState("feed"),[gt,mt]=o.useState(null),[vt,jt]=o.useState(null),[X,he]=o.useState(null),[qe,nt]=o.useState(null),[Ke,Xe]=o.useState(!1),[He,xt]=o.useState(null),[Qt,wt]=o.useState(!1),At=o.useRef(Date.now()),Pt=o.useRef(null),Kt=o.useRef(null),at=o.useRef(null),st=o.useRef(null),Ft=o.useRef(null),[Rt,$t]=o.useState(()=>Nr(h.startIso)),[Dt,Yt]=o.useState(()=>Nr(h.endIso)),[kn,ys]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),Vn=o.useMemo(()=>Zl(g),[g]),Gn=o.useMemo(()=>Nr(h.startIso),[h.startIso]),Xn=o.useMemo(()=>Nr(h.endIso),[h.endIso]),Qn=o.useMemo(()=>!Rt||!Dt?!1:Dt.getTime()>=Rt.getTime(),[Dt,Rt]),Ms=o.useMemo(()=>g!=="custom"?Vn.label:Gn&&Xn?`${jr(Gn)} - ${jr(Xn)}`:"Custom range",[Xn,Gn,g,Vn.label]);o.useEffect(()=>{$t(Gn),Yt(Xn)},[Xn,Gn]),o.useEffect(()=>{if(typeof window>"u")return;const m=()=>ys(window.innerWidth<=640);return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]),o.useEffect(()=>{const x=()=>{At.current=Date.now()};window.addEventListener("pointerdown",x),window.addEventListener("keydown",x);const k=setInterval(()=>{Date.now()-At.current>3e5&&wt(!0)},3e4);return()=>{window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",x),clearInterval(k)}},[]);const In=o.useMemo(()=>{const m=s.filter(S=>S.status==="completed").length,x=s.filter(S=>S.status==="blocked"||S.status==="failed").length,k=t.filter(S=>{var W;return S.type==="decision_requested"&&((W=S.metadata)==null?void 0:W.status)==="pending"}).length;return{completed:m,blocked:x,decisions:k}},[s,t]),tn=o.useMemo(()=>{const m=new Map;for(const x of s)m.set(x.runId,x.title),m.set(x.id,x.title);return m},[s]),dn=o.useMemo(()=>{const m=new Map;for(const x of s)x.status&&(m.set(x.runId,x.status),m.set(x.id,x.status));return m},[s]),hn=o.useRef(new Map),Es=o.useMemo(()=>{var x;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??((x=k.blockerDiagnostics)==null?void 0:x.reason)??null};m.set(k.runId,S),m.set(k.id,S)}return Il(hn.current,m)?hn.current:(hn.current=m,m)},[s]),Yn=o.useRef(new Map),bs=o.useMemo(()=>{const m=new Map;for(const x of i){const k={status:x.status??null,blockingDecisions:Math.max(0,x.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(x.decisionCount??0)-(x.blockingDecisionCount??0)),updatedEpoch:gs(x.updatedAt??x.lastEventAt??x.startedAt??null)},S=[x.runId,x.sliceRunId].filter(W=>typeof W=="string"&&W.trim().length>0).map(W=>W.trim());for(const W of S){const Ne=m.get(W);(!Ne||k.updatedEpoch>=Ne.updatedEpoch)&&m.set(W,k)}}return Il(Yn.current,m)?Yn.current:(Yn.current=m,m)},[i]),ei=o.useMemo(()=>{const m=new Map;for(const x of i){const k={startedAt:x.startedAt??null,completedAt:x.completedAt??null},S=[x.runId,x.sliceRunId].filter(W=>typeof W=="string"&&W.trim().length>0);for(const W of S)m.set(W,k)}return m},[i]),Rs=o.useMemo(()=>{const m=new Map;for(const x of s){const k=qc(x.progress);k!==null&&(m.set(x.runId,k),m.set(x.id,k))}return m},[s]),Jt=o.useMemo(()=>{const m=new Map;for(const x of s)!x.agentId||!x.agentName||m.set(x.agentId,x.agentName);return m},[s]),En=o.useMemo(()=>{const m=new Map;for(const x of s){const k=x.workstreamId??null;m.set(x.runId,k),m.set(x.id,k)}return m},[s]),Jn=o.useMemo(()=>{const m=new Map;for(const x of i){const k=x.workstreamId??null,S=js(x.workstreamTitle,k);if(!S)continue;const W=[x.runId,x.sliceRunId].filter(Ne=>typeof Ne=="string"&&Ne.trim().length>0).map(Ne=>Ne.trim());for(const Ne of W)m.set(Ne,S)}return m},[i]),z=o.useMemo(()=>{const m=new Map;for(const x of r){const k=js(x.name,x.id);k&&m.set(x.id,k)}return m},[r]),ge=o.useMemo(()=>{const m=new Map;for(const x of r)for(const k of x.workstreams??[]){const S=js(k.name,k.id);S&&m.set(k.id,S)}for(const x of i){const k=x.workstreamId??null;if(!k||m.has(k))continue;const S=js(x.workstreamTitle,k);S&&m.set(k,S)}return m},[r,i]);o.useMemo(()=>{const m=[...s];return m.sort((x,k)=>{const S=gs(x.updatedAt??x.lastEventAt??x.startedAt??null);return gs(k.updatedAt??k.lastEventAt??k.startedAt??null)-S}),m},[s]);const xe=o.useMemo(()=>t.map(m=>{const x=ui(m),k=Oh(m),S=ut(m),W=x?Es.get(x)??null:null,Ne=x?bs.get(x)??null:null,Le=qh(m,S),tt=Ef({sessionStatus:Le?null:(W==null?void 0:W.status)??(x?dn.get(x)??null:null),sessionPhase:Le?null:(W==null?void 0:W.phase)??null,sessionState:Le?null:(W==null?void 0:W.state)??null,sliceStatus:Le?null:(Ne==null?void 0:Ne.status)??null,activityType:m.type,activityStatus:oe(S,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:oe(S,["stop_reason","stopReason"]),decisionRequired:m.decisionRequired??!1,blockingDecisionCount:Ys(S,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Ne==null?void 0:Ne.blockingDecisions)??0,nonBlockingDecisionCount:Ys(S,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Ne==null?void 0:Ne.nonBlockingDecisions)??0,blockerCount:Le?0:(W==null?void 0:W.blockerCount)??0,blockerReason:Le?null:(W==null?void 0:W.blockerReason)??null}),Ue=zh(k,tt),pt=[m.title,m.description,m.summary,m.agentName,Ah(S)].filter(Lt=>typeof Lt=="string"&&Lt.length>0).join(" ").toLowerCase(),Je=x?(tn.get(x)??x).toLowerCase():"",lt=S==null?void 0:S.scope,bt=lt==="milestone"||lt==="workstream"?lt:void 0;return{item:m,bucket:k,userState:Ue.state,userStateWhy:Ue.why,canonicalProjection:tt,runId:x,timestampEpoch:gs(m.timestamp),searchText:pt,runLabelSearch:Je,scopeGroupId:bt?x??null:null,scope:bt}}),[t,tn,Es,dn,bs]),Fe=o.useMemo(()=>{const m=[...xe];m.sort((S,W)=>{const Ne=W.timestampEpoch-S.timestampEpoch;return Ne!==0?Ne:W.item.id.localeCompare(S.item.id)});const x=S=>{const W=new Map,Ne=new Map,Le=new Map,tt=new Map;for(const Ue of S){kr(W,Ue.runId,Ue),kr(tt,Ue.userState,Ue);const pt=Hs(Ue.item)??(Ue.runId?En.get(Ue.runId)??null:null);kr(Ne,pt,Ue);const Je=Xs(Ue.item).agentName;kr(Le,Je,Ue)}return{all:S,byRunId:W,byWorkstreamId:Ne,byAgentName:Le,byUserState:tt}},k=[...m].reverse();return{newest:x(m),oldest:x(k)}},[xe,En]),_t=o.useMemo(()=>{let m=0;for(const x of xe)m=Math.max(m,x.timestampEpoch);return m<=0?!1:Date.now()-m<6e4},[xe]),Ct=o.useMemo(()=>new Set(l.filter(m=>m&&m.trim().length>0)),[l]),ot=Ct.size>0,nn=o.useMemo(()=>Ui.filter(m=>["live","24h","7d","all"].includes(m.id)),[]),Tt=o.useMemo(()=>{if(!ot)return null;for(const m of Ct){const x=s.find(k=>k.runId===m||k.id===m);if(x)return x}return null},[ot,Ct,s]),Zn=o.useMemo(()=>ot?Tt!=null&&Tt.runtimeProvider?{id:jh(Tt.runtimeProvider)}:_s(Tt==null?void 0:Tt.agentId,Tt==null?void 0:Tt.agentName,Tt==null?void 0:Tt.title,Tt==null?void 0:Tt.lastEventSummary,Tt==null?void 0:Tt.runtimeClient,c):_s(),[Tt,ot,c]),es=o.useMemo(()=>p?_s(p):_s(),[p]),{filtered:Ot,filteredTotal:pn,hiddenCount:ds,hiddenSyncCount:ts}=o.useMemo(()=>{const m=Be==="newest"?Fe.newest:Fe.oldest,x=[];ot&&x.push(Nh(m.byRunId,Ct)),d&&x.push(m.byWorkstreamId.get(d)??[]),p&&x.push(m.byAgentName.get(p)??[]),K==="completed"?x.push(m.byUserState.get("completed")??[]):K==="in_progress"?x.push(m.byUserState.get("in_progress")??[]):K==="needs_attention"&&x.push([...m.byUserState.get("needs_input")??[],...m.byUserState.get("issue")??[]]);const k=x.length>0?[...x].sort((bt,Lt)=>bt.length-Lt.length)[0]:m.all,S=[];let W=0,Ne=0,Le=0;const tt=new Set,Ue=ke.trim().toLowerCase();for(const bt of k){const Lt=bt.runId;if(ot&&(!Lt||!Ct.has(Lt)))continue;if(d){const Dn=Hs(bt.item),An=Lt?En.get(Lt)??null:null;if((Dn??An)!==d)continue}const bn=Xs(bt.item);if(p&&bn.agentName!==p){Le++;continue}if(!Te){const Dn=ut(bt.item),An=oe(Dn,["event","event_name","eventName"]);if(An&&xg.has(An))continue}const as=Ea(bt.item);if(as){if(tt.has(as)){Ne+=1;continue}if(tt.add(as),!Oe){Ne+=1;continue}}else if(!Oe&&Fi(bt.item)){Ne+=1;continue}K==="completed"&&bt.userState!=="completed"||K==="needs_attention"&&bt.userState!=="needs_input"&&bt.userState!=="issue"||K==="in_progress"&&bt.userState!=="in_progress"||Ue.length>0&&!`${bt.searchText} ${bt.runLabelSearch}`.includes(Ue)||(S.length<vl?S.push(bt):W+=1)}const pt=Math.min(Math.max(1,Math.min(bl,It)),S.length),Je=S.slice(0,pt),lt=S.length+W;return{filtered:Je,filteredTotal:lt,hiddenCount:Math.max(0,lt-Je.length),hiddenSyncCount:Ne,skippedByAgent:Le}},[K,p,Fe,ot,ke,It,d,Ct,En,Oe,Be]),Ls=o.useMemo(()=>{if(!p)return null;let m=0;for(const x of t)if(Xs(x).agentName===p){const S=gs(x.timestamp);S>m&&(m=S)}return m===0?null:qt(m)},[p,t]),Ds=o.useMemo(()=>{const m=new Map;for(const k of Ot){const S=Bh(k.item.timestamp),W=m.get(S);W?W.push(k):m.set(S,[k])}return Array.from(m.keys()).sort((k,S)=>{const W=Number(S)-Number(k);return Be==="newest"?W:-W}).map(k=>({key:k,label:Fh(k),items:m.get(k)??[]}))},[Ot,Be]),us=o.useMemo(()=>Ds.map(m=>{const x=new Map;for(const k of m.items){const S=Ki(k.item).title.trim().toLowerCase(),W=Ea(k.item),Ne=ut(k.item),Le=oe(Ne,["event","event_name","eventName"]),tt=(Le==null?void 0:Le.startsWith("autopilot_"))||(Le==null?void 0:Le.startsWith("auto_continue_")),Ue=typeof Le=="string"&&/(transition|started|stopped|completed|blocked|paused|resumed|failed|decision|dispatch)/i.test(Le),pt=Hs(k.item),Je=W?`${k.item.type}::sync::${W}`:tt&&pt&&!Ue?`autopilot::${pt}::${Math.floor(k.timestampEpoch/3e5)}`:Ue?`autopilot-lifecycle::${k.item.id}`:`${k.item.type}::${S}`,lt=x.get(Je);lt?(lt.count+=1,lt.firstTimestamp=Math.min(lt.firstTimestamp,k.timestampEpoch),lt.allItems.push(k),k.timestampEpoch>lt.representative.timestampEpoch&&(lt.representative=k)):x.set(Je,{key:Je,representative:k,count:1,firstTimestamp:k.timestampEpoch,allItems:[k]})}return{...m,clusters:Array.from(x.values())}}),[Ds]),Nn=o.useCallback(m=>{Y(x=>{const k=new Set(x);return k.has(m)?k.delete(m):k.add(m),k}),ze(x=>{if(Object.prototype.hasOwnProperty.call(x,m)){const k={...x};return delete k[m],k}return{...x,[m]:Li}})},[]),Xi=o.useCallback((m,x)=>{ze(k=>{const S=k[m]??Li,W=Math.min(x,S+Li);return W===S?k:{...k,[m]:W}})},[]),ms=o.useCallback(()=>{!w||!v||!Rt||!Dt||Dt.getTime()<Rt.getTime()||(w({startIso:Rt.toISOString(),endIso:Dt.toISOString()}),v("custom"),ht(!1))},[Dt,Rt,w,v]),na=o.useCallback(()=>{$t(null),Yt(null),w==null||w({startIso:null,endIso:null}),g==="custom"&&(v==null||v("live"))},[w,v,g]),zt=o.useMemo(()=>Math.min(bl,Math.min(vl,pn)),[pn]);o.useEffect(()=>{We(_a),Y(new Set),ze({})},[K,p,ot,ke,d,Oe,Be,g]),o.useEffect(()=>{if(!Me)return;const m=k=>{var W;const S=k.target;S instanceof Node&&((W=Pt.current)!=null&&W.contains(S)||Se(!1))},x=k=>{k.key==="Escape"&&Se(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[Me]),o.useEffect(()=>{if(!J)return;const m=k=>{var W;const S=k.target;S instanceof Node&&((W=Kt.current)!=null&&W.contains(S)||ht(!1))},x=k=>{k.key==="Escape"&&ht(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[J]);const qn=o.useRef(M);qn.current=M;const ti=o.useRef(y);ti.current=y;const xi=o.useRef(I);xi.current=I;const[ns,sa]=o.useState(!1),vs=o.useRef(null),un=o.useRef(g),Qi=o.useRef(Date.now()),Ps=o.useRef(!1);o.useEffect(()=>{un.current!==g&&(un.current=g,vs.current=null,Qi.current=Date.now(),Ps.current=!1)},[g]),o.useEffect(()=>{const m=at.current,x=st.current;if(!m||!x)return;const k=new IntersectionObserver(W=>{const Ne=W.some(Le=>Le.isIntersecting);sa(Ne)},{root:m,rootMargin:"0px 0px 600px 0px"});k.observe(x);const S=()=>{Ps.current=!0};return m.addEventListener("scroll",S,{passive:!0}),()=>{k.disconnect(),m.removeEventListener("scroll",S)}},[]),o.useEffect(()=>{var m;if(ns){if(Ot.length<zt){We(x=>Math.min(zt,Math.max(x,_a)+kh));return}if(ti.current&&!xi.current){(m=qn.current)==null||m.call(qn);return}}},[Ot.length,zt,ns]),o.useEffect(()=>{if(!ns||y||I||!v)return;const m=at.current,x=m?m.scrollHeight<=m.clientHeight+4:!1;if(!Ps.current&&!x||Date.now()-Qi.current<3e3)return;const S=kl(g);S&&vs.current!==S&&(vs.current=S,v(S))},[Ot.length,y,I,v,ns,g]);const gn=o.useMemo(()=>Q?Ot.findIndex(m=>m.item.id===Q):-1,[Q,Ot]),R=gn>=0?Ot[gn]:null,ss=o.useMemo(()=>{var x;const m=new Map;for(const k of a){const S=(x=k==null?void 0:k.sliceRunId)==null?void 0:x.trim();!S||m.has(S)||m.set(S,k)}return m},[a]),xn=o.useMemo(()=>{if(!R)return null;const m=R.runId??ui(R.item);return m?ss.get(m)??null:null},[R,ss]),yn=o.useMemo(()=>Dc((R==null?void 0:R.item)??null),[R]),is=o.useMemo(()=>Ar((R==null?void 0:R.item)??null),[R]),Bn=o.useMemo(()=>Lc((R==null?void 0:R.item)??null),[R]),rs=o.useMemo(()=>Bn?null:ag((R==null?void 0:R.item)??null,t),[Bn,R,t]),it=o.useMemo(()=>R?Sl(R.item):null,[R]),Rn=o.useMemo(()=>it?it.executor??it.requester:null,[it]),se=Bn??(rs==null?void 0:rs.detail)??null,Yi=o.useMemo(()=>{var m,x;return Ma((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)??((x=it==null?void 0:it.requester)==null?void 0:x.id)??null,Jt)},[se,it,Jt]),ws=o.useMemo(()=>Th(Yi),[Yi]),Vt=o.useMemo(()=>{var x,k;const m=Ma((se==null?void 0:se.agentName)??((x=it==null?void 0:it.executor)==null?void 0:x.name)??null,(se==null?void 0:se.agentId)??((k=it==null?void 0:it.executor)==null?void 0:k.id)??null,Jt);return m==="—"?(it==null?void 0:it.primaryLabel)??"Codex":m},[se,it,Jt]),ps=o.useMemo(()=>R!=null&&R.runId?Rs.get(R.runId)??null:null,[R,Rs]),Mt=o.useMemo(()=>cg(se,ps),[se,ps]),B=o.useMemo(()=>{const m=se;if(!m)return null;const x=m.initiativeId??(R==null?void 0:R.item.initiativeId)??null,k=x?r.find(Lt=>Lt.id===x)??null:null,S=m.initiativeTitle??(k==null?void 0:k.name)??null,W=m.initiativeStatus??(k==null?void 0:k.status)??null,Ne=(k==null?void 0:k.workstreams)??[],Le=Ne.length>0?Ne.length:null,tt=Le!==null?Ne.filter(Lt=>Gi(Lt.status)).length:null,Ue=Le&&tt!==null?Math.round(tt/Le*100):null,pt=m.workstreamId??null,Je=pt&&Ne.length>0?Ne.find(Lt=>Lt.id===pt)??null:null,lt=m.workstreamTitle??(Je==null?void 0:Je.name)??(pt?ge.get(pt)??null:null),bt=m.workstreamStatus??(Je==null?void 0:Je.status)??null;return{initiativeId:x,initiativeTitle:S,initiativeStatus:W,totalInitiativeWorkstreams:Le,doneInitiativeWorkstreams:tt,initiativeWorkstreamPct:Ue,workstreamId:pt,workstreamTitle:lt,workstreamStatus:bt,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,R,r,ge]),Et=o.useMemo(()=>R?dg(R.item,se,B?{decisions:B.decisions,blockingDecisions:B.blockingDecisions,nonBlockingDecisions:B.nonBlockingDecisions,stopReason:B.stopReason,parsedStatus:B.parsedStatus}:null,R.canonicalProjection??null):null,[se,R,B]),Fn=o.useMemo(()=>{if(!R)return new Set;if(Te)return new Set(["header","artifact","outcome","structured_outcomes","action_needed","session","scope","summary","evidence"]);const m=oe(ut(R.item),["event","event_name","eventName"])??"";return gg(m,!!yn||!!Ar(R.item),!!Et,Gh(R.item))},[R,yn,Et,Te]),Ji=o.useMemo(()=>{if(!B)return[];const m=[];Et&&m.push({label:"Status",value:Et.label}),B.scopedTaskCount>0&&m.push({label:"Tasks",value:B.scopedTaskCount}),B.scopedMilestoneCount>0&&m.push({label:"Milestones",value:B.scopedMilestoneCount});const x=B.artifacts??0;x>0&&m.push({label:"Artifacts",value:x});const k=B.decisions??0;k>0&&m.push({label:"Decisions",value:k}),B.blockingDecisions&&B.blockingDecisions>0&&m.push({label:"Blocking",value:B.blockingDecisions,tone:"critical"}),B.stopReason&&m.push({label:"Stop reason",value:ji(B.stopReason)??rt(B.stopReason)});const S=fd(B.tokensUsed,B.tokenBudget);return S&&m.push({label:"Token usage",value:S}),m},[B,Et]),on=o.useMemo(()=>{const m=new Set;for(const x of ig((R==null?void 0:R.item)??null))m.add(x);for(const x of(se==null?void 0:se.decisionIds)??[])m.add(x);for(const x of(se==null?void 0:se.blockingDecisionIds)??[])m.add(x);for(const x of(se==null?void 0:se.nonBlockingDecisionIds)??[])m.add(x);return Array.from(m)},[se,R]),Zi=o.useMemo(()=>j?on.length>0||(R==null?void 0:R.item.decisionRequired)===!0||((B==null?void 0:B.blockingDecisions)??0)>0?!0:(Et==null?void 0:Et.label)==="Needs decision":!1,[on,R,B,Et,j]),sn=o.useMemo(()=>{if(!R)return null;const m=ui(R.item);return m?i.find(x=>x.runId===m||x.sliceRunId===m)??null:null},[R,i]),er=o.useMemo(()=>(sn==null?void 0:sn.decisionOptions)??[],[sn]),$s=o.useMemo(()=>(sn==null?void 0:sn.pendingDecisions)??[],[sn]),ia=o.useMemo(()=>(sn==null?void 0:sn.blockers)??[],[sn]),Os=o.useMemo(()=>Mt?Mt.tone==="positive"?L.lime:Mt.tone==="warning"?L.amber:Mt.tone==="critical"?L.red:L.teal:L.teal,[Mt]),yi=(Mt==null?void 0:Mt.terminalStop)===!0,yt=o.useMemo(()=>Wh(ut((R==null?void 0:R.item)??null)),[R]),tr=o.useMemo(()=>ut((R==null?void 0:R.item)??null),[R]),dt=o.useMemo(()=>Zh((R==null?void 0:R.item)??null,se),[se,R]),bi=o.useMemo(()=>{if(!(dt!=null&&dt.retryAt))return null;const m=new Date(dt.retryAt);if(!Number.isFinite(m.getTime()))return null;const x=m.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),k=qt(dt.retryAt);return k?`${x} (${k})`:x},[dt]),nr=o.useMemo(()=>R?Xs(R.item):{agentId:null,agentName:null},[R]),vi=o.useMemo(()=>El(Gt(R==null?void 0:R.item.metadata)??void 0),[R]),sr=o.useMemo(()=>{var k;if(!R)return[];const m=ui(R.item);if(m){const S=i.find(W=>W.runId===m||W.sliceRunId===m);if((k=S==null?void 0:S.scopeProgress)!=null&&k.milestones)return S.scopeProgress.milestones.map(W=>({id:W.id,title:W.title,tasks:[],totalTasks:W.total,doneTasks:W.done}))}const x=oe(ut(R.item),["workstream_id","workstreamId"]);if(x&&de){const S=de.find(W=>W.workstreamId===x);if(S!=null&&S.milestoneBreakdown)return S.milestoneBreakdown}return[]},[R,i,de]);o.useMemo(()=>El(tr),[tr]);const ir=o.useMemo(()=>{const m=$c((R==null?void 0:R.item)??null);return m.length>0?m:rg((R==null?void 0:R.item)??null,t,new Set)},[R,t]),Ln=o.useMemo(()=>ir.filter((m,x,k)=>k.findIndex(S=>S.path===m.path)===x),[ir]),rr=o.useMemo(()=>Ln.slice(0,4),[Ln]),qs=o.useMemo(()=>Ln.slice(4),[Ln]),Bs=o.useMemo(()=>{if(Ln.length===0)return null;const m=Ln[0];return m?qr(m.path):null},[Ln]),Fs=o.useMemo(()=>{var S;const m=Ht(V);if(m)return m;const x=Rl((R==null?void 0:R.item)??null);if(x)return x;const k=Ht(R==null?void 0:R.item.summary)??Ht(R==null?void 0:R.item.description);if(k)return k;if(R){const W=R.item,Ne=ut(W),Le=oe(Ne,["agent_name","agentName"])??W.agentName??"OrgX",tt=oe(Ne,["task_title","taskTitle","workstream_title","workstreamTitle"]),Ue=((S=W.type)==null?void 0:S.replace(/_/g," "))??"activity";return tt?`${Le} worked on ${tt}`:`${Le} recorded a ${Ue}`}return null},[V,R]),wi=o.useMemo(()=>R?Fi(R.item):!1,[R]),mn=o.useMemo(()=>{if(!se||!R)return null;const m=se.initiativeId??R.item.initiativeId??null,x=se.workstreamId??Hs(R.item);if(!m||!x)return null;const k=On((B==null?void 0:B.parsedStatus)??se.parsedStatus),S=On((B==null?void 0:B.stopReason)??se.stopReason),W=Math.max(0,(B==null?void 0:B.blockingDecisions)??se.blockingDecisions??(R.item.decisionRequired?1:0)),Ne=Math.max(0,(B==null?void 0:B.nonBlockingDecisions)??se.nonBlockingDecisions??0),Le=k==="blocked"||k==="error"||k==="failed"||S==="blocked"||S==="error"||R.item.type==="blocker_created",tt=!Le&&W===0&&Ne>0&&(k==="needs_decision"||k==="completed"||S==="completed");return!Le&&!tt?null:{initiativeId:m,workstreamId:x,runId:R.runId??null,event:se.event,requestedByAgentId:se.requesterAgentId??R.item.requesterAgentId??null,requestedByAgentName:se.requesterAgentName??R.item.requesterAgentName??null,actionLabel:Le?"Auto-fix in 10s":"Auto-continue in 10s",helperText:Le?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:Le}},[se,R,B]),jn=o.useCallback(()=>{q(null)},[]),ar=o.useCallback(async(m,x)=>{if(x){nt(null),he(m);try{await x()}catch(k){nt(k instanceof Error?k.message:"Action failed")}finally{he(k=>k===m?null:k)}}},[]),ki=o.useCallback(async()=>{var m;if(!(!mn||Ke)){Xe(!0),xt(null);try{const x=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:mn.initiativeId,workstreamId:mn.workstreamId,runId:mn.runId,event:mn.event,requestedByAgentId:mn.requestedByAgentId,requestedByAgentName:mn.requestedByAgentName,graceMs:1e4})}),k=await x.json().catch(()=>null);if(!x.ok||(k==null?void 0:k.ok)!==!0)throw new Error((k==null?void 0:k.error)||`Request failed (${x.status})`);const S=(m=k==null?void 0:k.scheduled)!=null&&m.dueAt?new Date(k.scheduled.dueAt):null,W=S&&Number.isFinite(S.getTime())?S.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;xt(W?`Scheduled. Auto action starts by ${W} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(x){const k=x instanceof Error?x.message:"Failed to schedule auto-fix";xt(en(k)||k)}finally{Xe(!1)}}},[mn,Ke]);o.useEffect(()=>{if(!te)return;const m=window.setTimeout(()=>le(null),2e3);return()=>window.clearTimeout(m)},[te]),o.useEffect(()=>{nt(null)},[K,ke,g]),o.useEffect(()=>{if(!Z){Ft.current=null;return}const m=Z.trim();!m||Ft.current===m||!t.some(k=>k.id===m)||(Ft.current=m,ye("all"),T(""),fe(1),q(m),E==null||E(m))},[t,E,Z]);const f=o.useCallback(async(m,x)=>{if(x)try{await navigator.clipboard.writeText(x),le(`${m} copied`)}catch{le("Copy failed")}},[]);o.useEffect(()=>{ie("structured"),Ve(!1),Xe(!1),xt(null)},[Q]),o.useEffect(()=>{Re(null),ct("feed"),mt(null),jt(null);const m=bg((R==null?void 0:R.item)??null);if(!m||Kn())return;const x=new URLSearchParams({turnId:m.turnId});m.sessionKey&&x.set("sessionKey",m.sessionKey),m.runId&&x.set("run",m.runId);const k=new AbortController;return fetch(`/orgx/api/live/activity/detail?${x.toString()}`,{method:"GET",headers:Ut({workspaceId:re}),signal:k.signal}).then(async S=>S.ok?await S.json():(S.status===404&&ct("missing"),null)).then(S=>{var Le;const W=((Le=S==null?void 0:S.detail)==null?void 0:Le.summary)??null;typeof W=="string"&&W.trim().length>0?(Re(W),ct("local")):ct("missing");const Ne=S==null?void 0:S.headline;typeof Ne=="string"&&Ne.trim().length>0&&(mt(Ne.trim()),jt((S==null?void 0:S.headlineSource)??null))}).catch(S=>{S instanceof DOMException&&S.name==="AbortError"||ct("missing")}),()=>k.abort()},[R,re]);const N=o.useCallback(m=>{var S;if(Ot.length===0)return;const k=((gn>=0?gn:0)+m+Ot.length)%Ot.length;fe(m),q(((S=Ot[k])==null?void 0:S.item.id)??null)},[gn,Ot]);o.useEffect(()=>{Q&&(gn>=0||q(null))},[gn,Q]),o.useEffect(()=>{if(!Q)return;const m=x=>{x.key==="ArrowRight"||x.key.toLowerCase()==="l"?(x.preventDefault(),N(1)):(x.key==="ArrowLeft"||x.key.toLowerCase()==="h")&&(x.preventDefault(),N(-1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[Q,N]);const $=Ct.size===1,_=$?[...Ct][0]:null,Ie=_?s.find(m=>m.runId===_||m.id===_)??null:null,je=o.useMemo(()=>{if(!$)return[];const m=[],x=new Set;for(const k of xe){if(!k.runId||!Ct.has(k.runId))continue;const S=Ea(k.item);if(S){if(x.has(S)||(x.add(S),!Oe))continue}else if(!Oe&&Fi(k.item))continue;m.push(k.item)}return m},[$,xe,Ct,Oe]),Ge=!C&&Ot.length<=160,Pe=(m,x,k)=>{const S=m.item,W=k??S.id,Ne=Xs(S),Le=Sl(S),tt=Lh(S,Le),Ue=Le.executor??Le.requester,pt=Ma(vn((Ue==null?void 0:Ue.name)??Le.primaryLabel??S.agentName??Ne.agentName??null),vn((Ue==null?void 0:Ue.id)??S.agentId??Ne.agentId??null),Jt)||"OrgX";let Je=Ph(tt)||pt;if(tt==="agent"&&pt){const uo=Hi(pt);uo&&(Je=`${pt} (${uo})`)}const lt=Ta(m.userState),bt=tt==="agent"?Za(pt)||lt:Dh[tt]||lt,Lt=Be==="newest"&&x<2,bn=m.runId,as=Rl(S),Dn=Vh(S),{title:An}=Ki(S),Ze=as??Dn??Ht(S.summary),ln=Ht(S.description),zn=Dl(S,Ze??ln??null),ra=ut(S),oo=Cr([{value:oe(ra,["initiative_title","initiativeTitle"]),idHint:S.initiativeId},{value:S.initiativeId?z.get(S.initiativeId)??null:null,idHint:S.initiativeId}]),ks=Hs(S)??(bn?En.get(bn)??null:null),lo=Cr([{value:oe(ra,["workstream_title","workstreamTitle"]),idHint:ks},{value:ks?ge.get(ks)??null:null,idHint:ks},{value:bn?Jn.get(bn)??null:null,idHint:ks}]),zc=[oo,lo].filter(Boolean).join(" > "),Uc=js(oe(ra,["event","event_name","eventName"]),null),Ii=ks?U.get(ks):void 0,Wc=(we==null?void 0:we.state)==="running"&&ks===(we==null?void 0:we.activeWorkstreamId),Hc=Ii?` — #${Ii.rank} in queue`:"",Kc=(zc||oo||lo||Uc||Bi(S.type))+(Wc?Hc:""),Vc=Ca(m.userState),Gc=new Date(S.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),Xc=qt(S.timestamp),Qc=m.bucket==="artifact"?Hh(S):null,co=Kh(S);return n.jsx(Xf,{renderKey:W,displayTitle:An,headline:zn,contextLabel:Kc,detailText:(Ze??ln)!==zn?Ze??ln:null,displayAgentName:Je,railColor:bt,statusColor:lt,userStateLabel:Vc,userStateWhy:m.userStateWhy,relativeTime:Xc,timeLabel:Gc,isRecent:Lt,enableMotion:Ge,onOpen:()=>{fe(1),q(S.id)},ariaLabel:`Open activity details for ${An||Bi(S.type)}`,artifactSnippet:Qc,evidenceChips:co.length>0?co:void 0,actorCategory:tt,queuePosition:Ii?{rank:Ii.rank,state:Ii.state}:null},W)};return n.jsx(uh,{sessions:s,initiatives:r??[],workspaceId:re??null,query:ke,statusFilter:K,sortOrder:Be,timeFilterId:g,customTimeRange:h,snapshot:ne,onRequestRefresh:G,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[$&&je.length>0?n.jsx(Hf,{items:je,session:Ie,agentName:((_e=je[0])==null?void 0:_e.agentName)??null,onBack:F,onOpenItem:m=>{fe(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:pn}),ds>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:["+",ds," hidden"]}),ts>0&&!Oe&&n.jsxs("button",{type:"button",onClick:()=>me(!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:[ts," sync hidden"]}),Oe&&n.jsx("button",{type:"button",onClick:()=>me(!1),className:"hidden flex-shrink-0 rounded-full border border-lime/30 bg-lime/[0.10] px-2 py-0.5 text-micro text-lime 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",_t&&"pulse-soft"),style:{backgroundColor:L.lime},"aria-label":"Live",title:_t?"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:ke,onChange:m=>T(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-lime/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:Kt,children:[n.jsxs("button",{type:"button",onClick:()=>{ht(m=>!m),Se(!1)},"aria-haspopup":"menu","aria-expanded":J,className:ue("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",J?"border-lime/30 bg-lime/[0.10] text-lime":"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:Ms}),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",J&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(Nt,{children:J&&n.jsx(ce.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:Ui.filter(m=>m.id!=="custom").map(m=>{const x=g===m.id;return n.jsx("button",{type:"button",onClick:()=>{v==null||v(m.id),ht(!1)},className:ue("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",x?"border-lime/30 bg-lime/[0.12] text-lime":"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"}),kn?n.jsx("input",{type:"datetime-local",step:300,value:Sa(Rt),onChange:m=>$t(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:Rt,onChange:m=>$t(m instanceof Date?m:null),selectsStart:!0,startDate:Rt,endDate:Dt,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"}),kn?n.jsx("input",{type:"datetime-local",step:300,min:Sa(Rt),value:Sa(Dt),onChange:m=>Yt(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:Dt,onChange:m=>Yt(m instanceof Date?m:null),selectsEnd:!0,minDate:Rt??void 0,startDate:Rt,endDate:Dt,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:Qn?`${jr(Rt)} - ${jr(Dt)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:na,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:ms,disabled:!Qn,className:"rounded-full border border-lime/30 bg-lime/[0.14] px-2.5 py-1 text-micro font-semibold text-lime 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:[(ot||d||p)&&n.jsxs(n.Fragment,{children:[ot&&n.jsxs("button",{onClick:F,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[Nl(Zn.id)?n.jsx(pi,{provider:Zn.id,size:"xs"}):n.jsx(Zt,{name:(Tt==null?void 0:Tt.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:b,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:A,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(pi,{provider:es.id,size:"xs"}):n.jsx(Zt,{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(Ir).map(m=>{const x=K===m;return n.jsx("button",{type:"button",onClick:()=>ye(m),"aria-pressed":x,className:ue("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",x?"border border-lime/25 bg-lime/[0.10] text-lime":"border border-transparent text-secondary hover:bg-white/[0.08] hover:text-bright"),children:Ir[m]},m)})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:Pt,children:[n.jsxs("button",{type:"button",onClick:()=>{Se(m=>!m),ht(!1)},"aria-haspopup":"menu","aria-expanded":Me,"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",Me?"border-lime/30 bg-lime/[0.10] text-lime":"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",Me&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(Nt,{children:Me&&n.jsx(ce.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:()=>{ft(m.id),Se(!1)},className:ue("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",Be===m.id?"border-lime/30 bg-lime/[0.12] text-lime":"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(Ir).map(m=>{const x=K===m;return n.jsx("button",{type:"button",onClick:()=>{ye(m),Se(!1)},className:ue("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",x?"border-lime/30 bg-lime/[0.12] text-lime":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:Ir[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:()=>{me(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-lime":"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:at,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[Ot.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(ea,{icon:"activity",headline:ae?"Syncing activity feed...":ot?"No activity yet for this session":d?"No activity yet for this workstream":p?`No recent activity from ${p}`:K!=="all"?`No matches for this filter. ${pn>0?`${pn} events in other categories.`:""}`:de&&de.length>0?`Waiting for autopilot to start. Queue has ${de.length} item${de.length===1?"":"s"} ready.`:"No activity yet",description:ae?"Live updates usually appear within a few seconds after dispatch.":K!=="all"?'Try selecting "All" to see every event.':p?`Try widening the time window or select a different agent.${Ls?` Last active: ${Ls}.`:""}`:`Try widening the time window (${Ms}), 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:nn.map(m=>{const x=g===m.id;return n.jsx("button",{type:"button",onClick:()=>v==null?void 0:v(m.id),className:ue("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",x?"border-lime/30 bg-lime/[0.12] text-lime":"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:()=>{A==null||A(),v==null||v("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"}),(ot||d||K!=="all")&&n.jsx("button",{type:"button",onClick:()=>{ot&&F(),d&&(b==null||b()),p&&(A==null||A()),K!=="all"&&ye("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"}),D&&n.jsx("button",{type:"button",onClick:()=>void ar("play",D),disabled:X!==null,className:"rounded-full border border-lime/28 bg-lime/12 px-3 py-1.5 text-caption font-semibold text-lime transition hover:bg-lime/18 disabled:opacity-45",children:X==="play"?"Starting...":"Start next session"}),!D&&pe&&n.jsx("button",{type:"button",onClick:pe,className:"rounded-full border border-lime/28 bg-lime/12 px-3 py-1.5 text-caption font-semibold text-lime transition hover:bg-lime/18",children:"Browse initiatives"})]}),qe&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:qe})]})}),n.jsx(Kf,{completedCount:In.completed,decisionsCount:In.decisions,blockerCount:In.blocked,visible:Qt,onDismiss:()=>{wt(!1),At.current=Date.now()}}),Ot.length>0&&n.jsxs("div",{className:"space-y-4",children:[us.map(m=>{const x=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}),Ge?n.jsx(Nt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:x.map((k,S)=>{const W=be.has(k.key),Ne=k.allItems.slice(1),Le=Ne.length,tt=Math.min(Le,Ee[k.key]??Li),Ue=Ne.slice(0,tt);if(k.count===1)return Pe(k.representative,S);if(k.key.startsWith("autopilot::")&&k.count>=3){const Je=Ml(k);return n.jsx(yl,{workstreamTitle:Je.workstreamTitle,items:Je.items,firstTimestamp:k.firstTimestamp,lastTimestamp:k.representative.timestampEpoch,onExpandItem:lt=>{const bt=k.allItems[lt];bt&&q(bt.item.id)}},k.key)}const pt=`cluster:${k.key}`;return n.jsxs("div",{children:[Pe(k.representative,S,pt),n.jsxs("button",{type:"button",onClick:Je=>{Je.stopPropagation(),Nn(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:W?"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",W?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),W&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[Ue.map((Je,lt)=>Pe(Je,S+lt+1)),tt<Le&&n.jsxs("button",{type:"button",onClick:Je=>{Je.stopPropagation(),Xi(k.key,Le)},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 (",Le-tt," remaining)"]})]})]},k.key)})})}):n.jsx("div",{className:"space-y-2",children:x.map((k,S)=>{const W=be.has(k.key),Ne=k.allItems.slice(1),Le=Ne.length,tt=Math.min(Le,Ee[k.key]??Li),Ue=Ne.slice(0,tt);if(k.count===1)return Pe(k.representative,S);if(k.key.startsWith("autopilot::")&&k.count>=3){const Je=Ml(k);return n.jsx(yl,{workstreamTitle:Je.workstreamTitle,items:Je.items,firstTimestamp:k.firstTimestamp,lastTimestamp:k.representative.timestampEpoch,onExpandItem:lt=>{const bt=k.allItems[lt];bt&&q(bt.item.id)}},k.key)}const pt=`cluster:${k.key}`;return n.jsxs("div",{children:[Pe(k.representative,S,pt),n.jsxs("button",{type:"button",onClick:Je=>{Je.stopPropagation(),Nn(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:W?"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",W?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),W&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[Ue.map((Je,lt)=>Pe(Je,S+lt+1)),tt<Le&&n.jsxs("button",{type:"button",onClick:Je=>{Je.stopPropagation(),Xi(k.key,Le)},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 (",Le-tt," remaining)"]})]})]},k.key)})})]},m.key)}),n.jsx("div",{ref:st,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:ue("flex items-center justify-center py-6 transition-[opacity,transform] duration-500 ease-out",I?"opacity-100 translate-y-0":y?"opacity-0 translate-y-2":"opacity-0 translate-y-2 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-lime/70 animate-[pulse_1.4s_ease-in-out_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-lime/50 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-lime/30 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]"})]})})}),!y&&!I&&Ot.length>0&&!kl(g)&&n.jsx("p",{className:"py-6 text-center text-caption text-muted",children:ds>0?`${Ot.length} of ${pn} events`:"Beginning of activity history"})]})]})]}),Te?n.jsx(wh,{}):null,n.jsx(Qf,{open:R!==null,onClose:jn,children:R&&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:Ta(R.userState),boxShadow:`0 0 12px ${Ta(R.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Ca(R.userState)," · ",gn+1,"/",Ot.length," sessions"]}),te&&n.jsx(Pn,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:te})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[R.runId&&H&&n.jsx("button",{type:"button",onClick:()=>{H(R.runId),jn()},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:()=>N(-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:()=>N(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:()=>Ve(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"})]})}),$e&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>Ve(!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:[R.runId&&n.jsx("button",{type:"button",onClick:()=>{f("Run id",R.runId??""),Ve(!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"}),nr.agentId&&n.jsx("button",{type:"button",onClick:()=>{f("Agent id",nr.agentId??""),Ve(!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:()=>{f("Event id",R.item.id),Ve(!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:jn,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(Nt,{mode:"wait",custom:Ye,children:n.jsx(ce.section,{custom:Ye,initial:{opacity:0,x:Ye*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:Ye*-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:gt||Dl(R.item,V)||rt(R.item.title||Bi(R.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(R.item.timestamp).toLocaleString()," · ",qt(R.item.timestamp),vt==="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=ut(R.item),x=(se==null?void 0:se.workstreamId)??Hs(R.item)??(R.runId?En.get(R.runId)??null:null),k=Cr([{value:(se==null?void 0:se.workstreamTitle)??null,idHint:x},{value:oe(m,["workstream_title","workstreamTitle"]),idHint:x},{value:x?ge.get(x)??null:null,idHint:x},{value:R.runId?Jn.get(R.runId)??null:null,idHint:x}]),W=[Cr([{value:(se==null?void 0:se.initiativeTitle)??null,idHint:R.item.initiativeId},{value:oe(m,["initiative_title","initiativeTitle"]),idHint:R.item.initiativeId},{value:R.item.initiativeId?z.get(R.item.initiativeId)??null:null,idHint:R.item.initiativeId}]),k].filter(Boolean).join(" > ");return W?n.jsx(Pn,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:W})}):null})(),n.jsx(Pn,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:Ca(R.userState)}),n.jsxs(Pn,{tone:"muted",children:[n.jsx(Zt,{name:(Rn==null?void 0:Rn.label)??(it==null?void 0:it.primaryLabel)??"OrgX",hint:Rn?Cl(Rn):(it==null?void 0:it.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(Rn==null?void 0:Rn.label)??(it==null?void 0:it.primaryLabel)??"OrgX"})]}),wi&&n.jsx(Pn,{tone:"lime",children:"Sync replay"})]})]}),Fn.has("artifact")&&R&&Ar(R.item)&&!yn&&n.jsxs("button",{type:"button",onClick:()=>{const m=Ar(R.item);m&&O(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:L.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:L.cyan},children:"View registered artifact"})]}),n.jsx(Zf,{item:R.item}),Fn.has("artifact")&&yn&&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:yn.source==="metadata"?"Artifact":rt(yn.source)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[Te&&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:()=>ie("structured"),"aria-pressed":Qe==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${Qe==="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:()=>ie("json"),"aria-pressed":Qe==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${Qe==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),is&&n.jsx("button",{type:"button",onClick:()=>O(is),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:Qe==="structured"?Bc(yn.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(yn.value,null,2)})})})]}),Fn.has("outcome")&&Et&&n.jsxs("div",{className:ue("rounded-xl border px-3.5 py-3",Et.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",Et.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",Et.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",Et.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:Et.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:Et.summary}),Et.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:Et.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[R.runId&&H&&n.jsx("button",{type:"button",onClick:()=>{H(R.runId),jn()},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"}),Zi&&n.jsx("button",{type:"button",onClick:()=>{j==null||j(on[0]??null),jn()},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:on.length>0?"Resolve decision":"Resolve decisions"}),is&&!yn&&n.jsx("button",{type:"button",onClick:()=>O(is),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"}),Bs&&n.jsx("a",{href:Bs,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"}),mn&&n.jsx("button",{type:"button",onClick:()=>void ki(),disabled:Ke,className:ue("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",mn.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-lime hover:bg-lime/[0.18]"),children:Ke?"Scheduling...":mn.actionLabel})]}),mn&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:He??mn.helperText})]}),(()=>{var as,Dn,An;if(!Fn.has("structured_outcomes"))return null;const m=ut(R.item),x=Gt(m==null?void 0:m.outcomes),k=ta(m),S=wn((m==null?void 0:m.status_updates_applied)??(m==null?void 0:m.statusUpdatesApplied)??((as=Gt(m==null?void 0:m.result))==null?void 0:as.status_updates_applied)??((Dn=Gt(m==null?void 0:m.result))==null?void 0:Dn.statusUpdatesApplied)),W=((An=oe(m,["event","event_name","eventName"]))==null?void 0:An.toLowerCase())??"",Ne=(m==null?void 0:m.status_updates_buffered)??(m==null?void 0:m.statusUpdatesBuffered),Le=W.includes("status_updates_buffered")||Ne===!0||typeof Ne=="number"&&Ne>0||typeof Ne=="string"&&["true","1","yes"].includes(Ne.trim().toLowerCase()),tt=oe(x,["pr_url","prUrl","url"]),Ue=x==null?void 0:x.pr_number,pt=oe(x,["commit_sha","commitSha"]),Je=oe(x,["commit_url","commitUrl"]),lt=Gt(x==null?void 0:x.tests),Lt=(k.length>0||(S??0)>0||Le)&&(!yn||W.includes("status_updates"));return tt||pt||lt||Lt?n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-muted",children:Lt?"Updates & outcomes":"Outcomes"}),Lt&&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:Le?"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",Le?" · queued for sync":""]})]})]}),k.length>0&&n.jsx("ul",{className:"mt-2 space-y-1.5 pl-5",children:k.slice(0,6).map((Ze,ln)=>n.jsxs("li",{className:"text-caption text-secondary",children:[n.jsxs("span",{className:"text-primary",children:[Ze.scope,": ",Ze.label]}),Ze.status?` → ${Ze.status}`:"",Ze.reason?` · ${Ze.reason}`:""]},`${Ze.scope}-${Ze.label}-${ln}`))})]}),tt&&n.jsxs("a",{href:tt,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:Ue?`#${Ue}`:"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"})})]}),pt&&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:pt.slice(0,7)})]}),Je&&n.jsx("a",{href:Je,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary hover:text-primary transition-colors",children:"View"})]}),lt&&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:(lt.failed??0)>0?L.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:(lt.failed??0)>0?L.red:"rgba(103,232,249,0.7)"},children:"Tests"}),n.jsxs("p",{className:"mt-0.5 text-body text-primary",children:[lt.passed??0," passed",(lt.failed??0)>0&&n.jsxs("span",{className:"text-red-300",children:[" · ",lt.failed," failed"]}),(lt.skipped??0)>0&&n.jsxs("span",{className:"text-muted",children:[" · ",lt.skipped," skipped"]})]})]})]})]}):null})(),dt&&!Te&&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."}),dt.retryInMs!==null&&n.jsxs("p",{className:"mt-1 text-micro text-muted",children:["Retrying in ~",Math.max(1,Math.round(dt.retryInMs/1e3)),"s"]})]}),dt&&Te&&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(Pn,{tone:dt.isRateLimited?"muted":"red",children:dt.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:dt.domainCurrent!==null&&dt.domainMax!==null?`${dt.domainCurrent}/${dt.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:dt.totalCurrent!==null&&dt.totalMax!==null?`${dt.totalCurrent}/${dt.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[dt.domain&&n.jsxs(Pn,{tone:"muted",children:["Domain: ",rt(dt.domain)]}),dt.modelTier&&n.jsxs(Pn,{tone:"muted",children:["Tier: ",rt(dt.modelTier)]}),bi&&n.jsxs(Pn,{tone:"muted",children:["Retry: ",bi]}),!bi&&dt.retryInMs!==null&&n.jsxs(Pn,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(dt.retryInMs/1e3)),"s"]})]}),dt.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:Ht(dt.blockedReason)??dt.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[Ae&&n.jsx("button",{type:"button",onClick:Ae,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"}),mn&&n.jsx("button",{type:"button",onClick:()=>void ki(),disabled:Ke,className:"rounded-full border border-lime/30 bg-lime/[0.12] px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/[0.18] disabled:opacity-50",children:Ke?"Scheduling...":"Retry now"})]})]}),Ji.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:Ji.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(Zt,{name:it.executor.label,hint:Cl(it.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:it.executor.label}),(()=>{const m=Hi(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:[Fn.has("action_needed")&&(B==null?void 0:B.nextStep)&&((Mt==null?void 0:Mt.tone)==="critical"||(Mt==null?void 0:Mt.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:B.nextStep})]}),(()=>{if(!Fn.has("session"))return null;const m=ut(R.item),x=oe(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"},W=S[x??""]??S[se.event??""]??null,Ne=W?k.indexOf(W):-1,Le=x==="completed"||x==="success",tt=ui(R.item),Ue=tt?ei.get(tt):null,pt=Ue!=null&&Ue.startedAt?new Date(Ue.startedAt).getTime():null,Je=Ue!=null&&Ue.completedAt?new Date(Ue.completedAt).getTime():null;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:ji(se.event)??rt(se.event)}),pt&&n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-black/20 px-2 py-0.5 text-micro text-secondary",children:[n.jsx(Ih,{startMs:pt,endMs:Je,isTerminal:Le})," ","elapsed"]})]})]}),Mt&&n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:Os},children:yi?(Et==null?void 0:Et.label)??"Stopped":`${Mt.pct}%`})]}),Ne>=0&&n.jsx("div",{className:"mt-3 flex items-center gap-1",children:k.map((lt,bt)=>{const Lt=bt<Ne||bt===Ne&&Le,bn=bt===Ne&&!Le;return n.jsxs("div",{className:"flex items-center gap-1",children:[bt>0&&n.jsx("div",{className:"h-[1.5px] w-4 sm:w-5",style:{backgroundColor:Lt||bn?L.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",bn&&"animate-pulse scale-110"),style:{backgroundColor:Lt||bn?L.lime:"rgba(255,255,255,0.18)"}}),n.jsxs("span",{className:ue("text-[10px] leading-none tracking-[0.05em]",Lt||bn?"text-primary":"text-muted/60"),children:[lt,Lt&&bt===k.length-1&&" ✓"]})]})]},lt)})}),Mt&&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,Mt.pct)}%`,backgroundColor:Os}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:yi?(Et==null?void 0:Et.summary)??Mt.label:Mt.label})]})]})})(),n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"People"}),ws.primary!==Vt?n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(Zt,{name:ws.primary,hint:ws.secondary??ws.primary,size:"xs"}),n.jsx("span",{children:ws.primary}),n.jsx("span",{className:"text-white/[0.2]",children:"→"}),n.jsx(Zt,{name:Vt,hint:Vt,size:"xs"}),n.jsx("span",{children:Vt}),se.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",rt(se.domain),")"]})]}):n.jsxs("div",{className:"flex items-center gap-2 text-body text-primary",children:[n.jsx(Zt,{name:Vt,hint:Vt,size:"xs"}),n.jsx("span",{children:Vt}),se.domain&&n.jsxs("span",{className:"text-caption text-muted",children:["(",rt(se.domain),")"]})]}),Te&&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:ws.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:Vt})]}),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:rt(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(", ")}`:""]})]})]})]}),Fn.has("scope")&&B&&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:B.initiativeTitle??(B.initiativeId?As(B.initiativeId):"—")})]}),B.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:rt(B.initiativeStatus)})]}),(B.workstreamTitle||B.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:B.workstreamTitle??As(B.workstreamId)})]}),B.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:rt(B.workstreamStatus)})]})]}),B.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:[B.doneInitiativeWorkstreams??0,"/",B.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-lime/80",style:{width:`${Math.max(4,B.initiativeWorkstreamPct)}%`}})})]})]}),sr.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(Mm,{nodes:Sm(sr),compact:!0})]}),((B==null?void 0:B.taskTitle)||(B==null?void 0:B.milestoneTitle)||(B==null?void 0:B.phase)||(B==null?void 0:B.nextStep)||(B==null?void 0:B.parsedStatus)||(B==null?void 0:B.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:[(B==null?void 0:B.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:B.taskTitle})]}),(B==null?void 0:B.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:B.milestoneTitle})]}),(B==null?void 0:B.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:ji(B.phase)??rt(B.phase)})]}),(B==null?void 0:B.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:B.nextStep})]}),(B==null?void 0:B.parsedStatus)&&B.parsedStatus!==(B==null?void 0:B.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:ji(B.parsedStatus)??rt(B.parsedStatus)})]}),(B==null?void 0:B.stopReason)&&B.stopReason!==(B==null?void 0:B.phase)&&B.stopReason!==(B==null?void 0:B.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:ji(B.stopReason)??rt(B.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})]}),Fn.has("summary")&&Fs&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),et==="missing"&&!wi&&Te&&n.jsx("p",{className:"mb-1 text-caption italic text-muted",children:"Transcript expired — showing event metadata"}),n.jsx(qi,{mode:"block",text:Fs,className:"text-body leading-relaxed text-primary"})]}),Ht(R.item.description)&&Ht(R.item.description)!==Fs&&(()=>{const m=Ht(R.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(qi,{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(qi,{mode:"block",text:m,className:"text-body leading-relaxed text-secondary"})]})})(),xn&&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:xn.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:xn.dispatch})]}),xn.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:xn.highlights.slice(0,3).map((m,x)=>n.jsx("li",{children:m},`${xn.sliceRunId}:highlight:${x}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:xn.outcome.summary})]})]})]}),(()=>{var An;if(!Fn.has("evidence"))return null;const m=ut(R.item),x=Gt(m==null?void 0:m.blocker),k=oe(m,["error","reason","blocked_reason","blockedReason","last_error","lastError"])??null,S=ia[0]??null,W=x?{description:oe(x,["description","summary"])??k??null,waiting_on:oe(x,["waiting_on","required_actor","requiredActor"])??null,required_action:oe(x,["required_action","requiredAction"])??oe(m,["next_step","nextStep"])??null}:S?{description:S.reason,waiting_on:S.waitingOn,required_action:S.requiredAction}:(R.item.type==="run_failed"||R.item.type==="blocker_created")&&k?{description:k,waiting_on:null,required_action:oe(m,["next_step","nextStep"])}:void 0,Ne=(m==null?void 0:m.decisions_needed)??(m==null?void 0:m.decisionsNeeded),Le=Array.isArray(Ne)?Ne.map(Ze=>{const ln=Gt(Ze);return ln?{title:oe(ln,["title","label","question","summary"])??"Pending decision",id:oe(ln,["id","decision_id","decisionId"])}:null}).filter(Ze=>Ze!==null):[],tt=Le.length>0?Le:$s.length>0?$s.map(Ze=>({title:Ze.title,id:Ze.id})):on.length>0?on.map(Ze=>({id:Ze,title:"Pending decision"})):void 0,Ue=m==null?void 0:m.outcomes,pt=(An=m==null?void 0:m.task_updates)==null?void 0:An.filter(Ze=>{var ln,zn;return((ln=Ze.title)==null?void 0:ln.trim().toLowerCase())!==((zn=W==null?void 0:W.description)==null?void 0:zn.trim().toLowerCase())}),Je=(W==null?void 0:W.description)&&(Et==null?void 0:Et.summary)&&W.description.trim().toLowerCase()===Et.summary.trim().toLowerCase(),lt=!!W&&!Je,bt=!!(Ue!=null&&Ue.pr_url||Ue!=null&&Ue.commit_sha||Ue!=null&&Ue.tests||pt&&pt.length>0),Lt=!!(lt||tt&&tt.length>0),bn=bt||Lt,as=Lt,Dn=Ln.length>0;return!as&&!Dn?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:[lt&&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:W.description??"Blocked"}),W.waiting_on&&n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Waiting on: ",W.waiting_on]}),W.required_action&&n.jsxs("p",{className:"mt-0.5 text-caption text-secondary",children:["Next action: ",W.required_action]})]})]}),Zi&&on.length>0&&n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[er.map(Ze=>n.jsx("button",{type:"button",onClick:()=>void(P==null?void 0:P(on[0],Ze.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:Ze.label},Ze.id)),n.jsx("button",{type:"button",onClick:()=>{j==null||j(on[0]??null),jn()},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"})]})]}),tt&&tt.length>0&&n.jsx("div",{className:"space-y-1.5",children:tt.map((Ze,ln)=>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:Ze.title})]}),Ze.id&&j&&n.jsx("button",{type:"button",onClick:()=>{j(Ze.id),jn()},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"})]},Ze.id??ln))}),Dn&&n.jsxs("details",{className:"group rounded-lg border border-white/[0.08] bg-black/15 px-2.5 py-2",open:!bn,children:[n.jsxs("summary",{className:"cursor-pointer list-none text-caption font-semibold text-secondary select-none",children:[Ln.length," evidence file",Ln.length===1?"":"s"]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[rr.map((Ze,ln)=>{const zn=qr(Ze.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:rt(Ze.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Wn(Ze.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[zn&&n.jsx("a",{href:zn,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 f(`${rt(Ze.key)} path`,Ze.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"})]})]},`${Ze.key}:${Ze.path}:${ln}`)}),qs.length>0&&qs.map((Ze,ln)=>{const zn=qr(Ze.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:rt(Ze.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Wn(Ze.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[zn&&n.jsx("a",{href:zn,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 f(`${rt(Ze.key)} path`,Ze.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"})]})]},`${Ze.key}:${Ze.path}:overflow:${ln}`)})]})]})]})]})})(),Te&&(yt||(se==null?void 0:se.logPath)||vi)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),Te&&(yt||(se==null?void 0:se.logPath)||(se==null?void 0:se.outputPath)||(B==null?void 0:B.initiativeId)||(B==null?void 0:B.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:[yt&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[yt.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:rt(yt.domain)})]}),(yt.provider||yt.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:[yt.provider?`${rt(yt.provider)} · `:"",yt.model?zi(yt.model):"—"]})]}),yt.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:rt(yt.modelTier)})]}),yt.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",yt.pluginVersion]})]})]}),(yt==null?void 0:yt.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:[yt.skillPack.name??"—",yt.skillPack.version?`@${yt.skillPack.version}`:"",yt.skillPack.source?` · ${yt.skillPack.source}`:""]}),yt.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var m;return void f("Skill pack checksum",((m=yt.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 ",yt.skillPack.checksum.slice(0,12)]})]}),yt&&yt.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"}),yt.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))]}),(yt==null?void 0:yt.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:[yt.kickoffContextSource?`${yt.kickoffContextSource} · `:"",yt.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void f("Kickoff context hash",yt.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: ",Wn(se.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void f("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: ",Wn(se.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void f("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"})]})]}),((B==null?void 0:B.initiativeId)||(B==null?void 0:B.workstreamId))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(B==null?void 0:B.initiativeId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["initiative: ",As(B.initiativeId)]}),(B==null?void 0:B.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",As(B.workstreamId)]})]})]})]}),Te&&vi&&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:vi})]})]})},R.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"})]})})]})})});function kg({workspaceLabel:e,suggestedTitle:t,sessionSummary:s,onCreateInitiative:i,onCreateFromSession:r,onOpenSandbox:a,onOpenSettings:l,onRefresh:c}){const d=!!(t&&t.trim().length>0);return n.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-8 sm:px-6",style:{backgroundColor:L.background},children:n.jsx(Ss,{className:"w-full max-w-5xl overflow-hidden",children:n.jsxs("div",{className:"grid gap-0 lg:grid-cols-[1.08fr_0.92fr]",children:[n.jsxs("div",{className:"border-b border-subtle p-6 sm:p-8 lg:border-b-0 lg:border-r",children:[n.jsxs(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.28,ease:[.16,1,.3,1]},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(an,{type:"initiative",size:16,className:"opacity-95"}),n.jsx("span",{className:"text-caption font-semibold uppercase tracking-[0.12em] text-secondary",children:"First value runway"}),n.jsx("span",{className:"chip",children:e})]}),n.jsx("h2",{className:"mt-4 max-w-2xl text-[30px] font-semibold leading-[1.08] tracking-[-0.03em] text-white sm:text-[38px]",children:"Connected successfully. There is no tracked work here yet."}),n.jsx("p",{className:"mt-4 max-w-2xl text-body leading-relaxed text-secondary sm:text-heading",children:"The fastest path to value is to create one initiative, dispatch one workstream, and watch OrgX keep the execution visible inside OpenClaw."})]}),n.jsxs(ce.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:.06,duration:.3,ease:[.16,1,.3,1]},className:"mt-6 grid gap-3",children:[n.jsxs("button",{type:"button",onClick:i,className:"flex min-h-[56px] items-center justify-between rounded-2xl border border-lime/28 bg-lime/10 px-4 py-3 text-left transition hover:bg-lime/14",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-semibold text-[#E4FFAD]",children:"Create first initiative"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-[#D7F3A3]/78",children:"Start with a real initiative and land directly in Mission Control once it exists."})]}),n.jsx(an,{type:"initiative",size:16,className:"shrink-0"})]}),n.jsxs("button",{type:"button",onClick:r,disabled:!d,className:"flex min-h-[56px] items-center justify-between rounded-2xl border border-white/[0.1] bg-white/[0.03] px-4 py-3 text-left transition hover:bg-white/[0.05] disabled:cursor-not-allowed disabled:opacity-45",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-semibold text-white",children:"Use current OpenClaw session as draft"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:d?`Prefill from “${t}” and refine before you launch.`:"No recent local session is available to prefill right now."})]}),n.jsx(an,{type:"session",size:16,className:"shrink-0 opacity-92"})]}),n.jsxs("button",{type:"button",onClick:a,className:"flex min-h-[56px] items-center justify-between rounded-2xl border border-white/[0.08] bg-white/[0.02] px-4 py-3 text-left transition hover:bg-white/[0.04]",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-semibold text-white",children:"Open guided sandbox"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:"See the operating model in a clearly marked sandbox before you set up real work."})]}),n.jsx(an,{type:"workstream",size:16,className:"shrink-0 opacity-92"})]})]})]}),n.jsxs("div",{className:"p-6 sm:p-8",children:[n.jsxs("div",{className:"rounded-2xl border border-white/[0.08] bg-white/[0.025] p-4",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(an,{type:"workstream",size:13,className:"text-lime"}),n.jsx("p",{className:"text-caption font-semibold uppercase tracking-[0.1em] text-secondary",children:"What happens next"})]}),n.jsxs("div",{className:"mt-4 space-y-3",children:[n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3",children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"1. Create one initiative"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:"Keep the title concrete. This becomes the first object OrgX can route, track, and score."})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3",children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"2. Add the first workstream"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:"One workstream is enough to prove the queue, dispatch, and progress model."})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3",children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"3. Watch one live execution"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:"The aha moment is seeing the work move from Next Up to In Progress with decisions and artifacts attached."})]})]})]}),n.jsxs("div",{className:"mt-4 rounded-2xl border border-white/[0.08] bg-white/[0.02] p-4",children:[n.jsx("p",{className:"text-caption font-semibold uppercase tracking-[0.1em] text-secondary",children:"Draft signal"}),n.jsx("p",{className:"mt-3 text-body font-semibold text-white",children:d?t:"No current OpenClaw session detected"}),n.jsx("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:s&&s.trim().length>0?s:"As soon as a local work session exists, this runway can prefill the initiative draft instead of starting from a blank field."}),n.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[n.jsx("button",{type:"button",onClick:l,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:"Review settings"}),n.jsx("button",{type:"button",onClick:c,className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-secondary transition hover:bg-white/[0.08] hover:text-primary",children:"Refresh workspace"})]})]})]})]})})})}const Ig=o.lazy(async()=>({default:(await cn(()=>import("./OlLPtzdz.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))).MissionControlView})),Ng=o.lazy(async()=>({default:(await cn(()=>import("./LOFrVoPD.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13]))).SessionInspector})),jg=o.lazy(async()=>({default:(await cn(()=>import("./qLX6NZ-J.js"),__vite__mapDeps([16,1,8,5,15,2,10,11,12,13]))).DecisionQueue})),Ag=o.lazy(()=>cn(()=>import("./CSlBSRyv.js"),__vite__mapDeps([17,1,5])).then(e=>({default:e.TriageQueue}))),_g=o.lazy(()=>cn(()=>import("./Dhz7qPtn.js"),__vite__mapDeps([18,1,5])).then(e=>({default:e.TriageDetailModal}))),Sg=o.lazy(async()=>({default:(await cn(()=>import("./9gFmK3Kr.js").then(t=>t.a),__vite__mapDeps([3,1,4,5,6]))).NextUpPanel})),Cg=o.lazy(async()=>({default:(await cn(()=>import("./m2smti3F.js"),__vite__mapDeps([19,1,2,5,9,10,11,12,13]))).SettingsModal})),Tg=o.lazy(async()=>({default:(await cn(()=>import("./BrMXbzQ-.js"),__vite__mapDeps([20,1,2,5,10,11,12,13]))).BulkSessionsModal})),Mg=o.lazy(async()=>({default:(await cn(()=>import("./DDCPrZRt.js"),__vite__mapDeps([21,1,16,8,5,15,2,10,11,12,13]))).BulkDecisionsModal})),Eg=o.lazy(async()=>({default:(await cn(()=>import("./nra1yvJX.js"),__vite__mapDeps([22,1,2,5,10,11,12,13]))).BulkOutboxModal})),Rg=o.lazy(async()=>({default:(await cn(()=>import("./RN4M9u9W.js"),__vite__mapDeps([23,1,2,5,10,11,12,13]))).BulkHandoffsModal})),Lg=o.lazy(async()=>({default:(await cn(()=>import("./D-FuHfT8.js"),__vite__mapDeps([24,1,2,4,5,10,11,12,13]))).ArtifactViewerModal})),Dg=o.lazy(async()=>({default:(await cn(()=>import("./VCHu272d.js"),__vite__mapDeps([25,1,8,5,7,6,2,10,11,12,13]))).SliceDetailModal})),Pg=o.lazy(async()=>({default:(await cn(()=>import("./DNQ-iFO2.js"),__vite__mapDeps([26,1,2,5,10,11,12,13]))).RealtimeOrchestratorModal})),Pl={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},$g={connected:L.lime,reconnecting:L.amber,disconnected:L.red},$l={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},Og=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function rn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function qg(e){const t=rn(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function Bg(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 Fg(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=en(e);return{title:"Live stream degraded",message:Bg(s),action:"settings"}}function Tr(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 Fl(e,t){const s=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";return!s||!i?null:`${s}:${i}`}function zg(e,t){const s=new Set,i=new Set;for(const a of t){const l=typeof a.runId=="string"?a.runId.trim():"";l&&s.add(l);const c=typeof a.sliceRunId=="string"?a.sliceRunId.trim():"";c&&s.add(c);const d=Fl(a.initiativeId,a.workstreamId);d&&i.add(d)}let r=0;for(const a of e){const l=typeof a.sourceRunId=="string"?a.sourceRunId.trim():"";if(l&&s.has(l))continue;const c=typeof a.sourceSessionId=="string"?a.sourceSessionId.trim():"";if(c&&s.has(c))continue;const d=Fl(a.initiativeId,a.workstreamId);d&&i.has(d)||(r+=1)}return r}function Ug(e){return e.filter(t=>t.queueState!=="running"&&t.queueState!=="completed").length}function Wg(e,t=new Date){if(!e)return!1;const s=new Date(e);return Number.isNaN(s.getTime())?!1:s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function Ra(e,t){const s=$l[e.status]??99,i=$l[t.status]??99;return s!==i?s-i:rn(e.updatedAt??e.lastEventAt??e.startedAt)-rn(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=>{var d;const a=r.queueState,l=r.playbackState??null,c=((d=r.autoContinue)==null?void 0:d.status)??null;return a==="blocked"||a==="running"||a==="completed"||l==="blocked"||l==="running"||l==="completed"||c==="running"||c==="stopping"?!1:a==="queued"||a==="idle"})??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){const t=e==null?void 0:e.run;if(!t)return null;const s=typeof t.activeRunId=="string"?t.activeRunId.trim():"";if(s)return s;if(Array.isArray(t.activeSliceRunIds)){for(const r of t.activeSliceRunIds)if(typeof r=="string"&&r.trim().length>0)return r.trim()}return(typeof t.lastRunId=="string"?t.lastRunId.trim():"")||null}function Wl(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 Hg(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 Kg(e){if(gi(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Vg(e){if(gi(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Gg(e){const t=e.metadata;return t==null||typeof t!="object"?!1:t.mock===!0}function Xg(e){return Og.test(e)}function Mr(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 Qg(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Yg(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function Jg(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 Zg(e,t){Ts(e,t)}function ex(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 tx(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=Jg(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(La);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function nx(){const e=ku();return e.showGate?n.jsx(um,{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(Sp,{children:n.jsx(ox,{onboarding:e})})}function sx(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 ix(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 Hl(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 Kl(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function rx(){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:Jr,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function ax(){const{state:e}=vc();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Lg,{})}):null}function ox({onboarding:e}){var ki;const[t,s]=o.useState(()=>Oi()),[i,r]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Lr)==="1"}catch{return!1}}),[a,l]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(pa)==="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(()=>tx()),g=o.useCallback(f=>{d(f);try{localStorage.setItem("orgx-dashboard-view",f)}catch{}},[]),{data:v=[]}=Zs({queryKey:["workspace-options",t?"demo":"live",e.state.hasApiKey?"auth":"anon",e.state.connectionVerified?"verified":"unverified",u??"__all__"],queryFn:async()=>{if(t)return[];const f=new URLSearchParams;f.set("type","command_center"),f.set("limit","50");const N=await fetch(`/orgx/api/entities?${f.toString()}`,{headers:Ut({workspaceId:u})});if(!N.ok)return[];const $=await N.json().catch(()=>null),_=Array.isArray($==null?void 0:$.data)?$.data:[],Ie=[];for(const je of _){if(!je||typeof je!="object"||Array.isArray(je))continue;const Ge=Mr(je,["id"]);if(!Ge)continue;const Pe=Mr(je,["status","priority"]);if(!Qg(Pe))continue;const _e=Mr(je,["title","name"])??(Ge.length>10?`${Ge.slice(0,8)}…`:Ge),m=je.is_default===!0,x=Yg({title:_e,isDefault:m}),k=Mr(je,["created_at"]);Ie.push({id:Ge,title:x,status:Pe,isDefault:m,createdAt:k})}return Ie.sort((je,Ge)=>{if(je.isDefault!==Ge.isDefault)return je.isDefault?-1:1;const Pe=rn(je.createdAt)-rn(Ge.createdAt);return Pe!==0?Pe:je.title.localeCompare(Ge.title)}),Ie},staleTime:6e4}),h=o.useMemo(()=>{var f;return u?((f=v.find(N=>N.id===u))==null?void 0:f.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,v]),w=o.useMemo(()=>!u||v.some(f=>f.id===u)?v:[{id:u,title:h,status:null,isDefault:!1,createdAt:null},...v],[u,h,v]);o.useEffect(()=>{u&&v.length!==0&&(v.some(f=>f.id===u)||p(null))},[u,v]),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:I,isLoading:M,error:F,refetch:b,approveDecision:A,rejectDecision:H,approveAllDecisions:j,bulkDecisionAction:P,decisionMutation:Z}=Jd({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...y}),E=t||i,D=o.useMemo(()=>E?I.sessions.nodes:I.sessions.nodes.filter(f=>!Kg(f)),[I.sessions.nodes,E]),ee=o.useMemo(()=>I.activity.filter(f=>!(!E&&Vg(f)||!a&&Gg(f))),[I.activity,E,a]),ve=I.connection==="connected"||I.decisions.length>0,[Ce,pe]=o.useState(null),[Ae,re]=o.useState(!1),[ne,G]=o.useState(null),[ae,De]=o.useState(null),[Te,de]=o.useState(null),[we,C]=o.useState(null),[O,U]=o.useState(null),[K,ye]=o.useState("24h"),[Oe,me]=o.useState({startIso:null,endIso:null}),ke=o.useRef(new Set),[T,be]=o.useState(null),[Y,Ee]=o.useState(null),[ze,Be]=o.useState(null),[ft,Me]=o.useState(null),Se=o.useRef(null),J=o.useCallback(f=>{Se.current&&clearTimeout(Se.current),Me(f),Se.current=setTimeout(()=>Me(null),4e3)},[]),[ht,It]=o.useState(!1),[We,Q]=o.useState(!1),[q,te]=o.useState([]),le=o.useRef(null),$e=o.useRef(null),[Ve,Ye]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[fe,Qe]=o.useState(!1),[ie,V]=o.useState(null),[Re,et]=o.useState("activity"),[ct,gt]=o.useState("initiatives"),[mt,vt]=o.useState("next_up"),jt=o.useCallback(f=>{if(et(f),f==="initiatives"){gt("initiatives"),vt("next_up");return}f==="decisions"&&(gt("initiatives"),vt("in_progress"),he("needs_attention"))},[]),[X,he]=o.useState("all"),qe=o.useMemo(()=>Array.isArray(I.sliceRuns)?I.sliceRuns:[],[I.sliceRuns]),nt=o.useMemo(()=>{var Ie,je,Ge,Pe;const f=qe.filter(_e=>{const m=Bt(_e.status);return m==="completed"||m==="archived"});if(f.length===0)return[];const N=new Map;for(const _e of D){const m=(Ie=_e.runId)==null?void 0:Ie.trim();m&&!N.has(m)&&N.set(m,_e);const x=(je=_e.id)==null?void 0:je.trim();x&&!N.has(x)&&N.set(x,_e)}const $=new Map;for(const _e of D){const m=(Ge=_e.initiativeId)==null?void 0:Ge.trim(),x=(Pe=_e.groupLabel)==null?void 0:Pe.trim();!m||!x||$.has(m)||$.set(m,x)}const _=[];for(const _e of f){const m=(_e.runId??_e.sliceRunId??"").trim();if(!m)continue;const x=N.get(m)??N.get(_e.sliceRunId)??null,k=_e.initiativeId??(x==null?void 0:x.initiativeId)??null,S=ee.filter(W=>{const Ne=Tr(W),Le=Ol(W);return!!(Ne&&(Ne===m||Ne===_e.sliceRunId)||Le&&Le===_e.sliceRunId)}).sort((W,Ne)=>rn(W.timestamp)-rn(Ne.timestamp));_.push({key:`completed:${_e.sliceRunId}`,runId:m,title:_e.workstreamTitle??(x==null?void 0:x.title)??`Completed slice ${_e.sliceRunId.slice(0,8)}`,statusExplainer:_e.statusExplainer??_e.lastEventSummary??(x==null?void 0:x.lastEventSummary)??null,initiativeTitle:k?$.get(k)??k:null,workstreamTitle:_e.workstreamTitle??(x==null?void 0:x.title)??null,scope:_e.scope??null,taskIds:Array.isArray(_e.taskIds)?_e.taskIds:[],milestoneIds:Array.isArray(_e.milestoneIds)?_e.milestoneIds:[],artifacts:Array.isArray(_e.artifacts)?_e.artifacts:[],artifactCount:_e.artifactCount??0,completedAt:_e.completedAt??_e.updatedAt??_e.lastEventAt??(x==null?void 0:x.updatedAt)??(x==null?void 0:x.lastEventAt)??null,timelineEvents:S})}return _.sort((_e,m)=>rn(m.completedAt)-rn(_e.completedAt)),_},[qe,ee,D]),Ke=nt.length,[Xe,He]=o.useState(null),xt=o.useCallback(f=>{const N=qe.find($=>$.initiativeId===f.initiativeId&&$.workstreamId===f.workstreamId)??null;He({source:"queue",item:f,linkedSliceRun:N})},[qe]),Qt=o.useCallback((f,N)=>{He({source:"in_progress",row:f,sliceRun:N})},[]),wt=o.useCallback(f=>{He({source:"needs_input",sliceRun:f})},[]),At=o.useCallback(async(f,N)=>{J("Slice accepted and marked complete."),b()},[b,J]),Pt=o.useCallback(async(f,N)=>{J("Changes requested — feedback posted.")},[J]),Kt=o.useCallback(async(f,N,$)=>{await A(f,{optionId:N,...$?{note:$}:{}}),J("Decision resolved.")},[A,J]),at=qu({projectId:u,limit:40,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:I.snapshotVersion}),st=Bu({authToken:null,embedMode:!1,projectId:u}),{model:Ft,actions:Rt}=Uu({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),$t=o.useMemo(()=>Ft.items.filter(f=>f.kind==="failure_diagnostic"),[Ft.items]),Dt=o.useMemo(()=>({...Ft,items:$t,total:$t.length}),[$t,Ft]),[Yt,kn]=o.useState(null),[ys,Vn]=o.useState(0),Gn=o.useCallback(f=>{kn(f);const N=$t.findIndex($=>$.id===f.id);Vn(N>=0?N:0)},[$t]),Xn=o.useCallback(f=>{if($t.length===0)return;const N=(ys+f+$t.length)%$t.length;Vn(N),kn($t[N]??null)},[ys,$t]),Qn=at,Ms=o.useMemo(()=>{var f;return((f=Qn.summary)==null?void 0:f.visibleTotal)??Ug(Qn.items)},[Qn.items,(ki=Qn.summary)==null?void 0:ki.visibleTotal]),In=o.useMemo(()=>{var Ie;const f=at.items.filter(je=>je.autoContinue);if(f.length===0)return null;const N=[...f].sort((je,Ge)=>Wl(Ge)-Wl(je)),$=N.find(je=>{var Ge,Pe;return((Ge=je.autoContinue)==null?void 0:Ge.status)==="running"||((Pe=je.autoContinue)==null?void 0:Pe.status)==="stopping"})??null;if($)return{item:$,state:((Ie=$.autoContinue)==null?void 0:Ie.status)==="stopping"?"stopping":"running"};const _=N.find(je=>{var Ge,Pe;return((Ge=je.autoContinue)==null?void 0:Ge.stopReason)==="blocked"||((Pe=je.autoContinue)==null?void 0:Pe.stopReason)==="error"})??null;return _?{item:_,state:"blocked"}:null},[at.items]),tn=(In==null?void 0:In.item)??null,dn=(In==null?void 0:In.state)??"idle",hn=dn==="running"||dn==="stopping",Es=dn==="blocked"?"blocked":hn?"active":"idle",Yn=dn==="blocked"?"Hold":hn?"On":"Off",bs=dn==="blocked"?"Resolve blockers, then resume autopilot":hn?"Stop autopilot":"Start autopilot",ei=dn==="blocked"?"amber":"teal",Rs=o.useMemo(()=>{var f,N;return tn?{state:dn,reason:((f=tn.autoContinue)==null?void 0:f.stopReason)??tn.blockReason??null,activeRunId:((N=tn.autoContinue)==null?void 0:N.activeRunId)??null,activeWorkstreamTitle:tn.workstreamTitle??null}:null},[tn,dn]);o.useEffect(()=>{if(!(typeof window>"u"))try{t?(window.localStorage.setItem(Ur,"1"),window.localStorage.removeItem(Wr)):(window.localStorage.removeItem(Ur),window.localStorage.removeItem(Wr))}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{i?window.localStorage.setItem(Lr,"1"):window.localStorage.removeItem(Lr)}catch{}},[i]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(pa,"1"):window.localStorage.removeItem(pa)}catch{}},[a]),o.useEffect(()=>{a||Qe(!1)},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(La,u):window.localStorage.removeItem(La)}catch{}try{const f=new URL(window.location.href);u?Zg(f.searchParams,u):ex(f.searchParams),f.searchParams.delete("initiative"),f.searchParams.delete("initiative_id"),f.searchParams.delete("project"),window.history.replaceState(null,"",`${f.pathname}${f.search}${f.hash}`)}catch{}}},[u]);const Jt=o.useCallback((f,N)=>{Ye($=>({open:!0,tab:f??$.tab,focusAgentDomain:(N==null?void 0:N.focusAgentDomain)??null}))},[]),En=o.useCallback(f=>{if(s(f),!(typeof window>"u"))try{const N=new URL(window.location.href);f?(N.searchParams.set("sandbox","1"),N.searchParams.delete("demo")):(N.searchParams.delete("sandbox"),N.searchParams.delete("demo")),window.history.replaceState(null,"",`${N.pathname}${N.search}${N.hash}`)}catch{}},[]),Jn=o.useCallback(()=>{Jt("orgx")},[Jt]),z=o.useCallback(()=>{cn(()=>import("./OlLPtzdz.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))},[]),ge=e.state.connectionVerified&&!t,{data:xe,isLoading:Fe}=yc(ge,u),{data:_t,isLoading:Ct}=_p(ge,u),{data:ot=[]}=Zs({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[nn,Tt]=o.useState(null),[Zn,es]=o.useState(""),[Ot,pn]=o.useState(!1),ds=o.useCallback((f,N)=>{Tt({type:f,initiativeId:N}),es(""),pn(!1)},[]),ts=o.useCallback(()=>{Tt(null),es(""),pn(!1)},[]),Ls=o.useCallback(()=>{De(null)},[]),Ds=o.useCallback(()=>{de(null),C(null)},[]),us=o.useCallback(()=>{Be(null)},[]);o.useEffect(()=>{var $;const f=(($=D[0])==null?void 0:$.id)??null;if(!f){Ce!==null&&pe(null);return}if(Ce===null){pe(f);return}D.some(_=>_.id===Ce)||pe(f)},[D,Ce]),o.useEffect(()=>{if(!ae)return;D.some(N=>N.id===ae)||De(null)},[ae,D]);const Nn=o.useCallback(f=>{cn(()=>import("./LOFrVoPD.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),pe(f),re(!0),G(null),De(f),de(null),C(null)},[]);o.useEffect(()=>{if(!O)return;const f=D.find(N=>N.id===O||N.runId===O)??null;f&&(Nn(f.id),U(null))},[Nn,O,D]);const Xi=o.useCallback(f=>{cn(()=>import("./LOFrVoPD.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),pe(f.id),re(!0),De(f.id),de(f.workstreamId??null),C(f.title),G({workstreamId:f.workstreamId??null,text:`Intervention requested for "${f.title}". `}),J(`Opened intervention composer for ${f.title}.`)},[]),ms=o.useCallback(f=>{const N=f.trim();if(!N)return;const $=D.find(_=>_.runId===N||_.id===N)??null;if(!$){J("Session not found — it may have ended or not started yet.");return}Nn($.id),J(`Focused session: ${$.title}`)},[D,Nn,J]),na=o.useCallback(f=>{var _;const N=(_=f.id)==null?void 0:_.trim();if(!N)return;const $=Tr(f);if($){const Ie=D.find(je=>je.runId===$||je.id===$)??null;Ie&&(pe(Ie.id),De(Ie.id))}g("activity"),et("activity"),re(!1),be(N),J("Opened activity detail from session timeline.")},[D,g]),zt=o.useMemo(()=>D.find(f=>f.id===ae)??null,[ae,D]),qn=o.useMemo(()=>{var $,_;const f=(($=zt==null?void 0:zt.runId)==null?void 0:$.trim())??"",N=((_=zt==null?void 0:zt.id)==null?void 0:_.trim())??"";return!f||!N?[]:f===N?[f]:[f,N]},[zt==null?void 0:zt.id,zt==null?void 0:zt.runId]),ti=o.useMemo(()=>{const f=new Set;for(const N of qn){const $=N.trim();$.length>0&&f.add($)}return f},[qn]),xi=o.useMemo(()=>{const f=new Map;for(const N of D){const $=N.workstreamId??null;N.runId&&f.set(N.runId,$),N.id&&f.set(N.id,$)}return f},[D]),ns=o.useMemo(()=>{const f=qn.length>0?qn.join("|"):"*",N=(Te==null?void 0:Te.trim())||"*",$=(ze==null?void 0:ze.trim())||"*";return`${f}::${N}::${$}`},[Te,ze,qn]),sa=o.useCallback(f=>{ke.current.add(ns),ye(f)},[ns]);o.useEffect(()=>{if(ke.current.has(ns)||M)return;const f=Date.now(),N=ee.filter(Ie=>{const je=Tr(Ie);if(ti.size>0&&(!je||!ti.has(je)))return!1;if(Te){const Ge=ql(Ie);if((Bl(Ge,["workstreamId","workstream_id"])??(je?xi.get(je)??null:null))!==Te)return!1}if(ze){const Ge=ql(Ie);if((Bl(Ge,["agentName","agent_name"])??Ie.agentName)!==ze)return!1}return!0});if(N.length===0)return;const _=["live","24h","7d","all"].find(Ie=>{const je=Vi(Ie,f);return N.some(Ge=>{const Pe=rn(Ge.timestamp);return Pe?je===null||Pe>=je:!1})})??"all";ke.current.add(ns),_!==K&&ye(_)},[Te,ee,ns,K,xi,ze,M,ti]);const vs=ou({seed:ee,timeFilterId:K,customSinceIso:K==="custom"?Oe.startIso:null,customUntilIso:K==="custom"?Oe.endIso:null,runId:(zt==null?void 0:zt.runId)??null,projectId:u,pageSize:50,demoMode:t}),un=o.useMemo(()=>D.find(f=>f.id===Ce)??null,[D,Ce]),Qi=o.useMemo(()=>gc({sessions:D,sliceRuns:qe}),[qe,D]),Ps=typeof I.runningWorkSlices=="number"&&Number.isFinite(I.runningWorkSlices)?Math.max(0,Math.floor(I.runningWorkSlices)):Qi.length,gn=o.useMemo(()=>xc(qe),[qe]),R=o.useMemo(()=>ve?zg(I.decisions,gn.map(f=>f.item)):0,[I.decisions,ve,gn]),ss=typeof I.needsInputTotal=="number"&&Number.isFinite(I.needsInputTotal)?Math.max(0,Math.floor(I.needsInputTotal)):gn.length+R,xn=Ps,yn=o.useMemo(()=>Math.max(0,ss-R),[ss,R]);o.useMemo(()=>D.filter(f=>f.status==="failed").length,[D]);const is=o.useMemo(()=>{if(typeof I.completedTodayTotal=="number"&&Number.isFinite(I.completedTodayTotal))return Math.max(0,Math.floor(I.completedTodayTotal));const f=new Date;return D.filter(N=>N.status==="completed"&&Wg(N.updatedAt??N.lastEventAt??N.startedAt,f)).length},[I.completedTodayTotal,D]);o.useMemo(()=>{const f=ss;return[{id:"active",label:"Running",value:xn,color:xn>0?L.lime:L.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:f,color:f>0?L.amber:L.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:is,color:L.teal,icon:"session"}]},[xn,is,ss]),o.useMemo(()=>I.decisions.length>0?Math.max(0,...I.decisions.map(f=>f.waitingMinutes)):0,[I.decisions]);const Bn=o.useMemo(()=>F?Fg(F):null,[F]),rs=o.useMemo(()=>{const f=[];if(Bn){const N=Bn.action==="refresh"&&typeof b=="function";f.push({id:`stream-error:${F}`,kind:"error",icon:"notification",title:Bn.title,message:Bn.message,actionLabel:N?"Refresh":"Settings",onAction:N?()=>void b():()=>Jt("orgx")})}return I.connection!=="connected"&&f.push({id:`connection:${I.connection}`,kind:I.connection==="disconnected"?"error":"info",icon:"notification",title:I.connection==="disconnected"?"Connection lost":"Reconnecting",message:I.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:Jn}),ft&&f.push({id:`ops:${ft}`,kind:"info",icon:/decision/i.test(ft)?"decision":"workstream",title:"Update",message:ft}),f},[I.connection,I.outbox.lastReplayError,I.outbox.pendingTotal,I.outbox.replayStatus,F,Bn,Jn,b,Jt,ft]);o.useEffect(()=>{const f=new Set(rs.map(N=>N.id));te(N=>N.filter($=>f.has($)))},[rs]);const it=o.useMemo(()=>rs.filter(f=>!q.includes(f.id)),[q,rs]),Rn=R,se=ss,Yi=o.useCallback(f=>{te(N=>N.includes(f)?N:N.concat(f))},[]),ws=o.useCallback(()=>{te(rs.map(f=>f.id))},[rs]);o.useEffect(()=>{if(!We)return;const f=$=>{var Ie,je;const _=$.target;_&&((Ie=$e.current)!=null&&Ie.contains(_)||(je=le.current)!=null&&je.contains(_)||Q(!1))},N=$=>{$.key==="Escape"&&Q(!1)};return document.addEventListener("mousedown",f),document.addEventListener("touchstart",f),document.addEventListener("keydown",N),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("touchstart",f),document.removeEventListener("keydown",N)}},[We]);const Vt=o.useMemo(()=>{var $;const f=new Map;for(const _ of D){const Ie=_.initiativeId??_.groupId??"unscoped",je=_.groupLabel&&_.groupLabel.trim().length>0?_.groupLabel:_.initiativeId??"Unscoped Initiative",Ge=sx(je),Pe=f.get(Ie)??{id:Ie,name:je,category:Ge,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(_.progress!==null&&(Pe.progressTotal+=_.progress,Pe.progressCount+=1),Pe.statusCounts[_.status]=(Pe.statusCounts[_.status]??0)+1,_.agentName&&(Pe.allAgents.add(_.agentName),["running","queued","pending","blocked"].includes(_.status)&&Pe.activeAgents.add(_.agentName)),_.workstreamId){const _e=I.sessions.groups.find(x=>x.id===_.workstreamId),m=(($=_e==null?void 0:_e.label)==null?void 0:$.trim())||_.workstreamId;Pe.workstreams.set(_.workstreamId,m)}Pe.latestEpoch=Math.max(Pe.latestEpoch,rn(_.updatedAt??_.lastEventAt??_.startedAt)),f.set(Ie,Pe)}const N=[];for(const _ of f.values()){const Ie=_.progressCount>0?Math.round(_.progressTotal/_.progressCount):_.statusCounts.completed?100:_.statusCounts.running?55:0,je=_.category,Ge=ix(je),Pe=Math.round(Math.max(0,Math.min(100,Ie))/100*(Ge.length-1)),_e=(_.statusCounts.blocked??0)>0,m=(_.statusCounts.completed??0)>0&&(_.statusCounts.running??0)===0&&(_.statusCounts.queued??0)===0&&(_.statusCounts.pending??0)===0&&(_.statusCounts.blocked??0)===0&&(_.statusCounts.paused??0)===0,x=!m&&!_e&&(_.statusCounts.paused??0)>0&&(_.statusCounts.running??0)===0&&(_.statusCounts.queued??0)===0&&(_.statusCounts.pending??0)===0,k=(_.statusCounts.running??0)+(_.statusCounts.active??0)+(_.statusCounts.in_progress??0),S=(_.statusCounts.queued??0)+(_.statusCounts.pending??0),W=_.workstreams.size,Ne=`${W} workstream${W===1?"":"s"}`,Le=W===0?"No workstreams linked yet.":m?`${Ne} completed.`:_e?`${Ne} linked · resolve blockers to continue.`:x?`${Ne} linked · initiative is paused.`:k>0?`${k} workstream${k===1?"":"s"} active right now.`:S>0?`${S} workstream${S===1?"":"s"} queued to start.`:`${Ne} linked · ready to run.`,tt=Ge.map((Ue,pt)=>{let Je="upcoming";return(m||pt<Pe)&&(Je="completed"),pt===Pe&&!m&&(Je=_e?"warning":"current"),{name:Ue,status:Je}});N.push({id:_.id,name:_.name,status:m?"completed":_e?"blocked":x?"paused":"active",rawStatus:m?"completed":_e?"blocked":x?"paused":"active",category:je,health:Math.max(0,Math.min(100,Ie)),phases:tt,currentPhase:m?Ge.length-1:Pe,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:Le,workstreams:Array.from(_.workstreams.entries()).map(([Ue,pt])=>({id:Ue,name:pt,status:"active"}))})}return N.sort((_,Ie)=>{const je=_.status==="blocked"?0:_.status==="active"?1:2,Ge=Ie.status==="blocked"?0:Ie.status==="active"?1:2;return je!==Ge?je-Ge:Ie.health-_.health})},[D,I.sessions.groups]),ps=o.useMemo(()=>{const f=(_,Ie)=>{var Pe,_e;const je=typeof Ie.description=="string"&&Ie.description.trim().length>0?Ie.description:null,Ge=typeof _.description=="string"&&_.description.trim().length>0?_.description:null;return{..._,...Ie,health:Ie.health>0?Ie.health:_.health,activeAgents:Math.max(_.activeAgents,Ie.activeAgents),totalAgents:Math.max(_.totalAgents,Ie.totalAgents),avatars:(Pe=_.avatars)!=null&&Pe.length?_.avatars:Ie.avatars,workstreams:(_e=_.workstreams)!=null&&_e.length?_.workstreams:Ie.workstreams,description:je??Ge??void 0,rawStatus:Ie.rawStatus??_.rawStatus??null,targetDate:Ie.targetDate??_.targetDate??null,createdAt:Ie.createdAt??_.createdAt??null,updatedAt:Ie.updatedAt??_.updatedAt??null}},N=new Map;for(const _ of Vt)N.set(_.id,_);for(const _ of[..._t??[],...xe??[]]){if(!E&&gi(_.id)){N.delete(_.id);continue}const Ie=_.rawStatus??_.status;if(!Kl(Ie)){N.delete(_.id);continue}const je=N.get(_.id);N.set(_.id,je?f(je,_):_)}const $=new Set(ot);return Array.from(N.values()).filter(_=>!$.has(_.id)).filter(_=>Kl(_.rawStatus??_.status)).sort((_,Ie)=>{const je=x=>x==="blocked"?0:x==="active"?1:x==="paused"?2:3,Ge=je(_.status)-je(Ie.status);if(Ge!==0)return Ge;const Pe=Hl(_.priority)-Hl(Ie.priority);if(Pe!==0)return Pe;const _e=rn(Ie.updatedAt)-rn(_.updatedAt);if(_e!==0)return _e;const m=Ie.health-_.health;return m!==0?m:_.name.localeCompare(Ie.name)})},[Vt,xe,E,_t,ot]),Mt=o.useMemo(()=>[...D].filter(f=>f.title.trim().length>0).sort((f,N)=>rn(N.updatedAt??N.lastEventAt??N.startedAt)-rn(f.updatedAt??f.lastEventAt??f.startedAt))[0]??null,[D]),B=!t&&e.state.connectionVerified&&!M&&!Fe&&!Ct&&ps.length===0,Et=o.useMemo(()=>{const f={};for(const N of ps)N.id&&N.name&&(f[N.id]=N.name);return f},[ps]),Fn=o.useMemo(()=>{if(!zt)return null;const f=zt.agentName,N=zt.title;if(f){const $=ee.find(_=>{var Ie;return _.runId===zt.runId&&((Ie=_.summary)==null?void 0:Ie.trim())});if($!=null&&$.summary){const _=$.summary.trim().length>40?$.summary.trim().slice(0,40)+"…":$.summary.trim();return`${f}: ${_}`}return f}if(N){const $=N.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if($.length>0)return $}return N??null},[ee,zt]),Ji=o.useMemo(()=>{const f=new Map;for(const N of D){const $=(N.agentId??"").trim()||`name:${(N.agentName??"").trim()}`,_=(N.agentName??"").trim()||(N.agentId??"").trim();if(!_)continue;const Ie=N.updatedAt??N.lastEventAt??N.startedAt??"unknown",je=rn(Ie),Ge=je?Math.max(0,Math.floor((Date.now()-je)/6e4)):Number.MAX_SAFE_INTEGER,Pe=f.get($),_e={id:$,name:_,role:"Agent",status:Hg(N.status),task:N.title??null,progress:N.progress??null,lastActive:Ie,lastActiveMinutes:Ge};(!Pe||rn(_e.lastActive)>rn(Pe.lastActive))&&f.set($,_e)}return Array.from(f.values())},[D]),on=o.useCallback(async(f,N)=>{const $=await f.json().catch(()=>null),_=typeof($==null?void 0:$.error)=="string"&&$.error.trim()||typeof($==null?void 0:$.message)=="string"&&$.message.trim()||`${N} (${f.status})`;return/unknown api endpoint/i.test(_)?`${N}. This route is unavailable in the running plugin build.`:en(_)},[]),Zi=o.useCallback(async()=>{if(D.length===0){J("No sessions available to continue.");return}const f=[...D].sort(Ra)[0];if(pe(f.id),De(f.id),de(null),C(null),["blocked","pending","queued"].includes(f.status)){const N=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})});if(!N.ok)throw new Error(await on(N,`Failed to resume ${f.title}`))}J(`Focused highest priority session: ${f.title}`),await b()},[on,b,D]),sn=o.useCallback((f,N)=>!f||f.trim().length===0?N:en(f.trim())||N,[]),er=o.useCallback(async()=>{const f=zl(at.items);if(!f){J("No startable Next Up workstream is available."),g("mission-control");return}const N=await at.playWorkstream({initiativeId:f.initiativeId,workstreamId:f.workstreamId,agentId:f.runnerAgentId});vt("in_progress"),he("all"),gt("initiatives"),De(null),de(f.workstreamId),C(f.workstreamTitle),Be(null),typeof N.sessionId=="string"&&N.sessionId.trim().length>0&&U(N.sessionId.trim()),J(N.dispatchMode==="pending"?`Dispatching ${f.workstreamTitle}…`:`Started ${f.workstreamTitle}.`),await Promise.all([at.refetch(),b()])},[b,at,g]),$s=o.useCallback(async(f=null)=>{const N=zl(at.items,f);if(!N){J("No startable initiative is ready for Autopilot yet."),g("mission-control");return}await st.move({initiativeId:N.initiativeId,workstreamId:N.workstreamId,placement:"top"});const $=await at.startWorkstreamAutoContinue({initiativeId:N.initiativeId,workstreamId:N.workstreamId,agentId:N.runnerAgentId,scope:"initiative"});vt("in_progress"),he("all"),gt("initiatives"),De(null);const _=Ul($);_?U(_):(de(N.workstreamId),C(N.workstreamTitle)),J(_?`Autopilot started for ${N.initiativeTitle}.`:`Autopilot started for ${N.initiativeTitle}; dispatching from ${N.workstreamTitle}.`),await Promise.all([at.refetch(),b()])},[b,st,at,g]),ia=o.useCallback(async()=>{It(!0);try{if(!tn||!hn){const f=dn==="blocked"?(tn==null?void 0:tn.initiativeId)??null:null;await $s(f);return}await at.stopInitiativeAutoContinue({initiativeId:tn.initiativeId}),J(`Autopilot stopped for ${tn.initiativeTitle}.`),await Promise.all([at.refetch(),b()])}finally{It(!1)}},[hn,tn,dn,b,at,$s]),Os=o.useCallback(async f=>{const N=(f.initiativeId??"").trim(),$=(f.workstreamId??"").trim();if(!N||!$)throw new Error("Missing initiative/workstream metadata for this session.");const _=await at.playWorkstream({initiativeId:N,workstreamId:$,agentId:f.agentId??void 0});De(null),de($),C(f.title),typeof _.sessionId=="string"&&_.sessionId.trim().length>0&&U(_.sessionId.trim()),J(_.dispatchMode==="pending"?`Dispatching ${f.title}…`:`Started ${f.title}.`),await Promise.all([at.refetch(),b()])},[b,at]),yi=o.useCallback(async f=>{const N=(f.initiativeId??"").trim(),$=(f.workstreamId??"").trim();if(!N||!$)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:N,workstreamId:$,placement:"bottom",resetToTodo:!1})});if(!_.ok){const Ie=await on(_,"Failed to pause workstream from In Progress");throw new Error(Ie)}J(`Paused ${f.title} and sent it to the bottom of queue.`),await Promise.all([at.refetch(),b()])},[on,b,at]),yt=o.useCallback(async f=>{const N=(f.workstreamId??"").trim();if(!N)throw new Error("This session is missing a workstream id for intervention notes.");const $=f.text.trim();if(Xg($)){Jt("agents",{focusAgentDomain:"engineering"}),J("Opened agent settings for engineering runtime configuration.");return}const _=await fetch(`/orgx/api/entities/workstream/${encodeURIComponent(N)}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:$,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!_.ok)throw new Error(await on(_,"Failed to submit intervention"));J(`Intervention sent for ${f.session.title}.`),await b()},[Jt,on,b]),tr=o.useCallback(async f=>{if(pe(f.id),De(f.id),de(null),C(null),!["running","completed","archived"].includes(f.status)){const N=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})});if(!N.ok)throw new Error(await on(N,`Failed to dispatch ${f.title}`))}J(`Dispatch requested: ${f.title}`),await b()},[on,b]),dt=o.useCallback(async(f,N,$={})=>{const _=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/actions/${N}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!_.ok){const Ie=await _.json().catch(()=>null);throw new Error((Ie==null?void 0:Ie.error)??`${N} failed (${_.status})`)}},[]),bi=o.useCallback(async f=>{var Ie;const N=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!N.ok){const je=await N.json().catch(()=>null);throw new Error((je==null?void 0:je.error)??`Checkpoint creation failed (${N.status})`)}const $=await N.json().catch(()=>null),_=$&&"data"in $&&((Ie=$.data)==null?void 0:Ie.id)||$&&"id"in $&&$.id||null;J(_?`Checkpoint created: ${_.slice(0,8)}`:"Checkpoint created."),await b()},[b]),nr=o.useCallback(async f=>{await dt(f,"pause",{reason:"pause_from_dashboard"}),J(`Pause requested: ${f.title}`),await b()},[b,dt]),vi=o.useCallback(async f=>{await dt(f,"resume",{reason:"resume_from_dashboard"}),J(`Resume requested: ${f.title}`),await b()},[b,dt]),sr=o.useCallback(async f=>{await dt(f,"cancel",{reason:"restart_from_in_progress"}),await Os(f),J(`Restarted ${f.title}.`),await b()},[Os,b,dt]),ir=o.useCallback(async f=>{await dt(f,"cancel",{reason:"cancel_from_dashboard"}),J(`Cancel requested: ${f.title}`),await b()},[b,dt]),Ln=o.useCallback(async f=>{var Ge;const N=await fetch(`/orgx/api/runs/${encodeURIComponent(f.runId)}/checkpoints`,{method:"GET"});if(!N.ok){const Pe=await N.json().catch(()=>null);throw new Error((Pe==null?void 0:Pe.error)??`Checkpoint list failed (${N.status})`)}const $=await N.json().catch(()=>null),je=(Ge=(Array.isArray($)?$:Array.isArray($==null?void 0:$.data)?$.data:[]).map(Pe=>({id:typeof Pe.id=="string"?Pe.id:"",createdAt:typeof Pe.createdAt=="string"?Pe.createdAt:typeof Pe.created_at=="string"?Pe.created_at:""})).filter(Pe=>Pe.id.length>0).sort((Pe,_e)=>Date.parse(_e.createdAt)-Date.parse(Pe.createdAt))[0])==null?void 0:Ge.id;if(!je)throw new Error("No checkpoint available for rollback.");await dt(f,"rollback",{checkpointId:je,reason:"rollback_from_dashboard"}),J(`Rollback requested for ${f.title}.`),await b()},[b,dt]),rr=o.useCallback(async()=>{var $;if(!nn||Zn.trim().length===0||Ot)return;pn(!0);const f=nn.type,N=Zn.trim();try{const _={type:f,title:N,status:"active"};if(f==="workstream"){const je=nn.initiativeId??(un==null?void 0:un.initiativeId)??(($=Vt[0])==null?void 0:$.id)??null;if(!je){J("Select an initiative first to start a workstream."),pn(!1);return}_.initiative_id=je,_.parentId=je}const Ie=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)});if(!Ie.ok){const je=await Ie.json().catch(()=>null);throw new Error((je==null?void 0:je.error)??`Failed to create ${f}.`)}J(`Created ${f}: ${N}`),ts(),await b()}catch(_){J(sn(_ instanceof Error?_.message:"",`Failed to create ${f}.`)),pn(!1)}},[ts,Ot,nn,Zn,Vt,b,un==null?void 0:un.initiativeId]),qs=o.useCallback(f=>{Tt({type:"initiative"}),es((f==null?void 0:f.trim())??""),pn(!1)},[]),Bs=o.useCallback(()=>{qs()},[qs]),Fs=o.useCallback(f=>{ds("workstream",f)},[ds]);o.useCallback(()=>{var f;return Fs((un==null?void 0:un.initiativeId)??((f=Vt[0])==null?void 0:f.id)??null)},[Vt,un==null?void 0:un.initiativeId,Fs]);const wi=o.useCallback(f=>{const N=[...D].filter($=>($.initiativeId??$.groupId)===f.id).sort(Ra)[0];N&&(pe(N.id),De(N.id),de(null),C(null),J(`Focused initiative: ${f.name}`))},[D]),mn=o.useCallback(f=>{const N=Vt.find($=>$.id===f)??ps.find($=>$.id===f)??null;N&&wi(N)},[wi,Vt,ps]),jn=o.useCallback(f=>{const N=(f??"").trim();g("activity"),gt("initiatives"),et("initiatives"),vt("in_progress"),he("needs_attention"),Ee(N.length>0?N:null),J(N.length>0?"Reviewing pending decision.":"Review needs attention.")},[g]),ar=o.useCallback(f=>{const N=new Set,$=(f.runId??"").trim();$.length>0&&N.add($),N.add(f.sliceRunId);const _=new Map;for(const _e of ee){const m=Tr(_e),x=Ol(_e);(m&&N.has(m)||x&&x===f.sliceRunId)&&_.set(_e.id,_e)}const Ie=Array.from(_.values()),je=_e=>{const m=_e.type.trim().toLowerCase();let x=0;return(m==="decision_requested"||m==="blocker_created")&&(x+=80),(m==="run_failed"||m==="autopilot_stopped")&&(x+=70),(m.includes("slice_completed")||m.includes("completed"))&&(x+=60),m.includes("artifact")&&(x+=55),(m.includes("progress")||m.includes("update"))&&(x+=35),x+=Math.floor(rn(_e.timestamp)/1e3),x};Ie.sort((_e,m)=>je(m)-je(_e));const Ge=Ie[0]??null;g("activity"),et("activity"),gt("initiatives");const Pe=($?D.find(_e=>_e.runId===$||_e.id===$)??null:null)??(f.initiativeId&&f.workstreamId?D.find(_e=>_e.initiativeId===f.initiativeId&&_e.workstreamId===f.workstreamId)??null:null);if(Pe?(pe(Pe.id),De(Pe.id),de(null),C(null)):f.workstreamId&&(De(null),de(f.workstreamId),C(f.workstreamTitle??"Work slice")),Ge!=null&&Ge.id){be(Ge.id),J(`Reviewing activity for ${f.workstreamTitle??"work slice"}.`);return}if(f.primaryAction==="resolve_decision"){jn();return}if($.length>0){ms($),J("Opened the related work session. Timeline details were unavailable.");return}J("No activity details were found for this slice yet.")},[ee,ms,jn,D,g]);return o.useCallback(f=>{const N=new Set(f),$=[...D].filter(_=>N.has(_.status)).sort(Ra)[0];if(!$){J("No matching sessions for that metric right now.");return}Nn($.id),et("activity")},[D,Nn]),o.useCallback(f=>{c==="activity"&&(f==="sessions"||f==="active"||f==="blocked"||f==="failed"||f==="decisions"||f==="outbox"||f==="handoffs")&&V(f)},[c]),M?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:L.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((f,N)=>n.jsx("div",{className:"shimmer-skeleton h-7 w-24 rounded-full"},N))})]}),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}})]})]})]}):B?n.jsx(kg,{workspaceLabel:h,suggestedTitle:(Mt==null?void 0:Mt.title)??null,sessionSummary:(Mt==null?void 0:Mt.lastEventSummary)??null,onCreateInitiative:()=>qs(),onCreateFromSession:()=>qs((Mt==null?void 0:Mt.title)??null),onOpenSandbox:()=>{En(!0),e.skipGate()},onOpenSettings:()=>Jt("orgx"),onRefresh:()=>{e.refreshStatus(),b()}}):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:L.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(rx,{}),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(mm,{color:$g[I.connection],pulse:I.connection==="connected",title:[`Status: ${Pl[I.connection]??I.connection}`,I.connection==="connected"?"Meaning: receiving live updates.":I.connection==="reconnecting"?"Meaning: retrying live stream (data may be stale).":"Meaning: offline (data is stale).",`Last snapshot: ${qg(I.lastSnapshotAt)}`,Bn?`Details: ${Bn.message}`:null].filter(Boolean).join(`
212
+ `),children:Pl[I.connection]??"Unknown"}),(xn>0||yn>0||Rn>0||is>0)&&n.jsx(sl,{className:"hidden md:flex",running:xn,blocked:yn,decisionsCount:Rn,completedToday:is,onDecisionsClick:()=>{g("activity"),gt("initiatives"),et("initiatives"),vt("in_progress"),he("needs_attention")},onBlockedClick:()=>{qe.length>0?(g("mission-control"),vt("in_progress"),he("needs_attention")):V("blocked")},onNewInitiative:Bs})]}),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:()=>g("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:()=>g("mission-control"),onMouseEnter:z,onFocus:z,"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:f=>{const N=f.target.value;p(N==="__all__"?null:N)},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"}),w.map(f=>n.jsx("option",{value:f.id,children:f.title},f.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"})})]}),I.lastActivity&&n.jsxs("span",{className:"hidden text-body text-secondary xl:inline",children:["Last activity: ",I.lastActivity]}),t&&n.jsx("button",{type:"button",onClick:()=>{En(!1),Jn()},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 guided sandbox",children:"Exit sandbox"}),n.jsxs("button",{type:"button",ref:le,onClick:()=>Q(f=>!f),title:"Notifications","aria-haspopup":"dialog","aria-expanded":We,"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"})]}),it.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:it.length})]}),a?n.jsx("button",{type:"button",onClick:()=>Qe(!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:()=>Jt("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:b,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"})]}),We&&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:[it.length>0&&n.jsx("button",{type:"button",onClick:ws,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>Q(!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:xn,blocked:yn,decisionsCount:Rn,completedToday:is,onDecisionsClick:()=>{g("activity"),et("initiatives"),gt("initiatives"),vt("in_progress"),he("needs_attention"),Q(!1)},onBlockedClick:()=>{qe.length>0?(g("mission-control"),vt("in_progress"),he("needs_attention")):V("blocked"),Q(!1)}})}),it.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:se>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:it.map(f=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:f.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:f.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:f.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(an,{type:f.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:f.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:f.message}),f.onAction&&n.jsx("button",{type:"button",onClick:()=>{var N;(N=f.onAction)==null||N.call(f),Q(!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:f.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>Yi(f.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"})]})},f.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:f=>{const N=f.target.value;p(N==="__all__"?null:N)},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"}),w.map(f=>n.jsx("option",{value:f.id,children:f.title},f.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:()=>g("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:()=>g("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(Ig,{initiatives:ps,activities:ee,agents:Ji,runtimeInstances:I.runtimeInstances??[],workspaceInitiativeId:u,isLoading:M,authToken:null,embedMode:!1,connection:I.connection,lastSnapshotAt:I.lastSnapshotAt,error:F,hasApiKey:e.state.hasApiKey,devMode:a,onOpenSettings:()=>Jt("orgx"),onRefresh:b,onCreateInitiative:Bs,onPlayNextUp:er,onStartAutopilot:$s,nextUpQueueModel:at,nextUpActionsModel:st,snapshotVersion:I.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 ${Re!=="agents"?"hidden lg:flex":""}`,children:n.jsx(wf,{sessions:I.sessions,activity:ee,runtimeInstances:I.runtimeInstances??[],showSyntheticEntities:t||i,selectedSessionId:Ce,onSelectSession:Nn,onAgentFilter:Be,agentFilter:ze,timeFilterId:K,onReconnect:Jn,onLaunched:b,connectionStatus:I.connection,autopilotState:Rs})}),n.jsx("section",{className:`min-h-0 lg:col-span-6 lg:flex lg:flex-col lg:[&>section]:h-full ${Re!=="activity"?"hidden lg:flex":""}`,children:n.jsx(wg,{activity:vs.items,sessions:D,sliceRuns:qe,initiatives:Vt,timelineNarrative:I.timelineNarrative??[],workspaceId:u,chatSnapshot:I.chat,devMode:a,selectedRunIds:qn,selectedSessionLabel:Fn,selectedWorkstreamId:Te,selectedWorkstreamLabel:we,agentFilter:ze,timeFilterId:K,onTimeFilterChange:sa,customTimeRange:Oe,onCustomTimeRangeChange:me,hasMore:vs.hasMore,isLoadingMore:vs.isLoadingMore,onLoadMore:vs.loadMore,onClearSelection:Ls,onClearWorkstreamFilter:Ds,onClearAgentFilter:us,onFocusRunId:ms,onOpenDecision:jn,onResolveDecision:Kt,requestedActivityItemId:T,onActivityItemRequestHandled:()=>be(null),onPlayNextUp:er,onStartAutopilot:$s,onPauseWorkstream:yi,onCreateInitiative:Bs,onOpenMissionControl:()=>g("mission-control"),onOpenNextUp:()=>g("mission-control"),onOpenSettings:()=>Jt("orgx"),onRefreshData:b,isLoading:M})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${Re!=="decisions"&&Re!=="initiatives"?"hidden lg:flex":""}`,children:n.jsx("div",{className:`min-h-0 ${ct==="initiatives"?"flex-1":"flex-shrink-0"} `,children:ct==="initiatives"?n.jsxs(Ss,{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":mt==="in_progress",onClick:f=>{f.stopPropagation(),vt("in_progress")},className:ue("relative inline-flex h-8 items-center gap-1.5 px-0.5 text-caption font-semibold transition-colors",mt==="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:Ps}),n.jsx("span",{className:ue("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-lime transition-opacity",mt==="in_progress"?"opacity-100":"opacity-0")})]}),n.jsxs("button",{type:"button",role:"tab","aria-selected":mt==="next_up",onClick:f=>{f.stopPropagation(),vt("next_up")},className:ue("relative inline-flex h-8 items-center gap-1.5 px-0.5 text-caption font-semibold transition-colors",mt==="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:Ms}),n.jsx("span",{className:ue("pointer-events-none absolute -bottom-px left-0 right-0 h-[2px] rounded-full bg-lime transition-opacity",mt==="next_up"?"opacity-100":"opacity-0")})]})]}),n.jsxs("button",{type:"button",onClick:()=>{ia().catch(f=>{J(sn(f instanceof Error?f.message:"","Autopilot action failed."))})},disabled:ht,className:"control-pill inline-flex h-8 items-center gap-1.5 px-2.5 text-caption font-semibold disabled:opacity-45","data-tone":ei,"data-state":Es,title:bs,"aria-label":bs,children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:ue("h-3.5 w-3.5",hn?"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",dn==="blocked"?"bg-amber-400/18 text-amber-100":hn?"bg-lime/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:Yn})]})]}),mt==="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:()=>he("all"),className:ue("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",X==="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:Ps})]}),n.jsxs("button",{type:"button",onClick:()=>he("needs_attention"),className:ue("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",X==="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:ss})]}),n.jsxs("button",{type:"button",onClick:()=>he("completed"),className:ue("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",X==="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:mt==="in_progress"?X==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[Dt.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(Ag,{model:Dt,actions:Rt,onOpenDetail:Gn})})}),ve?n.jsxs("section",{className:ue("overflow-hidden rounded-xl border border-subtle bg-white/[0.02]",gn.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:I.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(jg,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:I.decisions,focusDecisionId:Y,onFocusDecisionHandled:()=>Ee(null),onApproveDecision:A,onRejectDecision:H,onApproveAll:j,onBulkDecisionAction:P,mutationState:Z,initiativeNames:Et})})})]}):n.jsx(Ss,{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:ve?"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:gn.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(mp,{className:ue("h-full min-h-0"),title:ve?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:qe,initiatives:Vt,onOpenDecisions:()=>jn(),onFocusRunId:ms,onReviewActivity:ar,onOpenSliceDetail:wt})})]})]}):X==="completed"?n.jsx(gp,{rows:nt,onFocusRunId:ms,onOpenNextUp:()=>vt("next_up")}):n.jsx(tp,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:D,sliceRuns:qe,initiatives:Vt,needsAttentionCount:ss,onSwitchToNeedsAttention:()=>he("needs_attention"),onOpenSession:Nn,onFocusRunId:ms,onPlayWorkstream:Os,onPauseWorkstream:yi,onResumeWorkstream:Os,onRestartSession:sr,onIntervene:Xi,onOpenSliceDetail:Qt}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Sg,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:at,queueActions:st,snapshotVersion:I.snapshotVersion,excludeRunning:!0,onOpenInitiative:mn,onOpenSliceDetail:xt})})},`${mt}:${X}`)]}):n.jsx(Ss,{className:"card-enter",children:n.jsxs("button",{onClick:()=>gt("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(Nt,{children:Ae&&un&&n.jsxs(n.Fragment,{children:[n.jsx(ce.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:()=>re(!1)},"session-drawer-backdrop"),n.jsx(ce.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:L.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(Ng,{session:un,activity:ee,initiatives:Vt,sliceRuns:qe,initialInterventionDraft:ne,onSubmitIntervention:yt,onOpenActivityItem:na,onContinueHighestPriority:Zi,onDispatchSession:tr,onPauseSession:nr,onResumeSession:vi,onCancelSession:ir,onCreateCheckpoint:bi,onRollbackSession:Ln,onStartInitiative:Bs,onStartWorkstream:Fs,onClose:()=>re(!1)})})})},"session-drawer-panel")]})}),c==="activity"?n.jsx(fm,{activeTab:Re,onTabChange:jt,pendingDecisionCount:ve?I.decisions.length:0}):null,n.jsx(Zr,{open:nn!==null,onClose:ts,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:(nn==null?void 0:nn.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(nn==null?void 0:nn.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:Zn,onChange:f=>es(f.target.value),onKeyDown:f=>{f.key==="Enter"&&rr()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(nn==null?void 0:nn.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-lime/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:ts,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:rr,disabled:Zn.trim().length===0||Ot,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:Ot?"Creating…":"Create"})]})]})}),Ve.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Cg,{open:Ve.open,onClose:()=>Ye(f=>({...f,open:!1,focusAgentDomain:null})),activeTab:Ve.tab,onChangeTab:f=>Ye(N=>({...N,tab:f})),agentBehaviorInitialDomain:Ve.focusAgentDomain,demoMode:t,onToggleDemoMode:f=>{En(f),f||Jn()},devMode:a,onToggleDevMode:l,showSyntheticEntities:i,onToggleShowSyntheticEntities:r,workspaceOptions:w,selectedWorkspaceId:u,onSelectWorkspace:p,onboarding:e,authToken:null,embedMode:!1})}),a&&fe&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Pg,{open:fe,selectedWorkspaceId:u,onClose:()=>Qe(!1)})}),(ie==="sessions"||ie==="active"||ie==="blocked"||ie==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Tg,{open:ie==="sessions"||ie==="active"||ie==="blocked"||ie==="failed",onClose:()=>V(null),mode:ie==="active"||ie==="blocked"||ie==="failed"?ie:"sessions",sessions:D,onOpenSession:f=>{Nn(f.id),V(null)},onRunAction:async(f,N)=>{await dt(f,N,{reason:`bulk_${N}_from_header`})},onRefetch:async()=>b(),onSetNotice:f=>J(f)})}),ie==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Mg,{open:ie==="decisions",onClose:()=>V(null),decisions:ve?I.decisions:[],onApproveDecision:A,onRejectDecision:H,onApproveAll:j,onBulkDecisionAction:P})}),ie==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Eg,{open:ie==="outbox",onClose:()=>V(null),outbox:I.outbox,onOpenSettings:()=>{V(null),Jt("orgx")},onRefresh:()=>{b()}})}),ie==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Rg,{open:ie==="handoffs",onClose:()=>V(null),handoffs:I.handoffs})}),n.jsx(ax,{}),Yt&&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(_g,{item:Yt,actions:Rt,onClose:()=>kn(null),onNavigate:Xn,currentIndex:ys,totalCount:$t.length,decisions:ve?I.decisions:void 0,onApproveDecision:A,onRejectDecision:H})})})}),Xe&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Dg,{target:Xe,initiatives:Vt,onClose:()=>He(null),onPlayWorkstream:async(f,N,$)=>{try{const _=await at.playWorkstream({initiativeId:f,workstreamId:N,agentId:$??void 0});await Promise.all([at.refetch(),b()]),typeof _.sessionId=="string"&&_.sessionId.trim().length>0&&U(_.sessionId.trim()),J(_.dispatchMode==="pending"?"Dispatching workstream…":"Started workstream.")}catch(_){J(sn(_ instanceof Error?_.message:null,"Failed to dispatch workstream"))}},onStartAutoContinue:async(f,N,$)=>{try{await st.move({initiativeId:f,workstreamId:N,placement:"top"});const _=await at.startWorkstreamAutoContinue({initiativeId:f,workstreamId:N,agentId:$??void 0,scope:"initiative"}),Ie=Ul(_);await Promise.all([at.refetch(),b()]),Ie&&U(Ie),J(Ie?"Auto-continue started.":"Auto-continue is dispatching now.")}catch(_){J(sn(_ instanceof Error?_.message:null,"Failed to start auto-continue"))}},onMoveWorkstream:async(f,N,$)=>{try{await st.move({initiativeId:f,workstreamId:N,placement:$}),J(`Moved workstream to ${$}.`),b()}catch(_){J(sn(_ instanceof Error?_.message:null,"Move failed"))}},onRemoveFromQueue:async(f,N)=>{try{await st.remove({initiativeId:f,workstreamId:N}),J("Removed workstream from queue."),b()}catch($){J(sn($ instanceof Error?$.message:null,"Remove failed"))}},onOpenSession:Nn,onFocusRunId:ms,onOpenInitiative:mn,onReviewActivity:ar,onOpenDecisions:()=>jn(),onAcceptSlice:At,onRejectSlice:Pt})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});gu();const lx=new nd({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});ed.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(sd,{client:lx,children:n.jsx(nx,{})})}));export{em as $,Zt as A,Ts as B,ue as C,Wt as D,an as E,Hn as F,As as G,qu as H,jx as I,bx as J,vx as K,wx as L,qi as M,Is as N,_s as O,Ss as P,Ef as Q,xx as R,Wn as S,Pn as T,Iu as U,Bt as V,cc as W,eo as X,ea as Y,Nx as Z,Zu as _,Nu as a,dc as a0,om as a1,kx as a2,bd as a3,yx as a4,fc as a5,Ix as a6,fr as a7,Am as a8,Sm as a9,Yp as aa,gx as ab,ji as ac,Mm as ad,Br as ae,Ut as b,Oa as c,bp as d,nu as e,L as f,Ex as g,en as h,Kn as i,Tx as j,Kp as k,Vs as l,Ax as m,Xt as n,vc as o,xa as p,cs as q,Sx as r,Mx as s,vp as t,Bu as u,Cx as v,qt as w,_x as x,Di as y,Zr as z};