orc-ai 0.1.48 → 0.1.49

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 (121) hide show
  1. package/README.md +1059 -0
  2. package/dist/index.js +514 -494
  3. package/dist/web/assets/{Agents-jr4tBoaK.js → Agents-C8dJX8px.js} +3 -3
  4. package/dist/web/assets/{Attention-C1CBdN6r.js → Attention-BHYo8Lwr.js} +2 -2
  5. package/dist/web/assets/{Audit-CHGMGiUH.js → Audit-CS_DZkbJ.js} +1 -1
  6. package/dist/web/assets/ConfirmDialog-CrSa87VF.js +1 -0
  7. package/dist/web/assets/Dashboard-V813oIhq.js +1 -0
  8. package/dist/web/assets/{DocumentWorkspace-Bw6NaR0Q.js → DocumentWorkspace-CNyVQTjg.js} +1 -1
  9. package/dist/web/assets/EmptyState-Ctm7L70B.js +1 -0
  10. package/dist/web/assets/ErrorState-BPTepwiG.js +1 -0
  11. package/dist/web/assets/{FileEditor-BWeo_YzB.js → FileEditor-Dh29_xCL.js} +1 -1
  12. package/dist/web/assets/JobWebhooks-TvAY8p1V.js +1 -0
  13. package/dist/web/assets/{Jobs-BYlPCj8c.js → Jobs-C5ggSs2T.js} +3 -3
  14. package/dist/web/assets/{Knowledge-DsOJpZd5.js → Knowledge-BpiN3iVE.js} +3 -3
  15. package/dist/web/assets/{PackageCatalog-CnsavTBo.js → PackageCatalog-B1U3vfhW.js} +5 -5
  16. package/dist/web/assets/{Pager-DCsiS5yC.js → Pager-ClYYU9et.js} +1 -1
  17. package/dist/web/assets/PriorityBadge-BW-A50LE.js +1 -0
  18. package/dist/web/assets/Projects-DRao5Qpk.js +3 -0
  19. package/dist/web/assets/ResumeActions-DHTOr6GQ.js +11 -0
  20. package/dist/web/assets/{Rules-K9XzeBoM.js → Rules-DGKsAbTf.js} +2 -2
  21. package/dist/web/assets/{Sessions-DVFKv-nY.js → Sessions-CWHU6sYy.js} +3 -3
  22. package/dist/web/assets/{Settings-DRFRwAzC.js → Settings-yW1S2q4F.js} +5 -5
  23. package/dist/web/assets/{Skills-794QsmRr.js → Skills-BwdXE5nT.js} +4 -4
  24. package/dist/web/assets/SourceEditor-ft02z20v.js +43 -0
  25. package/dist/web/assets/StatusBadge-C5G1fdZh.js +1 -0
  26. package/dist/web/assets/TaskDetailSheet-fUSHPFB-.js +11 -0
  27. package/dist/web/assets/{Tasks-DPjDT6DJ.js → Tasks-uRqvmLz7.js} +9 -9
  28. package/dist/web/assets/{Terminals-BAT8w5fU.js → Terminals-W5nszLI1.js} +6 -6
  29. package/dist/web/assets/ViewHeader-DXR0ZaMO.js +1 -0
  30. package/dist/web/assets/Webhooks-lXLoKWdt.js +1 -0
  31. package/dist/web/assets/{abnfDiagram-VCTEODGH-CU33f3k1.js → abnfDiagram-VCTEODGH-K8P_VxLi.js} +1 -1
  32. package/dist/web/assets/{arc-Cvg6JGGh.js → arc-BOl9BKfD.js} +1 -1
  33. package/dist/web/assets/{architectureDiagram-5GKGNRK7-CCrBayxl.js → architectureDiagram-5GKGNRK7-DIZ15fO5.js} +2 -2
  34. package/dist/web/assets/{blockDiagram-I7D4REHJ-UciymbQJ.js → blockDiagram-I7D4REHJ-DMrufypV.js} +1 -1
  35. package/dist/web/assets/{c4Diagram-7LVT6UL2-z2xI2mL_.js → c4Diagram-7LVT6UL2-BUUxjwvU.js} +1 -1
  36. package/dist/web/assets/channel-CQFNQIhG.js +1 -0
  37. package/dist/web/assets/{chunk-2Q5K7J3B-BKGKI1uz.js → chunk-2Q5K7J3B-wRIxA2_q.js} +1 -1
  38. package/dist/web/assets/{chunk-5VM5RSS4-CLAy5Pjy.js → chunk-5VM5RSS4-B6lAVcgQ.js} +1 -1
  39. package/dist/web/assets/{chunk-F27PBJKO-Ch--IqBe.js → chunk-F27PBJKO-DVuei-Pl.js} +1 -1
  40. package/dist/web/assets/{chunk-IMKFNOWR-Rlkt_DmX.js → chunk-IMKFNOWR-CwyogA-y.js} +1 -1
  41. package/dist/web/assets/{chunk-JWPE2WC7-DaeLNYk7.js → chunk-JWPE2WC7-zdsOarNZ.js} +1 -1
  42. package/dist/web/assets/{chunk-POPQ4Y6H-BnuI44n3.js → chunk-POPQ4Y6H-D3ieeKih.js} +1 -1
  43. package/dist/web/assets/{chunk-SVP7TREG-DvZSQ5NI.js → chunk-SVP7TREG-CmiQdvOH.js} +1 -1
  44. package/dist/web/assets/{chunk-TICWLB2K-DVsqEZRj.js → chunk-TICWLB2K-CieIpfOy.js} +1 -1
  45. package/dist/web/assets/{chunk-XXDRQBXY-DnIZuVZV.js → chunk-XXDRQBXY-BoTHwisB.js} +1 -1
  46. package/dist/web/assets/classDiagram-ZZMXUADV-B5yD90Df.js +1 -0
  47. package/dist/web/assets/classDiagram-v2-VYDZK3BY-B5yD90Df.js +1 -0
  48. package/dist/web/assets/{cose-bilkent-JH36ORCC-Cn03pIS1.js → cose-bilkent-JH36ORCC-CtGsuuTW.js} +1 -1
  49. package/dist/web/assets/{cynefin-OW5HDTMX-Ce0_rfcJ.js → cynefin-OW5HDTMX-vMXgcpgg.js} +1 -1
  50. package/dist/web/assets/{cynefinDiagram-5FMLGOSQ-BmvPd2DO.js → cynefinDiagram-5FMLGOSQ-kMbm5D7e.js} +1 -1
  51. package/dist/web/assets/{dagre-GXQ25YYZ-BI_iESjX.js → dagre-GXQ25YYZ-xmoviGlr.js} +1 -1
  52. package/dist/web/assets/{diagram-S7CK7UJ4-DCkANt02.js → diagram-S7CK7UJ4-CguQzzXs.js} +1 -1
  53. package/dist/web/assets/{diagram-UQ7AKVKN-CJbIrhc6.js → diagram-UQ7AKVKN-CMX0u7Gf.js} +1 -1
  54. package/dist/web/assets/{diagram-VSXAHHWV-BS3wAm8f.js → diagram-VSXAHHWV-cuhv3Fvj.js} +1 -1
  55. package/dist/web/assets/{diagram-VX7I27RA-Bf6ouJud.js → diagram-VX7I27RA-Bp_JbX0e.js} +1 -1
  56. package/dist/web/assets/{diagram-Z3DM3KII-BR7YnYjD.js → diagram-Z3DM3KII-oZ6jRSCd.js} +1 -1
  57. package/dist/web/assets/{download-BvcsHVh_.js → download-UgMvjBjR.js} +1 -1
  58. package/dist/web/assets/{ebnfDiagram-PWID7BFC-BB_duVb2.js → ebnfDiagram-PWID7BFC-DbxnEjb0.js} +1 -1
  59. package/dist/web/assets/{erDiagram-RLTQ6QDP-DVpvqADj.js → erDiagram-RLTQ6QDP-Cl5kXPho.js} +1 -1
  60. package/dist/web/assets/{flowDiagram-HODETNUW-CYCG8Khy.js → flowDiagram-HODETNUW-DueO0Ju6.js} +1 -1
  61. package/dist/web/assets/{folder-open-FLHAqscD.js → folder-open-DojCP5NP.js} +1 -1
  62. package/dist/web/assets/{ganttDiagram-EL5Y4UJY-BXeyk_i8.js → ganttDiagram-EL5Y4UJY-DNjT4iVH.js} +4 -4
  63. package/dist/web/assets/{gitGraphDiagram-WWUBYQGX-KGCo-QoM.js → gitGraphDiagram-WWUBYQGX-B4aUQ9gY.js} +1 -1
  64. package/dist/web/assets/{highlighted-body-KPVGNVTW-_lM_4hwr.js → highlighted-body-KPVGNVTW-gt1u8RcC.js} +1 -1
  65. package/dist/web/assets/index-C_jtMgr7.js +412 -0
  66. package/dist/web/assets/{infoDiagram-27XIBGKW-BXbLlnR-.js → infoDiagram-27XIBGKW-CWcOvNAB.js} +1 -1
  67. package/dist/web/assets/{ishikawaDiagram-5VMMS53U-Bgfr65z9.js → ishikawaDiagram-5VMMS53U-ccIPCUs4.js} +1 -1
  68. package/dist/web/assets/{journeyDiagram-3NMN7TZE-Cceeqsmt.js → journeyDiagram-3NMN7TZE-rRe3uTLu.js} +1 -1
  69. package/dist/web/assets/{kanban-definition-UXKFOSKX-BWdymhtd.js → kanban-definition-UXKFOSKX-tAKCWntJ.js} +1 -1
  70. package/dist/web/assets/{layout-VQYaf5Px.js → layout-7xCiQ5Mn.js} +1 -1
  71. package/dist/web/assets/{linear-C_UKR9_Y.js → linear-WCNhc07o.js} +1 -1
  72. package/dist/web/assets/{list-DZ7tVJxe.js → list-BL4eRkIg.js} +1 -1
  73. package/dist/web/assets/{mermaid-HWGCJPDP-CUN0Fzkf.js → mermaid-HWGCJPDP-C8QwWdo5.js} +6 -6
  74. package/dist/web/assets/{mindmap-definition-YA3MSWOX-skKDKZay.js → mindmap-definition-YA3MSWOX-Cj5-j6a7.js} +1 -1
  75. package/dist/web/assets/{pegDiagram-XKGWAZYB-BBVgKimF.js → pegDiagram-XKGWAZYB-BYB3oVZ_.js} +1 -1
  76. package/dist/web/assets/{pencil-864Hty9z.js → pencil-gxvh59uO.js} +1 -1
  77. package/dist/web/assets/{pieDiagram-E7YTZNPT-DbTfOeVM.js → pieDiagram-E7YTZNPT-CSbpzXas.js} +1 -1
  78. package/dist/web/assets/{quadrantDiagram-AXDQQJYC-GB57kGMj.js → quadrantDiagram-AXDQQJYC-DKTP6jS5.js} +1 -1
  79. package/dist/web/assets/{railroadDiagram-O6MQD6OU-BaWEAljp.js → railroadDiagram-O6MQD6OU-Ct8aPeLX.js} +1 -1
  80. package/dist/web/assets/{refresh-cw-CDVBz6mR.js → refresh-cw-BQRdbjy6.js} +1 -1
  81. package/dist/web/assets/{requirementDiagram-BXWQKSXE-1FhQiz9k.js → requirementDiagram-BXWQKSXE-B9hH69zu.js} +1 -1
  82. package/dist/web/assets/{sankeyDiagram-P5KCCOFB-tQhcHMdz.js → sankeyDiagram-P5KCCOFB-CDqNONxU.js} +1 -1
  83. package/dist/web/assets/{save-cYQVut42.js → save-CYoz3QKB.js} +1 -1
  84. package/dist/web/assets/scroll-area-CU4DGUBA.js +1 -0
  85. package/dist/web/assets/{sequenceDiagram-WJ2MYXX4-CC3gj2gv.js → sequenceDiagram-WJ2MYXX4-BF77J63J.js} +1 -1
  86. package/dist/web/assets/{sizeCapture-INFHLROL-CQ9O8ZCT.js → sizeCapture-INFHLROL-Dpubco_U.js} +1 -1
  87. package/dist/web/assets/{stateDiagram-D77RDMKH-DYKy0trf.js → stateDiagram-D77RDMKH-CzslKEYw.js} +1 -1
  88. package/dist/web/assets/stateDiagram-v2-MP3YSRHH-DKbNjyV-.js +1 -0
  89. package/dist/web/assets/{swimlanes-42K2YHIH-glbk0TBg.js → swimlanes-42K2YHIH-bD_tUjo6.js} +1 -1
  90. package/dist/web/assets/swimlanesDiagram-VR7AAH4N-0wAluWQF.js +8 -0
  91. package/dist/web/assets/table-D3N_5Wee.js +1 -0
  92. package/dist/web/assets/tabs-CSlEXoxD.js +1 -0
  93. package/dist/web/assets/{timeline-definition-24CTP7MA-f6rViR3x.js → timeline-definition-24CTP7MA-owGoHn8z.js} +1 -1
  94. package/dist/web/assets/trash-2-D3Ey4I09.js +6 -0
  95. package/dist/web/assets/{upload-CVOr0xxD.js → upload-DhVOCWST.js} +1 -1
  96. package/dist/web/assets/useDetailRoute-j9nlwack.js +1 -0
  97. package/dist/web/assets/{useJobs-D6xj3XjG.js → useJobs-Dcl-Vim3.js} +1 -1
  98. package/dist/web/assets/{useKnowledge-qKVT26ZM.js → useKnowledge-gIjk0_I1.js} +1 -1
  99. package/dist/web/assets/useListSelection-CSQd_Hmx.js +1 -0
  100. package/dist/web/assets/{useMemories-Cd7-k-Iq.js → useMemories-B8Zpz0Qz.js} +1 -1
  101. package/dist/web/assets/useProjectScope-Dk0mjyHf.js +1 -0
  102. package/dist/web/assets/useSessions-BrdK-12R.js +1 -0
  103. package/dist/web/assets/{vennDiagram-4TSXK5OY-CxG3VgNS.js → vennDiagram-4TSXK5OY-D0_6bldW.js} +1 -1
  104. package/dist/web/assets/view-params-Bm1Qf6KC.js +1 -0
  105. package/dist/web/assets/{wardleyDiagram-VM6X3IG4-ByyivCzx.js → wardleyDiagram-VM6X3IG4-D9GbTBKy.js} +1 -1
  106. package/dist/web/assets/{xychartDiagram-S5SC5T6Z-BVm2sRFs.js → xychartDiagram-S5SC5T6Z-BFqPF2Hl.js} +1 -1
  107. package/dist/web/index.html +1 -1
  108. package/package.json +1 -1
  109. package/dist/checksums.txt +0 -5
  110. package/dist/web/assets/Dashboard-DTwx4Oce.js +0 -1
  111. package/dist/web/assets/JobWebhooks-DjkbxUMt.js +0 -1
  112. package/dist/web/assets/SourceEditor-Bbm17thv.js +0 -14
  113. package/dist/web/assets/Webhooks-CDzbzurB.js +0 -1
  114. package/dist/web/assets/channel-DfI_NPkS.js +0 -1
  115. package/dist/web/assets/classDiagram-ZZMXUADV-BMn0P_qW.js +0 -1
  116. package/dist/web/assets/classDiagram-v2-VYDZK3BY-BMn0P_qW.js +0 -1
  117. package/dist/web/assets/index-CS_oHx6f.js +0 -468
  118. package/dist/web/assets/scroll-area-DQvJ9JpU.js +0 -1
  119. package/dist/web/assets/stateDiagram-v2-MP3YSRHH-BKFrUA7i.js +0 -1
  120. package/dist/web/assets/swimlanesDiagram-VR7AAH4N-C6lvE7xF.js +0 -8
  121. package/dist/web/assets/useProjectScope-Duh5p4ZM.js +0 -1
@@ -1,4 +1,4 @@
1
- var Jt=Object.defineProperty;var jt=(n,B,e)=>B in n?Jt(n,B,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[B]=e;var F=(n,B,e)=>jt(n,typeof B!="symbol"?B+"":B,e);import{bI as W,bJ as pB,bK as KB,bL as LB,bM as At,bN as lB,bO as eB,bP as Lt,bQ as vB,bR as Ut,bS as Qe,bT as Ye,r as S,j as c,_ as Y,$ as rB,B as dB,a as Kt,u as qt,o as Qt,a1 as Ve,b as me,d as te,bU as Yt,bV as Vt,bW as ze,bX as Xe,a4 as zt,a5 as Xt,a6 as Zt,a7 as Wt,bY as $t,a8 as Bs,V as es}from"./index-CS_oHx6f.js";import{u as ts}from"./useJobs-D6xj3XjG.js";function Fe(n,B,e,t=[]){return Object.entries(n).map(([s,C])=>({native:s,event:C,block:B.includes(s),context:e.includes(s),rewrite_command:t.includes(s)}))}const ss={PreToolUse:"pre_tool",PostToolUse:"post_tool",PostToolUseFailure:"post_tool_failure",PostToolBatch:"post_tool_batch",SessionStart:"session_start",SessionEnd:"session_end",UserPromptSubmit:"prompt_submit",UserPromptExpansion:"prompt_expansion",Stop:"stop",StopFailure:"stop_failure",SubagentStart:"subagent_start",SubagentStop:"subagent_stop",PreCompact:"pre_compact",PostCompact:"post_compact",PermissionRequest:"permission_request",PermissionDenied:"permission_denied",Notification:"notification",Setup:"setup",TeammateIdle:"teammate_idle",TaskCreated:"task_created",TaskCompleted:"task_completed",Elicitation:"elicitation",ElicitationResult:"elicitation_result",ConfigChange:"config_change",WorktreeRemove:"worktree_remove",InstructionsLoaded:"instructions_loaded",CwdChanged:"cwd_changed",FileChanged:"file_changed",DirectoryAdded:"directory_added",MessageDisplay:"message_display"},ne={claude:Fe(ss,["PreToolUse","PermissionRequest","UserPromptSubmit","UserPromptExpansion","Stop","SubagentStop","TaskCreated","ConfigChange"],["PreToolUse","PostToolUse","PostToolUseFailure","UserPromptSubmit","SessionStart","SubagentStart","UserPromptExpansion","PostToolBatch","Stop","SubagentStop"],["PreToolUse"]),cursor:Fe({sessionStart:"session_start",sessionEnd:"session_end",preToolUse:"pre_tool",postToolUse:"post_tool",postToolUseFailure:"post_tool_failure",subagentStart:"subagent_start",subagentStop:"subagent_stop",beforeShellExecution:"before_shell",afterShellExecution:"after_shell",beforeMCPExecution:"before_mcp",afterMCPExecution:"after_mcp",beforeReadFile:"before_read",afterFileEdit:"after_edit",beforeSubmitPrompt:"prompt_submit",preCompact:"pre_compact",stop:"stop",afterAgentResponse:"agent_response",afterAgentThought:"agent_thought",beforeTabFileRead:"before_tab_read",afterTabFileEdit:"after_tab_edit",workspaceOpen:"workspace_open"},["preToolUse","beforeShellExecution","beforeMCPExecution","beforeReadFile","beforeTabFileRead","beforeSubmitPrompt","subagentStart"],["sessionStart"]),gemini:Fe({BeforeTool:"pre_tool",AfterTool:"post_tool",BeforeAgent:"prompt_submit",AfterAgent:"stop",BeforeModel:"before_model",AfterModel:"after_model",BeforeToolSelection:"before_tool_selection",SessionStart:"session_start",SessionEnd:"session_end",PreCompress:"pre_compact",Notification:"notification"},["BeforeTool","BeforeAgent","AfterAgent","BeforeModel"],["SessionStart","BeforeAgent","BeforeTool","AfterTool","AfterAgent"]),codex:Fe({PreToolUse:"pre_tool",PermissionRequest:"permission_request",PostToolUse:"post_tool",PreCompact:"pre_compact",PostCompact:"post_compact",UserPromptSubmit:"prompt_submit",SubagentStart:"subagent_start",SubagentStop:"subagent_stop",SessionStart:"session_start",SessionEnd:"session_end",Stop:"stop",Interrupt:"interrupt"},["PreToolUse"],["PreToolUse","PostToolUse","UserPromptSubmit","SessionStart","SubagentStart"])};function bt(n,B){if(["claude","codex"].includes(n)&&["runtime:permission_request","runtime:question_request"].includes(B))return{native:"",event:B,block:!0,context:!0,rewrite_command:!1};const e=ne[n];return e==null?void 0:e.find(t=>t.event===B||`native:${t.native}`===B)}/*!
1
+ var Jt=Object.defineProperty;var jt=(n,B,e)=>B in n?Jt(n,B,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[B]=e;var F=(n,B,e)=>jt(n,typeof B!="symbol"?B+"":B,e);import{b0 as W,b1 as pB,b2 as KB,b3 as LB,b4 as At,b5 as lB,b6 as eB,b7 as Lt,b8 as vB,b9 as Ut,ba as Qe,bb as Ye,r as S,j as c,p as Y,I as rB,B as dB,a as Kt,u as qt,e as Qt,b as me,d as te,a8 as Yt,a9 as Vt,aa as zt,ab as Xt,bc as Zt,ac as Wt}from"./index-C_jtMgr7.js";import{V as $t}from"./ViewHeader-DXR0ZaMO.js";import{T as Bs,a as es,b as Ve,c as ze}from"./tabs-CSlEXoxD.js";import{u as Xe}from"./view-params-Bm1Qf6KC.js";import{u as ts}from"./useJobs-Dcl-Vim3.js";function Fe(n,B,e,t=[]){return Object.entries(n).map(([s,C])=>({native:s,event:C,block:B.includes(s),context:e.includes(s),rewrite_command:t.includes(s)}))}const ss={PreToolUse:"pre_tool",PostToolUse:"post_tool",PostToolUseFailure:"post_tool_failure",PostToolBatch:"post_tool_batch",SessionStart:"session_start",SessionEnd:"session_end",UserPromptSubmit:"prompt_submit",UserPromptExpansion:"prompt_expansion",Stop:"stop",StopFailure:"stop_failure",SubagentStart:"subagent_start",SubagentStop:"subagent_stop",PreCompact:"pre_compact",PostCompact:"post_compact",PermissionRequest:"permission_request",PermissionDenied:"permission_denied",Notification:"notification",Setup:"setup",TeammateIdle:"teammate_idle",TaskCreated:"task_created",TaskCompleted:"task_completed",Elicitation:"elicitation",ElicitationResult:"elicitation_result",ConfigChange:"config_change",WorktreeRemove:"worktree_remove",InstructionsLoaded:"instructions_loaded",CwdChanged:"cwd_changed",FileChanged:"file_changed",DirectoryAdded:"directory_added",MessageDisplay:"message_display"},ne={claude:Fe(ss,["PreToolUse","PermissionRequest","UserPromptSubmit","UserPromptExpansion","Stop","SubagentStop","TaskCreated","ConfigChange"],["PreToolUse","PostToolUse","PostToolUseFailure","UserPromptSubmit","SessionStart","SubagentStart","UserPromptExpansion","PostToolBatch","Stop","SubagentStop"],["PreToolUse"]),cursor:Fe({sessionStart:"session_start",sessionEnd:"session_end",preToolUse:"pre_tool",postToolUse:"post_tool",postToolUseFailure:"post_tool_failure",subagentStart:"subagent_start",subagentStop:"subagent_stop",beforeShellExecution:"before_shell",afterShellExecution:"after_shell",beforeMCPExecution:"before_mcp",afterMCPExecution:"after_mcp",beforeReadFile:"before_read",afterFileEdit:"after_edit",beforeSubmitPrompt:"prompt_submit",preCompact:"pre_compact",stop:"stop",afterAgentResponse:"agent_response",afterAgentThought:"agent_thought",beforeTabFileRead:"before_tab_read",afterTabFileEdit:"after_tab_edit",workspaceOpen:"workspace_open"},["preToolUse","beforeShellExecution","beforeMCPExecution","beforeReadFile","beforeTabFileRead","beforeSubmitPrompt","subagentStart"],["sessionStart"]),gemini:Fe({BeforeTool:"pre_tool",AfterTool:"post_tool",BeforeAgent:"prompt_submit",AfterAgent:"stop",BeforeModel:"before_model",AfterModel:"after_model",BeforeToolSelection:"before_tool_selection",SessionStart:"session_start",SessionEnd:"session_end",PreCompress:"pre_compact",Notification:"notification"},["BeforeTool","BeforeAgent","AfterAgent","BeforeModel"],["SessionStart","BeforeAgent","BeforeTool","AfterTool","AfterAgent"]),codex:Fe({PreToolUse:"pre_tool",PermissionRequest:"permission_request",PostToolUse:"post_tool",PreCompact:"pre_compact",PostCompact:"post_compact",UserPromptSubmit:"prompt_submit",SubagentStart:"subagent_start",SubagentStop:"subagent_stop",SessionStart:"session_start",SessionEnd:"session_end",Stop:"stop",Interrupt:"interrupt"},["PreToolUse"],["PreToolUse","PostToolUse","UserPromptSubmit","SessionStart","SubagentStart"])};function bt(n,B){if(["claude","codex"].includes(n)&&["runtime:permission_request","runtime:question_request"].includes(B))return{native:"",event:B,block:!0,context:!0,rewrite_command:!1};const e=ne[n];return e==null?void 0:e.find(t=>t.event===B||`native:${t.native}`===B)}/*!
2
2
  * re2js
3
3
  * RE2JS is the JavaScript port of RE2, a regular expression engine that provides linear time matching
4
4
  *
@@ -25,4 +25,4 @@ var Jt=Object.defineProperty;var jt=(n,B,e)=>B in n?Jt(n,B,{enumerable:!0,config
25
25
  `),g.CODES.get(`
26
26
  `)));let i=!0;for(;!B.more()||B.peek()!==g.CODES.get("]")||i;){if(B.more()&&B.lookingAt("-")&&(this.flags&m.PERL_X)===0&&!i){const D=B.rest();if(D==="-"||!D.startsWith("-]"))throw B.rewindTo(e),new U(O.ERR_INVALID_CHAR_RANGE,B.rest())}i=!1;const r=B.pos();if(B.lookingAt("[:")){if(this.parseNamedClass(B,s))continue;B.rewindTo(r)}if(this.parseUnicodeClass(B,s)||this.parsePerlClassEscape(B,s))continue;B.rewindTo(r);const a=O.parseClassChar(B,e);let u=a;if(B.more()&&B.lookingAt("-")){if(B.skip(1),B.more()&&B.lookingAt("]"))B.skip(-1);else if(u=O.parseClassChar(B,e),u<a)throw new U(O.ERR_INVALID_CHAR_RANGE,B.from(r))}(this.flags&m.FOLD_CASE)===0?s.appendRange(a,u):s.appendFoldedRange(a,u)}B.skip(1),s.cleanClass(),C<0&&s.negateClass(),t.runes=s.toArray(),this.push(t)}},F(O,"ERR_INTERNAL_ERROR","regexp/syntax: internal error"),F(O,"ERR_INVALID_CHAR_RANGE","invalid character class range"),F(O,"ERR_INVALID_ESCAPE","invalid escape sequence"),F(O,"ERR_INVALID_NAMED_CAPTURE","invalid named capture"),F(O,"ERR_INVALID_PERL_OP","invalid or unsupported Perl syntax"),F(O,"ERR_INVALID_REPEAT_OP","invalid nested repetition operator"),F(O,"ERR_INVALID_REPEAT_SIZE","invalid repeat count"),F(O,"ERR_MISSING_BRACKET","missing closing ]"),F(O,"ERR_MISSING_PAREN","missing closing )"),F(O,"ERR_MISSING_REPEAT_ARGUMENT","missing argument to repetition operator"),F(O,"ERR_TRAILING_BACKSLASH","trailing backslash at end of expression"),F(O,"ERR_DUPLICATE_NAMED_CAPTURE","duplicate capture group name"),F(O,"ERR_UNEXPECTED_PAREN","unexpected )"),F(O,"ERR_NESTING_DEPTH","expression nests too deeply"),F(O,"ERR_LARGE","expression too large"),F(O,"ERR_INVALID_CAPTURE_IN_LOOKBEHIND","invalid capture in lookbehind"),F(O,"MAX_HEIGHT",1e3),F(O,"MAX_SIZE",3355443),F(O,"MAX_RUNES",33554432),F(O,"ANY_TABLE",new o(new Uint32Array([0,G.MAX_RUNE,1]))),F(O,"ASCII_TABLE",new o(new Uint32Array([0,127,1]))),F(O,"ASCII_FOLD_TABLE",new o(new Uint32Array([0,127,1,383,383,1,8490,8490,1]))),O),Ls=class RB{static initTest(B){const e=RB.compile(B),t=new RB(e.expr,e.prog,e.numSubexp,e.longest);return t.cond=e.cond,t.prefix=e.prefix,t.prefixUTF8=e.prefixUTF8,t.prefixComplete=e.prefixComplete,t.prefixRune=e.prefixRune,t.prefilter=e.prefilter,t}static compile(B){return RB.compileImpl(B,m.PERL,!1)}static compilePOSIX(B){return RB.compileImpl(B,m.POSIX,!0)}static compileImpl(B,e,t){let s=As.parse(B,e);const C=s.maxCap();s=Ns.simplify(s);const i=Is.build(s),r=Gs.compileRegexp(s),a=new RB(B,r,C,t);a.prefilter=i.type===P.Type.NONE?null:i;const[u,D]=r.prefix();return a.prefixComplete=u,a.prefix=D,a.prefixUTF8=A.stringToUtf8ByteArray(a.prefix),a.prefix.length>0&&(a.prefixRune=a.prefix.codePointAt(0)),a.namedGroups=s.namedGroups,a}static match(B,e){return RB.compile(B).match(e)}constructor(B,e,t=0,s=0){this.expr=B,this.prog=e,this.numSubexp=t,this.longest=s,this.cond=e.startCond(),this.prefix=null,this.prefixUTF8=null,this.prefixComplete=!1,this.prefixRune=0,this.machinePool=[],this.dfa=new hs(this.prog),this.onepass=tt.compile(this.prog),this.prefilter=null}matchPrefixComplete(B,e,t,s){if((t===m.ANCHOR_START||t===m.ANCHOR_BOTH)&&e!==0)return null;let C=-1,i=-1;const r=B.prefixLength(this);if(t===m.UNANCHORED){const a=B.index(this,e);if(a<0)return null;C=e+a,i=C+r}else if(t===m.ANCHOR_BOTH){if(B.endPos()!==r||B.index(this,0)!==0)return null;C=0,i=r}else if(t===m.ANCHOR_START){if(B.index(this,0)!==0)return null;C=0,i=r}if(C<0)return null;if(s>0){const a=new Int32Array(s).fill(-1);return a[0]=C,a[1]=i,Array.from(a)}return[]}executeEngine(B,e,t,s){if(this.prefixComplete&&(s===0||this.numSubexp===0))return this.matchPrefixComplete(B,e,t,s);if(this.prefilter!==null&&t===m.UNANCHORED&&!this.prefilter.eval(B,e))return null;if(this.onepass!==null)return tt.execute(this,B,e,t,s);if(s>0)return this.prog.numLb===0&&B.endPos()<=Ge.maxBitStateLen(this.prog)?Ge.execute(this,B,e,t,s):this.doExecuteNFA(B,e,t,s);if(this.prog.numLb===0){const C=this.dfa.match(B,e,t);if(C!==null)return C?[]:null;if(B.endPos()<=Ge.maxBitStateLen(this.prog))return Ge.execute(this,B,e,t,s)}return this.doExecuteNFA(B,e,t,s)}numberOfCapturingGroups(){return this.numSubexp}numberOfInstructions(){return this.prog.numInst()}get(){return this.machinePool.length>0?this.machinePool.pop():null}reset(){this.machinePool.length=0}put(B){this.machinePool.push(B)}toString(){return this.expr}doExecuteNFA(B,e,t,s){let C=this.get();C||(C=ls.fromRE2(this)),C.init(s);const i=C.match(B,e,t)?C.submatches():null;return this.put(C),i}match(B){return this.executeEngine(K.fromUTF16(B),0,m.UNANCHORED,0)!==null}matchWithGroup(B,e,t,s,C){return B instanceof kB||(A.isByteArray(B)?B=SB.utf8(B):B=SB.utf16(B)),this.matchMachineInput(B,e,t,s,C)}matchMachineInput(B,e,t,s,C){if(e>t)return[!1,null];const i=B.isUTF16Encoding()?K.fromUTF16(B.asCharSequence(),0,t):K.fromUTF8(B.asBytes(),0,t),r=this.executeEngine(i,e,s,2*C);return r===null?[!1,null]:[!0,r]}matchUTF8(B){return this.executeEngine(K.fromUTF8(B),0,m.UNANCHORED,0)!==null}replaceAll(B,e){return this.replaceAllFunc(B,()=>e,2*B.length+1)}replaceFirst(B,e){return this.replaceAllFunc(B,()=>e,1)}replaceAllFunc(B,e,t){let s=0,C=0,i="";const r=K.fromUTF16(B);let a=0;for(;C<=B.length;){const u=this.executeEngine(r,C,m.UNANCHORED,2);if(u===null||u.length===0)break;i+=B.substring(s,u[0]),(u[1]>s||u[0]===0)&&(i+=e(B.substring(u[0],u[1])),a++),s=u[1];const D=r.step(C)&7;if(C+D>u[1]?C+=D:C+1>u[1]?C++:C=u[1],a>=t)break}return i+=B.substring(s),i}pad(B){if(B===null)return null;let e=(1+this.numSubexp)*2;if(B.length<e){let t=new Array(e).fill(-1);for(let s=0;s<B.length;s++)t[s]=B[s];B=t}return B}allMatches(B,e,t=s=>s){let s=[];const C=B.endPos();e<0&&(e=C+1);let i=0,r=0,a=-1;for(;r<e&&i<=C;){const u=this.executeEngine(B,i,m.UNANCHORED,this.prog.numCap);if(u===null||u.length===0)break;let D=!0;if(u[1]===i){u[0]===a&&(D=!1);const f=B.step(i);f<0?i=C+1:i+=f&7}else i=u[1];a=u[1],D&&(s.push(t(this.pad(u))),r++)}return s}findUTF8(B){const e=this.executeEngine(K.fromUTF8(B),0,m.UNANCHORED,2);return e===null?null:B.slice(e[0],e[1])}findUTF8Index(B){const e=this.executeEngine(K.fromUTF8(B),0,m.UNANCHORED,2);return e===null?null:e.slice(0,2)}find(B){const e=this.executeEngine(K.fromUTF16(B),0,m.UNANCHORED,2);return e===null?"":B.substring(e[0],e[1])}findIndex(B){return this.executeEngine(K.fromUTF16(B),0,m.UNANCHORED,2)}findUTF8Submatch(B){const e=this.executeEngine(K.fromUTF8(B),0,m.UNANCHORED,this.prog.numCap);if(e===null)return null;const t=new Array(1+this.numSubexp).fill(null);for(let s=0;s<t.length;s++)2*s<e.length&&e[2*s]>=0&&(t[s]=B.slice(e[2*s],e[2*s+1]));return t}findUTF8SubmatchIndex(B){return this.pad(this.executeEngine(K.fromUTF8(B),0,m.UNANCHORED,this.prog.numCap))}findSubmatch(B){const e=this.executeEngine(K.fromUTF16(B),0,m.UNANCHORED,this.prog.numCap);if(e===null)return null;const t=new Array(1+this.numSubexp).fill(null);for(let s=0;s<t.length;s++)2*s<e.length&&e[2*s]>=0&&(t[s]=B.substring(e[2*s],e[2*s+1]));return t}findSubmatchIndex(B){return this.pad(this.executeEngine(K.fromUTF16(B),0,m.UNANCHORED,this.prog.numCap))}findAllUTF8(B,e){const t=this.allMatches(K.fromUTF8(B),e,s=>B.slice(s[0],s[1]));return t.length===0?null:t}findAllUTF8Index(B,e){const t=this.allMatches(K.fromUTF8(B),e,s=>s.slice(0,2));return t.length===0?null:t}findAll(B,e){const t=this.allMatches(K.fromUTF16(B),e,s=>B.substring(s[0],s[1]));return t.length===0?null:t}findAllIndex(B,e){const t=this.allMatches(K.fromUTF16(B),e,s=>s.slice(0,2));return t.length===0?null:t}findAllUTF8Submatch(B,e){const t=this.allMatches(K.fromUTF8(B),e,s=>{let C=new Array(s.length/2|0).fill(null);for(let i=0;i<C.length;i++)s[2*i]>=0&&(C[i]=B.slice(s[2*i],s[2*i+1]));return C});return t.length===0?null:t}findAllUTF8SubmatchIndex(B,e){const t=this.allMatches(K.fromUTF8(B),e);return t.length===0?null:t}findAllSubmatch(B,e){const t=this.allMatches(K.fromUTF16(B),e,s=>{let C=new Array(s.length/2|0).fill(null);for(let i=0;i<C.length;i++)s[2*i]>=0&&(C[i]=B.substring(s[2*i],s[2*i+1]));return C});return t.length===0?null:t}findAllSubmatchIndex(B,e){const t=this.allMatches(K.fromUTF16(B),e);return t.length===0?null:t}},bs=class UB{static isHexadecimal(B){return"0"<=B&&B<="9"||"A"<=B&&B<="F"||"a"<=B&&B<="f"}static translate(B){let e="";if(B instanceof RegExp&&(B.ignoreCase&&(e+="i"),B.multiline&&(e+="m"),B.dotAll&&(e+="s"),B=B.source),typeof B!="string")return B;let t="",s=!1,C=B.length;C===0&&(t="(?:)",s=!0);let i=!1,r=0;for(;r<C;){let u=B[r];if(u==="\\"){if(r+1<C)switch(u=B[r+1],u){case"\\":t+="\\\\",r+=2;continue;case"c":if(r+2<C){let I=B[r+2].charCodeAt(0);if(I>=65&&I<=90||I>=97&&I<=122){let w=I%32;t+="\\x",t+=(w>>4).toString(16).toUpperCase(),t+=(w&15).toString(16).toUpperCase(),r+=3,s=!0;continue}}t+="c",r+=2,s=!0;continue;case"u":if(r+2<C){if(B[r+2]==="{"){let I=r+3,w=!1,x=!1;for(;I<C;){const L=B[I];if(L==="}"){x=!0;break}if(!UB.isHexadecimal(L))break;w=!0,I++}if(x&&w){t+="\\x",r+=2,s=!0;continue}}else if(r+5<C){let I=!0;for(let w=0;w<4;w++)if(!UB.isHexadecimal(B[r+2+w])){I=!1;break}if(I){t+="\\x{"+B.substring(r+2,r+6)+"}",r+=6,s=!0;continue}}}t+="u",r+=2,s=!0;continue;case"x":{let I=!1;if(r+2<C&&B[r+2]==="{"){let w=r+3,x=!1,L=!1;for(;w<C;){const y=B[w];if(y==="}"){L=!0;break}if(!UB.isHexadecimal(y))break;x=!0,w++}L&&x&&(I=!0)}else r+3<C&&UB.isHexadecimal(B[r+2])&&UB.isHexadecimal(B[r+3])&&(I=!0);I?(t+="\\x",r+=2):(t+="x",r+=2,s=!0);continue}case"n":case"r":case"t":case"a":case"f":case"v":case"d":case"D":case"s":case"S":case"w":case"W":case"b":case"B":case"p":case"P":case"A":case"z":case"Q":case"E":case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":t+="\\"+u,r+=2;continue;default:{let I=B.codePointAt(r+1);if(I>=48&&I<=57||I>=65&&I<=90||I>=97&&I<=122){let w=A.charCount(I);t+=B.substring(r+1,r+1+w),r+=w+1,s=!0}else{t+="\\";let w=A.charCount(I);t+=B.substring(r+1,r+1+w),r+=w+1}continue}}}else if(u==="/"){t+="\\/",r+=1,s=!0;continue}else if(u==="[")i=!0;else if(u==="]")i=!1;else if(!i&&u==="("&&r+2<C&&B[r+1]==="?"&&B[r+2]==="<"&&r+3<C&&!"=!>)".includes(B[r+3])){t+="(?P<",r+=3,s=!0;continue}let D=B.codePointAt(r),f=A.charCount(D);t+=B.substring(r,r+f),r+=f}const a=s?t:B;return e.length>0?`(?${e})${a}`:a}},Z,It=(Z=class{static quote(B){return A.quoteMeta(B)}static quoteReplacement(B,e=!1){return We.quoteReplacement(B,e)}static translateRegExp(B){return bs.translate(B)}static compile(B,e=0){let t=B;if((e&Z.CASE_INSENSITIVE)!==0&&(t=`(?i)${t}`),(e&Z.DOTALL)!==0&&(t=`(?s)${t}`),(e&Z.MULTILINE)!==0&&(t=`(?m)${t}`),(e&-544)!==0)throw new os("Flags should only be a combination of MULTILINE, DOTALL, CASE_INSENSITIVE, DISABLE_UNICODE_GROUPS, LONGEST_MATCH, LOOKBEHINDS");let s=m.PERL;(e&Z.DISABLE_UNICODE_GROUPS)!==0&&(s&=-129),(e&Z.LOOKBEHINDS)!==0&&(s|=m.LOOKBEHIND);const C=new Z(B,e);return C.re2Input=Ls.compileImpl(t,s,(e&Z.LONGEST_MATCH)!==0),C}static matches(B,e){return Z.compile(B).testExact(e)}static initTest(B,e,t){if(B==null)throw new Error("pattern is null");if(t==null)throw new Error("re2 is null");const s=new Z(B,e);return s.re2Input=t,s}constructor(B,e){this.patternInput=B,this.flagsInput=e,this.re2Input=null}reset(){this.re2Input.reset()}flags(){return this.flagsInput}pattern(){return this.patternInput}re2(){return this.re2Input}matches(B){return this.testExact(B)}matcher(B){return A.isByteArray(B)&&(B=SB.utf8(B)),new We(this,B)}test(B){return A.isByteArray(B)?this.re2Input.matchUTF8(B):this.re2Input.match(B)}testExact(B){const e=A.isByteArray(B)?K.fromUTF8(B):K.fromUTF16(B);return this.re2Input.executeEngine(e,0,m.ANCHOR_BOTH,0)!==null}exec(B){const e=this.matcher(B);if(!e.find())return null;const t=[e.group(0)];for(let C=1;C<=e.groupCount();C++){const i=e.group(C);t.push(i===null?void 0:i)}t.index=e.start(0),t.input=B;const s=this.namedGroups();if(Object.keys(s).length>0){const C=e.getNamedGroups();for(const i in C)C[i]===null&&(C[i]=void 0);t.groups=C}else t.groups=void 0;return t}split(B,e=0){const t=this.matcher(B),s=[];let C=0,i=0;for(;t.find();){if(i===0&&t.end()===0){i=t.end();continue}if(e>0&&s.length===e-1)break;if(i===t.start()){if(e===0){C+=1,i=t.end();continue}}else for(;C>0;)s.push(""),C-=1;s.push(t.substring(i,t.start())),i=t.end()}if(e===0&&i!==t.inputLength()){for(;C>0;)s.push(""),C-=1;s.push(t.substring(i,t.inputLength()))}return(e!==0||s.length===0&&!(i===t.inputLength()&&i>0))&&s.push(t.substring(i,t.inputLength())),s}*matchAll(B){const e=this.matcher(B);for(;e.find();){const t=[e.group(0)];for(let C=1;C<=e.groupCount();C++){const i=e.group(C);t.push(i===null?void 0:i)}t.index=e.start(0),t.input=B;const s=this.namedGroups();if(Object.keys(s).length>0){const C=e.getNamedGroups();for(const i in C)C[i]===null&&(C[i]=void 0);t.groups=C}else t.groups=void 0;yield t}}toString(){return this.patternInput}programSize(){return this.re2Input.numberOfInstructions()}groupCount(){return this.re2Input.numberOfCapturingGroups()}namedGroups(){return this.re2Input.namedGroups}equals(B){return this===B?!0:B===null||this.constructor!==B.constructor?!1:this.flagsInput===B.flagsInput&&this.patternInput===B.patternInput}},F(Z,"CASE_INSENSITIVE",JB.CASE_INSENSITIVE),F(Z,"DOTALL",JB.DOTALL),F(Z,"MULTILINE",JB.MULTILINE),F(Z,"DISABLE_UNICODE_GROUPS",JB.DISABLE_UNICODE_GROUPS),F(Z,"LONGEST_MATCH",JB.LONGEST_MATCH),F(Z,"LOOKBEHINDS",JB.LOOKBEHINDS),Z);const wt=Lt([eB().max(16e3),vB().finite(),KB(),Ut()]).meta({anyOf:[{type:"string",maxLength:16e3},{type:"number"},{type:"boolean"},{type:"null"}]}),se=eB().min(1).max(256).regex(/^[a-zA-Z_][\w]*(?:\.[\w]+)*$/).refine(n=>!n.split(".").some(B=>["__proto__","prototype","constructor"].includes(B)),"Unsafe field path"),Hs=At("operator",[W({field:se,operator:lB("equals"),value:wt}).strict(),W({field:se,operator:lB("in"),value:pB(wt).min(1).max(100)}).strict(),W({field:se,operator:lB("exists")}).strict(),W({field:se,operator:LB(["contains","starts_with","ends_with"]),value:eB().min(1).max(16e3),ignore_case:KB().optional()}).strict(),W({field:se,operator:lB("regex"),value:eB().min(1).max(512),ignore_case:KB().optional()}).strict().superRefine((n,B)=>{try{Rs(n.value,n.ignore_case)}catch{B.addIssue({code:"custom",message:"Invalid RE2 regex (lookaround and backreferences are unsupported)"})}})]),Ts=W({match:LB(["all","any"]),conditions:pB(W({predicate:Hs,negate:KB().optional()}).strict()).max(32)}).strict();function Rs(n,B=!1){return It.compile(n,B?It.CASE_INSENSITIVE:0)}const EB=eB().trim().min(1).max(128),Ss={id:EB,reason:eB().trim().min(1).max(1e3)},_s=W({type:lB("ask_user"),kind:LB(["question","approval"]),prompt:eB().trim().min(1).max(16e3),choices:pB(eB().trim().min(1).max(1e3)).max(20).default([]),expires_in_seconds:vB().int().min(1).max(604800).default(86400),notify:pB(LB(["telegram","slack"])).max(2).default([])}).strict(),kt=["load_context","record_event","snapshot_session","restore_session","sync_agent_memory"],vs=W({type:lB("orc_action"),action:LB(kt),timeout_ms:vB().int().min(100).max(2e3).default(1e3),memory_directory:eB().min(1).max(4096).optional(),event_type:LB(["auto","file","task","rule","decision","git","env","error","plan","intent","subagent"]).optional()}).strict().superRefine((n,B)=>{n.memory_directory&&n.action!=="sync_agent_memory"&&B.addIssue({code:"custom",message:"Memory directory applies only to memory synchronization"}),n.memory_directory&&n.memory_directory!=="auto"&&!/^(?:[A-Za-z]:[\\/]|\\\\|\/|~\/)/.test(n.memory_directory)&&B.addIssue({code:"custom",message:"Memory directory must be absolute, ~/ prefixed, or auto"}),n.event_type&&n.action!=="record_event"&&B.addIssue({code:"custom",message:"Event type applies only to event recording"})}),ks=W({type:lB("rewrite_command"),argv:pB(eB().min(1).max(4096).refine(n=>!n.includes("\0"))).min(1).max(32),timeout_ms:vB().int().min(100).max(2e3),rewrite_exit_codes:pB(vB().int().min(0).max(255)).min(1).max(16).default([0]),passthrough_exit_codes:pB(vB().int().min(0).max(255)).max(16).default([])}).strict().superRefine((n,B)=>{var e;(e=n.argv[0])!=null&&e.includes("{command}")&&B.addIssue({code:"custom",message:"Processor executable cannot contain {command}"}),n.argv.some(t=>t.includes("{command}")&&t!=="{command}")&&B.addIssue({code:"custom",message:"{command} must be a complete argument"}),n.rewrite_exit_codes.some(t=>n.passthrough_exit_codes.includes(t))&&B.addIssue({code:"custom",message:"Rewrite and passthrough exit codes must not overlap"})}),Ps=W({type:lB("script"),mode:LB(["sync","background"]),argv:pB(eB().min(1).max(4096).refine(n=>!n.includes("\0"))).min(1).max(32),timeout_ms:vB().int().min(100).max(3e4)}).strict(),oe=W({...Ss,kind:lB("event"),enabled:KB(),scope:W({agents:Lt([lB("all"),pB(LB(["claude","cursor","gemini","codex"])).min(1).max(4)]),events:pB(EB).min(1).max(40)}).strict(),filter:Ts,target:At("type",[W({type:lB("block")}).strict(),W({type:lB("inject_context"),content:eB().min(1).max(8e3)}).strict(),W({type:lB("job"),job_id:EB}).strict(),Ps,ks,vs,_s])}).strict().superRefine((n,B)=>{const e=n.scope.agents==="all"?Object.keys(ne):n.scope.agents;for(const t of n.scope.events){const s=e.map(C=>bt(C,t));if(n.target.type==="ask_user"){const C=n.target;(t==="runtime:permission_request"&&C.kind!=="approval"||t==="runtime:question_request"&&C.kind!=="question")&&B.addIssue({code:"custom",message:"Runtime questions and approvals must use the matching request kind"}),s.some(i=>!(i!=null&&i.block)||C.kind==="question"&&!i.context)&&B.addIssue({code:"custom",message:"Ask user requires a blocking hook and questions require answer delivery on every selected agent"}),n.target.kind==="approval"&&n.target.choices.length&&B.addIssue({code:"custom",message:"Approval uses approve or deny"})}if(n.target.type==="orc_action"){const C={load_context:["session_start"],record_event:["post_tool","post_tool_failure","stop"],snapshot_session:["pre_compact"],restore_session:["session_start","post_compact"],sync_agent_memory:["post_tool","session_end"]}[n.target.action];s.some(i=>!i||!C.includes(i.event))&&B.addIssue({code:"custom",message:`Action ${n.target.action} is unavailable for ${t}`}),["load_context","restore_session"].includes(n.target.action)&&s.some(i=>!(i!=null&&i.context))&&B.addIssue({code:"custom",message:"Continuity context requires native context delivery"}),n.target.action==="sync_agent_memory"&&(n.scope.agents==="all"||e.some(i=>i!=="claude"))&&B.addIssue({code:"custom",message:"Agent memory synchronization currently supports local Claude memory"})}s.some(Boolean)||B.addIssue({code:"custom",message:`No selected agent supports event ${t}`}),t.startsWith("native:")&&n.scope.agents==="all"&&B.addIssue({code:"custom",message:"Native events require specific agents"}),n.target.type==="rewrite_command"&&(s.some(C=>!(C!=null&&C.rewrite_command))||n.scope.agents==="all")&&B.addIssue({code:"custom",message:`Event ${t} cannot rewrite commands on every selected agent`}),n.target.type==="block"&&s.some(C=>C&&!C.block)&&B.addIssue({code:"custom",message:`Event ${t} cannot block on every supporting selected agent`}),n.target.type==="inject_context"&&s.some(C=>C&&!C.context)&&B.addIssue({code:"custom",message:`Event ${t} cannot inject context on every supporting selected agent`})}n.target.type==="script"&&n.target.mode==="sync"&&n.target.timeout_ms>2e3&&B.addIssue({code:"custom",message:"Synchronous script timeout cannot exceed 2000ms"})}),ys=oe;W({workspace:eB().min(1).max(4096).refine(n=>/^(?:[A-Za-z]:[\\/]|\\\\|\/)/.test(n),"Workspace must be absolute"),project_id:EB.nullable(),rules:pB(ys).min(1).max(100)}).strict().superRefine((n,B)=>{new Set(n.rules.map(s=>s.id)).size!==n.rules.length&&B.addIssue({code:"custom",message:"Rule IDs must be unique"}),n.rules.reduce((s,C)=>s+(C.target.type==="inject_context"?C.target.content.length:0),0)>16e3&&B.addIssue({code:"custom",message:"Policy context exceeds 16000 characters"});const e=Math.max(0,...n.rules.map(s=>s.kind==="event"&&s.enabled&&s.target.type==="rewrite_command"?s.target.timeout_ms:0));n.rules.reduce((s,C)=>s+(C.kind==="event"&&C.target.type==="script"&&C.target.mode==="sync"?C.target.timeout_ms:0),0)*(e?2:1)+e>5e3&&B.addIssue({code:"custom",message:"Total synchronous execution and validation timeout exceeds 5000ms"})});W({id:EB,session_id:EB,backend:EB,cwd:eB().min(1).max(4096).refine(n=>/^(?:[A-Za-z]:[\\/]|\\\\|\/)/.test(n)),phase:EB,native_event:EB.optional(),payload:Qe(eB(),Ye()).optional(),tool:EB.optional(),input:Qe(eB(),Ye()).default({}),failed:KB().default(!1)}).strict();function Ce(n){return{match:"all",conditions:[{predicate:{field:"tool",operator:"equals",value:"Bash"}},{predicate:{field:"input.command",operator:"regex",value:n}}]}}function z(n){return{...n,rule:oe.parse(n.rule)}}const X={kind:"event",enabled:!0},xe={agents:["claude"],events:["pre_tool"]},Gt={type:"rewrite_command",argv:["rtk","rewrite","{command}"],timeout_ms:1e3,rewrite_exit_codes:[0,3],passthrough_exit_codes:[1]},Ae=[z({id:"orc-native-questions",name:"ORC · Agent questions",category:"Guidance",description:"Send Claude and Codex questions and non-secret MCP forms to Attention needed.",configuration:"For ORC-managed Claude/Codex sessions. Native tool choices override template choices. Enable optional channel notifications in the action.",rule:{...X,id:"orc-native-questions",reason:"Collect the human answer before continuing",scope:{agents:["claude","codex"],events:["runtime:question_request"]},filter:{match:"all",conditions:[]},target:{type:"ask_user",kind:"question",prompt:"Agent question"}}}),z({id:"orc-native-approvals",name:"ORC · Agent tool approvals",category:"Protection",description:"Review native command, file and permission requests in Attention needed.",configuration:"For ORC-managed Claude/Codex sessions. Select default permissions so the agent emits native approvals. Existing agent permissions still apply.",rule:{...X,id:"orc-native-approvals",reason:"Review the exact proposed action",scope:{agents:["claude","codex"],events:["runtime:permission_request"]},filter:{match:"all",conditions:[]},target:{type:"ask_user",kind:"approval",prompt:"May this agent perform the shown action?"}}}),z({id:"orc-claude-hook-questions",name:"ORC · External Claude questions",category:"Guidance",description:"Collect AskUserQuestion answers from an independently launched Claude through its native command hook.",configuration:"Install Claude PreToolUse hooks with a timeout longer than this request lifetime. Requires an existing ORC CLI/API connection on that machine; no helper installation.",rule:{...X,id:"orc-claude-hook-questions",reason:"Collect real native question answers",scope:{agents:["claude"],events:["pre_tool"]},filter:{match:"all",conditions:[{predicate:{field:"tool",operator:"equals",value:"AskUserQuestion"}}]},target:{type:"ask_user",kind:"question",prompt:"Agent question",expires_in_seconds:1800}}}),z({id:"orc-claude-hook-approvals",name:"ORC · External Claude approvals",category:"Protection",description:"Route an independently launched Claude's permission prompts into Attention needed.",configuration:"Install Claude PermissionRequest hooks with --timeout-seconds 1815. Native permission prompts must be enabled. This does not grant additional OS privileges.",rule:{...X,id:"orc-claude-hook-approvals",reason:"Review the exact proposed action",scope:{agents:["claude"],events:["permission_request"]},filter:{match:"all",conditions:[]},target:{type:"ask_user",kind:"approval",prompt:"May this agent perform the shown action?",expires_in_seconds:1800}}}),z({id:"orc-load-context",name:"ORC · Load project context",category:"Guidance",description:"Load active tasks and key shared memories at session start using ORC's existing context service.",configuration:"Uses this policy's project scope. Requires the configured ORC API connection.",rule:{...X,id:"orc-load-context",reason:"Load shared workspace context",scope:{agents:"all",events:["session_start"]},filter:{match:"all",conditions:[{predicate:{field:"payload.source",operator:"in",value:["compact","resume"]},negate:!0}]},target:{type:"orc_action",action:"load_context",timeout_ms:1e3}}}),z({id:"orc-record-events",name:"ORC · Record work events",category:"Automation",description:"Record file, task, Git, environment and other significant tool events with the existing session-event service.",configuration:"Customize scope, tool filters and event type. Command text and memory contents are not copied into event history.",rule:{...X,id:"orc-record-events",reason:"Retain significant work events",scope:{agents:"all",events:["post_tool"]},filter:{match:"all",conditions:[]},target:{type:"orc_action",action:"record_event",event_type:"auto",timeout_ms:1e3}}}),z({id:"orc-snapshot",name:"ORC · Snapshot before compaction",category:"Automation",description:"Save session events and project tasks through ORC's existing bounded snapshot service.",configuration:"Uses the agent's native session identity and this policy's project scope.",rule:{...X,id:"orc-snapshot",reason:"Preserve continuity before compaction",scope:{agents:"all",events:["pre_compact"]},filter:{match:"all",conditions:[]},target:{type:"orc_action",action:"snapshot_session",timeout_ms:1e3}}}),z({id:"orc-restore",name:"ORC · Restore session context",category:"Guidance",description:"Restore the native session's snapshot after compaction or on resume.",configuration:"Delivered through the connected agent's native context response.",rule:{...X,id:"orc-restore",reason:"Restore saved session state",scope:{agents:"all",events:["session_start"]},filter:{match:"all",conditions:[{predicate:{field:"payload.source",operator:"in",value:["compact","resume"]}}]},target:{type:"orc_action",action:"restore_session",timeout_ms:1e3}}}),z({id:"claude-share-memory",name:"Claude · Share auto-memory with ORC",category:"Automation",description:"Sync Claude memory topic files into project-scoped ORC memory after writes and at session end.",configuration:"Auto detects the usual local Claude directory and custom settings; choose an explicit directory if needed. MEMORY.md is an index and is skipped. Updates retain source identity and audit history; captures are agent-origin facts, not verified lessons.",rule:{...X,id:"claude-share-memory",reason:"Share native Claude memory across agents",scope:{agents:["claude"],events:["post_tool","session_end"]},filter:{match:"all",conditions:[]},target:{type:"orc_action",action:"sync_agent_memory",memory_directory:"auto",timeout_ms:2e3}}}),z({id:"rtk-git",name:"Compact Git output with RTK",category:"Command routing",description:"Route Git status, diff and log through an installed RTK executable.",configuration:"RTK must be installed on the agent host and available on PATH. Review command filters before saving.",rule:{...X,id:"rtk-git",reason:"Compact Git command output",scope:xe,filter:Ce("^git\\s+(status|diff|log)(\\s|$)"),target:Gt}}),z({id:"rtk-tests",name:"Compact test output with RTK",category:"Command routing",description:"Route Bun, npm, pnpm, Cargo, Go and pytest test commands through RTK.",configuration:"RTK must be available on the agent host. Unsupported commands explicitly pass through.",rule:{...X,id:"rtk-tests",reason:"Compact test command output",scope:xe,filter:Ce("^(?:(?:bun|npm|pnpm|cargo|go)\\s+test|pytest)(\\s|$)"),target:Gt}}),z({id:"custom-command-router",name:"Use my own command processor",category:"Command routing",description:"Start with the generic CLI contract and choose your own executable and exit codes.",configuration:"Replace your-command-processor, narrow the filter, and configure the executable's exit-code contract.",rule:{...X,id:"custom-command-router",reason:"Use my configured command processor",scope:xe,filter:Ce("^git\\s+status(\\s|$)"),target:{type:"rewrite_command",argv:["your-command-processor","{command}"],timeout_ms:1e3,rewrite_exit_codes:[0],passthrough_exit_codes:[]}}}),z({id:"block-command-pattern",name:"Block Bash command text matching rm -rf",category:"Protection",description:"Block Bash pre-tool calls whose command text matches the rm -rf regex shown below.",configuration:"A command-text regex, including quoted text. Matches rm -rf; does not cover rm -fr, split flags, Python deletion, PowerShell or other tools. Edit the tool and pattern.",rule:{...X,id:"block-command-pattern",reason:"Command matches a blocked pattern",scope:{agents:"all",events:["pre_tool"]},filter:{match:"all",conditions:[{predicate:{field:"tool",operator:"equals",value:"Bash"}},{predicate:{field:"input.command",operator:"regex",value:"\\brm\\s+-rf\\b"}}]},target:{type:"block"}}}),z({id:"block-powershell-remove-item",name:"Block command text containing Remove-Item",category:"Protection",description:"Block pre-tool calls whose tool is Bash, PowerShell or shell_command and whose command text contains Remove-Item.",configuration:"A case-insensitive text check, including quoted text. Other tool names, aliases and other deletion methods are not covered. Edit the tool list and command pattern.",rule:{...X,id:"block-powershell-remove-item",reason:"Command text matched Remove-Item",scope:{agents:"all",events:["pre_tool"]},filter:{match:"all",conditions:[{predicate:{field:"tool",operator:"in",value:["Bash","PowerShell","shell_command"]}},{predicate:{field:"input.command",operator:"regex",value:"\\bRemove-Item\\b",ignore_case:!0}}]},target:{type:"block"}}}),z({id:"block-git-force-push",name:"Block direct git push commands with force flags",category:"Protection",description:"Block Bash command text starting with git push and containing --force, --force-with-lease or -f.",configuration:"Text matching only. Commands using git -C, aliases, wrappers or other spellings are not covered. Change the pattern to match your workflow.",rule:{...X,id:"block-git-force-push",reason:"Direct git push command matched a force flag",scope:{agents:"all",events:["pre_tool"]},filter:Ce("^git\\s+push\\b.*(?:--force(?:-with-lease)?\\b|\\s-f(?:\\s|$))"),target:{type:"block"}}}),z({id:"block-env-write",name:"Block Write/Edit calls targeting .env files",category:"Protection",description:"Block Write, Edit and MultiEdit calls when input.file_path ends in .env or .env.<name>.",configuration:"Checks the supplied file_path text. Reads, shell commands, other tools and paths supplied in other fields are unaffected. Edit the tool list and path pattern.",rule:{...X,id:"block-env-write",reason:"Structured edit targets an .env filename",scope:{agents:"all",events:["pre_tool"]},filter:{match:"all",conditions:[{predicate:{field:"tool",operator:"in",value:["Write","Edit","MultiEdit"]}},{predicate:{field:"input.file_path",operator:"regex",value:"(?:^|[/\\\\])\\.env(?:\\.[^/\\\\]+)?$",ignore_case:!0}}]},target:{type:"block"}}}),z({id:"block-write-comment-markers",name:"Block Write content containing // or /*",category:"Protection",description:"Block Write calls to JS/TS filenames when the supplied content contains // or /*.",configuration:"Text matching, not language parsing: URLs and strings containing these markers match too. Edit, shell commands and other tools are unaffected. Customize the tool, extensions or pattern.",rule:{...X,id:"block-write-comment-markers",reason:"Write content matched a comment-marker text pattern",scope:{agents:"all",events:["pre_tool"]},filter:{match:"all",conditions:[{predicate:{field:"tool",operator:"equals",value:"Write"}},{predicate:{field:"input.file_path",operator:"regex",value:"\\.[cm]?[jt]sx?$",ignore_case:!0}},{predicate:{field:"input.content",operator:"regex",value:"//|/\\*"}}]},target:{type:"block"}}}),z({id:"comments-guidance",name:"Ask the agent to avoid adding comments",category:"Guidance",description:"Send a session-start instruction asking the agent to avoid new comments unless requested.",configuration:"Advisory context, not a blocking check. Edit the instruction and selected agents.",rule:{...X,id:"comments-guidance",reason:"Session guidance about code comments",scope:{agents:"all",events:["session_start"]},filter:{match:"all",conditions:[]},target:{type:"inject_context",content:"Avoid adding new code comments unless the user requests them. Explain your changes in your response instead."}}}),z({id:"session-guidance",name:"Give guidance at session start",category:"Guidance",description:"Inject workspace instructions through the connected agent's session-start event.",configuration:"Customize the guidance and select the agents that should receive it.",rule:{...X,id:"session-guidance",reason:"Workspace session guidance",scope:{agents:"all",events:["session_start"]},filter:{match:"all",conditions:[]},target:{type:"inject_context",content:"Run the relevant checks before reporting work complete. Report any unresolved failures."}}}),z({id:"sync-guard-script",name:"Run my own guard script",category:"Automation",description:"Evaluate a trusted synchronous script on matching pre-tool events.",configuration:"Replace the script path and narrow the filter. The script receives event JSON and returns a decision/context JSON object.",rule:{...X,id:"sync-guard-script",reason:"Custom workspace guard",scope:xe,filter:Ce("^git\\s+status(\\s|$)"),target:{type:"script",mode:"sync",argv:["bun","C:/path/to/guard.ts"],timeout_ms:1e3}}})];function Ms(n){const B=Ae.find(e=>e.id===n);if(!B)throw new Error("Unknown rule template");return oe.parse(structuredClone(B.rule))}const sB="w-full rounded-md border border-control-border bg-background p-2 text-sm",ve={claude:"Claude",cursor:"Cursor",gemini:"Gemini CLI",codex:"Codex"};function Js({rule:n,projectId:B,pending:e,onSave:t,isEditing:s=!!n}){var qe;const[C,i]=S.useState((n==null?void 0:n.id)??`rule-${Date.now().toString(36)}`),[r,a]=S.useState((n==null?void 0:n.reason)??""),[u,D]=S.useState((n==null?void 0:n.scope.agents)==="all"||!n?"all":n.scope.agents.join(",")),[f,I]=S.useState((n==null?void 0:n.scope.events)??["pre_tool"]),[w,x]=S.useState(()=>((n==null?void 0:n.scope.events)??["pre_tool"]).map(()=>crypto.randomUUID())),[L,y]=S.useState((n==null?void 0:n.filter.match)??"all"),[R,$]=S.useState(()=>(n==null?void 0:n.filter.conditions.map(({predicate:d,negate:T})=>({key:crypto.randomUUID(),field:d.field,operator:d.operator,value:"value"in d?Array.isArray(d.value)?JSON.stringify(d.value):String(d.value):"",negate:T??!1,valueType:"value"in d&&typeof d.value!="string"?"json":"string",ignoreCase:"ignore_case"in d&&(d.ignore_case??!1)})))??[{key:crypto.randomUUID(),field:"",operator:"contains",value:"",valueType:"string",negate:!1,ignoreCase:!1}]),[M,cB]=S.useState((n==null?void 0:n.target.type)??"block"),[tB,DB]=S.useState((n==null?void 0:n.target.type)==="ask_user"?n.target.kind:"approval"),[bB,le]=S.useState((n==null?void 0:n.target.type)==="ask_user"?n.target.prompt:"May this agent continue?"),[ce,qB]=S.useState((n==null?void 0:n.target.type)==="ask_user"?n.target.choices.join(`
27
27
  `):""),[IB,Q]=S.useState((n==null?void 0:n.target.type)==="ask_user"?n.target.notify:[]),[QB,YB]=S.useState((n==null?void 0:n.target.type)==="ask_user"?n.target.expires_in_seconds:86400),[HB,Le]=S.useState((n==null?void 0:n.target.type)==="inject_context"?n.target.content:""),[mB,PB]=S.useState((n==null?void 0:n.target.type)==="job"?n.target.job_id:""),[VB,ue]=S.useState((n==null?void 0:n.target.type)==="script"?JSON.stringify(n.target.argv,null,2):'["bun", "C:/path/to/hook.ts"]'),[zB,be]=S.useState((n==null?void 0:n.target.type)==="script"?n.target.mode:"sync"),[yB,he]=S.useState((n==null?void 0:n.target.type)==="script"?n.target.timeout_ms:1e3),[XB,De]=S.useState((n==null?void 0:n.target.type)==="rewrite_command"?JSON.stringify(n.target.argv,null,2):'["rtk", "rewrite", "{command}"]'),[ZB,ge]=S.useState((n==null?void 0:n.target.type)==="rewrite_command"?n.target.timeout_ms:1e3),[WB,pe]=S.useState((n==null?void 0:n.target.type)==="rewrite_command"?JSON.stringify(n.target.rewrite_exit_codes):"[0, 3]"),[$B,Ee]=S.useState((n==null?void 0:n.target.type)==="rewrite_command"?JSON.stringify(n.target.passthrough_exit_codes):"[1]"),[Be,de]=S.useState((n==null?void 0:n.enabled)??!0),[E,N]=S.useState((n==null?void 0:n.target.type)==="orc_action"?n.target.action:"load_context"),[H,V]=S.useState((n==null?void 0:n.target.type)==="orc_action"?n.target.timeout_ms:1e3),[nB,TB]=S.useState((n==null?void 0:n.target.type)==="orc_action"?n.target.memory_directory??"auto":"auto"),[fe,Pt]=S.useState((n==null?void 0:n.target.type)==="orc_action"?n.target.event_type??"auto":"auto"),[Ue,Ke]=S.useState(""),He=ts({enabled:!0}),ee=u==="all"?Object.keys(ve):u.split(","),Te=[...new Set(ee.flatMap(d=>{var T;return((T=ne[d])==null?void 0:T.map(_=>_.event))??[]}))];u!=="all"&&Te.push(...ee.flatMap(d=>{var T;return((T=ne[d])==null?void 0:T.map(_=>`native:${_.native}`))??[]})),ee.every(d=>["claude","codex"].includes(d))&&Te.push("runtime:permission_request","runtime:question_request");const gB=d=>f.every(T=>{const _=ee.flatMap(BB=>{const uB=bt(BB,T);return uB?[uB]:[]});return _.length>0&&_.every(BB=>BB[d])}),yt=()=>{try{const d=oe.parse({id:C,reason:r,kind:"event",enabled:Be,scope:{agents:u==="all"?"all":u.split(","),events:f},filter:{match:L,conditions:R.map(T=>({negate:T.negate,predicate:{field:T.field,operator:T.operator,...T.operator==="exists"?{}:{value:T.operator==="in"||T.operator==="equals"&&T.valueType==="json"?JSON.parse(T.value):T.value},...["regex","contains","starts_with","ends_with"].includes(T.operator)?{ignore_case:T.ignoreCase}:{}}}))},target:M==="ask_user"?{type:M,kind:tB,prompt:bB,notify:IB,expires_in_seconds:QB,choices:tB==="question"?ce.split(`
28
- `).map(T=>T.trim()).filter(Boolean):[]}:M==="block"?{type:M}:M==="inject_context"?{type:M,content:HB}:M==="job"?{type:M,job_id:mB}:M==="rewrite_command"?{type:M,argv:JSON.parse(XB),timeout_ms:ZB,rewrite_exit_codes:JSON.parse(WB),passthrough_exit_codes:JSON.parse($B)}:M==="orc_action"?{type:M,action:E,timeout_ms:H,...E==="sync_agent_memory"?{memory_directory:nB}:{},...E==="record_event"?{event_type:fe}:{}}:{type:M,mode:zB,argv:JSON.parse(VB),timeout_ms:yB}});Ke(""),t(d)}catch(d){Ke(d instanceof Error?d.message:String(d))}},MB=(d,T)=>$(_=>_.map((BB,uB)=>uB===d?{...BB,...T}:BB));return c.jsxs("div",{"data-testid":"event-rule-editor",className:"space-y-5 py-4",children:[c.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[c.jsxs("div",{children:[c.jsx(Y,{htmlFor:"event-rule-id",children:"Rule name"}),c.jsx(rB,{id:"event-rule-id","data-testid":"event-rule-id",value:C,onChange:d=>i(d.target.value)})]}),c.jsxs("div",{children:[c.jsx(Y,{htmlFor:"event-rule-reason",children:"Message / reason"}),c.jsx(rB,{id:"event-rule-reason","data-testid":"event-rule-reason",value:r,onChange:d=>a(d.target.value)})]})]}),c.jsxs("fieldset",{className:"space-y-3",children:[c.jsx("legend",{className:"font-medium mb-2",children:"1. Scope"}),c.jsx(Y,{htmlFor:"rule-agent",children:"Coding agent"}),c.jsxs("select",{id:"rule-agent","data-testid":"rule-agent",className:sB,value:u,onChange:d=>{D(d.target.value),I(["pre_tool"]),x([crypto.randomUUID()])},children:[c.jsx("option",{value:"all",children:"All agents"}),Object.entries(ve).map(([d,T])=>c.jsx("option",{value:d,children:T},d)),u.includes(",")&&c.jsx("option",{value:u,children:u})]}),c.jsx(Y,{children:"Events to listen to"}),f.map((d,T)=>c.jsxs("div",{className:"flex flex-wrap gap-2",children:[c.jsx("select",{"aria-label":`Event ${T+1}`,"data-testid":"rule-event",className:sB,value:d,onChange:_=>I(BB=>BB.map((uB,Mt)=>Mt===T?_.target.value:uB)),children:[...new Set(Te)].map(_=>c.jsx("option",{value:_,children:_.split("_").join(" ")},_))}),f.length>1&&c.jsx(dB,{variant:"outline",onClick:()=>{I(_=>_.filter((BB,uB)=>uB!==T)),x(_=>_.filter((BB,uB)=>uB!==T))},children:"Remove event"})]},w[T])),c.jsx(dB,{variant:"outline",disabled:f.length>=40,onClick:()=>{I(d=>[...d,"post_tool"]),x(d=>[...d,crypto.randomUUID()])},children:"Add event"}),c.jsx("div",{"data-testid":"rule-event-coverage",className:"text-xs text-muted-foreground space-y-1",children:ee.map(d=>c.jsxs("p",{children:[ve[d],":"," ",f.map(T=>{var _;return((_=ne[d].find(BB=>BB.event===T||`native:${BB.native}`===T))==null?void 0:_.native)??`${T} unavailable`}).join(", ")]},d))})]}),c.jsxs("fieldset",{className:"space-y-3",children:[c.jsx("legend",{className:"font-medium mb-2",children:"2. Filtering"}),c.jsxs("select",{"aria-label":"Combine conditions","data-testid":"rule-filter-match",className:sB,value:L,onChange:d=>y(d.target.value),children:[c.jsx("option",{value:"all",children:"Match all conditions (AND)"}),c.jsx("option",{value:"any",children:"Match any condition (OR)"})]}),R.map((d,T)=>c.jsxs("div",{"data-testid":"rule-condition",className:"space-y-2 border-l border-outline-variant pl-3 py-1",children:[c.jsxs("div",{className:"grid gap-2 md:grid-cols-3",children:[c.jsx(rB,{"aria-label":`Field ${T+1}`,"data-testid":"rule-filter-field",value:d.field,placeholder:"input.command or payload.prompt",onChange:_=>MB(T,{field:_.target.value})}),c.jsx("select",{"aria-label":`Operator ${T+1}`,"data-testid":"rule-filter-operator",className:sB,value:d.operator,onChange:_=>MB(T,{operator:_.target.value}),children:[["regex","Regex"],["contains","Contains"],["equals","Equals"],["in","In list (JSON)"],["starts_with","Starts with"],["ends_with","Ends with"],["exists","Exists"]].map(([_,BB])=>c.jsx("option",{value:_,children:BB},_))}),d.operator!=="exists"&&c.jsx(rB,{"aria-label":`Value ${T+1}`,"data-testid":"rule-filter-value",value:d.value,onChange:_=>MB(T,{value:_.target.value})})]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs",children:[d.operator==="equals"&&c.jsxs("select",{"aria-label":`Value type ${T+1}`,"data-testid":"rule-filter-value-type",className:sB,value:d.valueType,onChange:_=>MB(T,{valueType:_.target.value}),children:[c.jsx("option",{value:"string",children:"Text value"}),c.jsx("option",{value:"json",children:"JSON scalar (number, boolean, null)"})]}),c.jsxs("label",{children:[c.jsx("input",{type:"checkbox",checked:d.negate,onChange:_=>MB(T,{negate:_.target.checked})})," ","Negate (NOT)"]}),["regex","contains","starts_with","ends_with"].includes(d.operator)&&c.jsxs("label",{children:[c.jsx("input",{type:"checkbox",checked:d.ignoreCase,onChange:_=>MB(T,{ignoreCase:_.target.checked})})," ","Ignore case"]}),c.jsx(dB,{variant:"ghost",onClick:()=>$(_=>_.filter((BB,uB)=>uB!==T)),children:"Remove condition"})]})]},d.key)),c.jsx(dB,{variant:"outline",disabled:R.length>=32,onClick:()=>$(d=>[...d,{key:crypto.randomUUID(),field:"tool",operator:"equals",value:"",valueType:"string",negate:!1,ignoreCase:!1}]),children:"Add condition"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"No conditions matches every selected event. Regex uses RE2 syntax. Filters apply equally to every target."})]}),c.jsxs("fieldset",{className:"space-y-3",children:[c.jsx("legend",{className:"font-medium mb-2","data-testid":"rule-target-heading",children:"3. Target"}),c.jsxs("select",{"aria-label":"Target","data-testid":"rule-target",className:sB,value:M,onChange:d=>cB(d.target.value),children:[c.jsxs("option",{value:"block",disabled:!gB("block"),children:["Block",gB("block")?"":" (unavailable for this scope)"]}),c.jsxs("option",{value:"inject_context",disabled:!gB("context"),children:["Inject context",gB("context")?"":" (unavailable for this scope)"]}),c.jsx("option",{value:"job",children:"Run ORC job"}),c.jsx("option",{value:"ask_user",disabled:!gB("block"),children:"Ask user"}),c.jsx("option",{value:"script",children:"Run custom script"}),c.jsx("option",{value:"orc_action",children:"Run built-in ORC action"}),c.jsxs("option",{value:"rewrite_command",disabled:!gB("rewrite_command"),children:["Rewrite command with a processor",gB("rewrite_command")?"":" (select Claude pre tool)"]})]}),M==="ask_user"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx(Y,{htmlFor:"rule-request-kind",children:"Request"}),c.jsxs("select",{id:"rule-request-kind","data-testid":"rule-request-kind",className:sB,value:tB,onChange:d=>DB(d.target.value),children:[c.jsx("option",{value:"approval",children:"Approve or deny the proposed action"}),c.jsx("option",{value:"question",disabled:!gB("context"),children:"Answer a question"})]}),c.jsx(Y,{htmlFor:"rule-request-prompt",children:"Question / approval prompt"}),c.jsx(rB,{id:"rule-request-prompt","data-testid":"rule-request-prompt",value:bB,onChange:d=>le(d.target.value)}),c.jsx(Y,{htmlFor:"rule-request-expiry",children:"Wait limit (seconds)"}),c.jsx(rB,{id:"rule-request-expiry","data-testid":"rule-request-expiry",type:"number",min:1,max:604800,value:QB,onChange:d=>YB(Number(d.target.value))}),c.jsx("p",{className:"text-xs text-outline",children:"Expiration never grants approval. An installed native hook's timeout must be longer than this limit."}),tB==="question"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-request-choices",children:"Choices (one per line, optional)"}),c.jsx("textarea",{id:"rule-request-choices","data-testid":"rule-request-choices",className:sB,value:ce,onChange:d=>qB(d.target.value)})]}),c.jsx("p",{className:"text-xs text-outline",children:"Waits in Attention needed. Approval lets the agent act with its existing permissions."}),c.jsx("div",{className:"flex gap-4 text-sm",children:["telegram","slack"].map(d=>c.jsxs("label",{className:"flex gap-2 items-center",children:[c.jsx("input",{type:"checkbox","data-testid":`rule-notify-${d}`,checked:IB.includes(d),onChange:T=>Q(T.target.checked?[...IB,d]:IB.filter(_=>_!==d))}),"Notify ",d==="telegram"?"Telegram":"Slack"]},d))}),c.jsx("p",{className:"text-xs text-outline",children:"Uses authorized gateway chats with the same selected project. Channel replies never grant extra privileges."})]}),M==="orc_action"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-orc-action",children:"ORC action"}),c.jsx("select",{id:"rule-orc-action","data-testid":"rule-orc-action",className:sB,value:E,onChange:d=>N(d.target.value),children:kt.map(d=>c.jsx("option",{value:d,children:d.split("_").join(" ")},d))}),E==="sync_agent_memory"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-memory-directory",children:"Claude memory directory"}),c.jsx(rB,{id:"rule-memory-directory","data-testid":"rule-memory-directory",value:nB,onChange:d=>TB(d.target.value)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Use auto or the absolute local directory. Only Markdown topic files inside that directory are shared. Session end catches writes without file-tool events."})]}),E==="record_event"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-record-event-type",children:"Recorded event type"}),c.jsx("select",{id:"rule-record-event-type","data-testid":"rule-record-event-type",className:sB,value:fe,onChange:d=>Pt(d.target.value),children:["auto","file","task","rule","decision","git","env","error","plan","intent","subagent"].map(d=>c.jsx("option",{value:d,children:d},d))})]}),c.jsx(Y,{htmlFor:"rule-orc-timeout",children:"Action timeout (milliseconds)"}),c.jsx(rB,{id:"rule-orc-timeout","data-testid":"rule-orc-timeout",type:"number",min:100,max:2e3,value:H,onChange:d=>V(Number(d.target.value))}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Uses the existing ORC services and agent connection. Failures are visible in action history."})]}),M==="inject_context"&&c.jsx("textarea",{"aria-label":"Context to inject","data-testid":"rule-context",className:`${sB} min-h-24`,value:HB,onChange:d=>Le(d.target.value)}),M==="job"&&c.jsxs(c.Fragment,{children:[c.jsxs("select",{"aria-label":"ORC job","data-testid":"rule-job",className:sB,value:mB,onChange:d=>PB(d.target.value),children:[c.jsx("option",{value:"",children:"Select an enabled job"}),(qe=He.data)==null?void 0:qe.filter(d=>(d.project_id??null)===B&&!d.command.startsWith("__internal:")).map(d=>c.jsx("option",{value:d.id,children:d.name},d.id))]}),He.error&&c.jsx("p",{role:"alert",children:String(He.error)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Jobs run in the background and must belong to this policy's project."})]}),M==="script"&&c.jsxs(c.Fragment,{children:[c.jsxs("select",{"aria-label":"Script mode","data-testid":"rule-script-mode",className:sB,value:zB,onChange:d=>be(d.target.value),children:[c.jsx("option",{value:"sync",children:"Synchronous — return a decision or context"}),c.jsx("option",{value:"background",children:"Background — run through the job queue"})]}),c.jsx(Y,{htmlFor:"rule-script-argv",children:"Executable and arguments (JSON array)"}),c.jsx("textarea",{id:"rule-script-argv","data-testid":"rule-script-argv",className:`${sB} min-h-24 font-mono`,value:VB,onChange:d=>ue(d.target.value)}),c.jsx(Y,{htmlFor:"rule-script-timeout",children:"Timeout (milliseconds)"}),c.jsx(rB,{id:"rule-script-timeout","data-testid":"rule-script-timeout",type:"number",min:100,max:zB==="sync"?2e3:3e4,value:yB,onChange:d=>he(Number(d.target.value))}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Event JSON is sent to stdin. Synchronous stdout:"," ",'{"decision":"abstain","context":["..."]}'," or ",'{"decision":"deny","reason":"..."}',". Blocking/context results require event support. Background output is recorded in Jobs."]})]}),M==="rewrite_command"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-processor-argv",children:"Command processor (executable and arguments)"}),c.jsx("textarea",{id:"rule-processor-argv","data-testid":"rule-processor-argv",className:`${sB} min-h-24 font-mono`,value:XB,onChange:d=>De(d.target.value)}),c.jsx(Y,{htmlFor:"rule-processor-timeout",children:"Timeout (milliseconds)"}),c.jsx(rB,{id:"rule-processor-timeout","data-testid":"rule-processor-timeout",type:"number",min:100,max:2e3,value:ZB,onChange:d=>ge(Number(d.target.value))}),c.jsx(Y,{htmlFor:"rule-processor-rewrite-codes",children:"Exit codes returning a replacement (JSON array)"}),c.jsx(rB,{id:"rule-processor-rewrite-codes","data-testid":"rule-processor-rewrite-codes",value:WB,onChange:d=>pe(d.target.value)}),c.jsx(Y,{htmlFor:"rule-processor-passthrough-codes",children:"Exit codes keeping the original command (JSON array)"}),c.jsx(rB,{id:"rule-processor-passthrough-codes","data-testid":"rule-processor-passthrough-codes",value:$B,onChange:d=>Ee(d.target.value)}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use any trusted local CLI. Event JSON goes to stdin; ","{command}"," as a complete argument passes the original command without shell interpolation. Stdout must contain the replacement command. Claude Bash executes it and returns its output, with normal permission checks. RTK example: rewrite codes [0, 3], passthrough [1]. Other failures block the call."]})]})]}),c.jsxs("label",{className:"flex flex-wrap gap-2 text-sm",children:[c.jsx("input",{"data-testid":"event-rule-enabled",type:"checkbox",checked:Be,onChange:d=>de(d.target.checked)})," ","Enabled"]}),Ue&&c.jsx("p",{role:"alert","data-testid":"event-rule-error",className:"text-xs whitespace-pre-wrap",children:Ue}),c.jsx(dB,{"data-testid":"event-rule-save",disabled:e||M==="block"&&!gB("block")||M==="inject_context"&&!gB("context")||M==="rewrite_command"&&!gB("rewrite_command"),onClick:yt,children:s?"Save rule changes":"Save rule"})]})}const ke="w-full rounded-md border border-control-border bg-background p-2 text-sm",Nt=["claude","codex","cursor","gemini"];function GB(n){const B=n.trim().split("\\").join("/"),e=B.length>1?B.replace(/\/+$/,""):B;return/^[a-z]:\//i.test(B)||B.startsWith("//")?e.toLowerCase():e}function xt(n){return n.target.type==="orc_action"?n.target.action.split("_").join(" "):n.target.type.split("_").join(" ")}function js(){var he,XB,De,ZB,ge,WB,pe,$B,Ee,Be,de;const n=Kt(),B=qt({queryKey:["rules"],queryFn:()=>te.rules.list(),retry:!1}),e=Qt(),[t,s]=Ve("tab","applied",["applied","settings"]),[C,i]=Ve("workspace",""),[r,a]=S.useState(""),[u,D]=S.useState(""),[f,I]=S.useState(""),[w,x]=S.useState({}),[L,y]=S.useState(!1),[R,$]=S.useState(),[M,cB]=S.useState(),[tB,DB]=S.useState(),[bB,le]=S.useState(""),[ce,qB]=S.useState(0),IB=S.useRef(null);S.useEffect(()=>{if(!L)return;const E=requestAnimationFrame(()=>{var N;return(N=document.getElementById("event-rule-id"))==null?void 0:N.focus()});return()=>cancelAnimationFrame(E)},[L]);const Q=(he=B.data)==null?void 0:he.history.find(E=>E.current&&GB(E.workspace)===GB(C)),QB=((XB=B.data)==null?void 0:XB.history.filter(E=>E.current&&E.policy&&(!C||GB(E.workspace)===GB(C))))??[];function YB(E,N=!1){var H;i(E,{replace:N}),sessionStorage.setItem("orc_rules_workspace",E),L&&!R&&DB((H=B.data)==null?void 0:H.history.find(V=>V.current&&GB(V.workspace)===GB(E)))}S.useEffect(()=>{a((Q==null?void 0:Q.project_id)??""),x({})},[Q]);function HB(E){I(E),n.invalidateQueries({queryKey:["rules"]})}function Le(){var E;return(((E=Q==null?void 0:Q.policy)==null?void 0:E.rules)??[]).map(N=>{if(!w[N.id])return N;const H=w[N.id];return oe.parse({...N,scope:{...N.scope,agents:H==="all"?"all":H.split(",")}})})}const mB=me({mutationFn:E=>{var H,V;const N=tB;if((H=N==null?void 0:N.policy)!=null&&H.rules.some(nB=>nB.id===E.id&&nB.id!==(R==null?void 0:R.id)))throw new Error("A rule with this name already exists.");return te.rules.activate({workspace:C.trim(),project_id:N?N.project_id:r||null,rules:[...((V=N==null?void 0:N.policy)==null?void 0:V.rules.filter(nB=>nB.id!==((R==null?void 0:R.id)??E.id)))??[],E]},(N==null?void 0:N.id)??null,u.trim()||(R?"Updated ":"Added ")+E.id)},onSuccess:()=>{y(!1),$(void 0),cB(void 0),HB("Rule saved.")}}),PB=me({mutationFn:()=>{const E=Le();return te.rules.activate({workspace:C.trim(),project_id:r||null,rules:E},(Q==null?void 0:Q.id)??null,u.trim()||"Updated rule settings")},onSuccess:()=>HB("Settings saved.")}),VB=me({mutationFn:({policy:E,rule:N})=>{var H;return te.rules.activate({workspace:E.workspace,project_id:E.project_id,rules:((H=E.policy)==null?void 0:H.rules.map(V=>V.id===N.id?{...N,enabled:!N.enabled}:V))??[]},E.id,(N.enabled?"Disabled ":"Enabled ")+N.id)},onSuccess:()=>HB("Rule status updated."),onError:E=>I(String(E))}),ue=me({mutationFn:E=>te.rules.revert(E,u.trim()||"Restored previous rule policy"),onSuccess:()=>HB("Previous policy restored."),onError:E=>I(String(E))});function zB(E){IB.current=E,mB.reset(),$(void 0),cB(void 0),DB(Q),le(""),qB(N=>N+1),y(!0)}function be(E,N,H){IB.current=H,mB.reset(),YB(E.workspace),DB(E),a(E.project_id??""),$(structuredClone(N)),cB(void 0),qB(V=>V+1),y(!0)}function yB(){var E,N;return c.jsxs("div",{className:"grid gap-4 sm:grid-cols-[2fr_1fr]",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Y,{htmlFor:"rules-workspace",children:"Workspace directory"}),c.jsx(rB,{id:"rules-workspace","data-testid":"rules-workspace",list:"rule-workspaces",value:C,disabled:L&&!!tB,onChange:H=>YB(H.target.value,!0),placeholder:"Absolute project directory"}),c.jsx("datalist",{id:"rule-workspaces",children:(E=B.data)==null?void 0:E.history.filter(H=>H.current).map(H=>c.jsx("option",{value:H.workspace},H.id))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Y,{htmlFor:"rule-policy-project",children:"Project"}),c.jsxs("select",{id:"rule-policy-project","data-testid":"rule-policy-project",className:ke,value:r,disabled:L&&!!tB,onChange:H=>a(H.target.value),children:[c.jsx("option",{value:"",children:"Unassigned"}),(N=e.data)==null?void 0:N.map(H=>c.jsx("option",{value:H.id,children:H.name},H.id))]})]})]})}return c.jsxs("section",{"data-testid":"rules-panel",className:"space-y-4",children:[B.error&&c.jsx("p",{role:"alert","data-testid":"rules-error",children:c.jsx("span",{"data-testid":"page-error",children:String(B.error)})}),c.jsxs(Yt,{value:t,onValueChange:s,children:[c.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[c.jsxs(Vt,{className:"h-auto max-w-full flex-wrap",children:[c.jsx(ze,{value:"applied","data-testid":"rules-applied-tab",children:"Applied rules"}),c.jsx(ze,{value:"settings","data-testid":"rules-settings-tab",children:"Settings"})]}),c.jsx(dB,{"data-testid":"rule-new",onClick:E=>zB(E.currentTarget),children:"Add rule"})]}),c.jsxs(Xe,{value:"applied",className:"space-y-4 pt-3",children:[c.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-4",children:[c.jsxs("select",{"data-testid":"rules-workspace-filter","aria-label":"Filter by workspace",className:"w-full min-w-0 max-w-full rounded-md border border-control-border bg-background p-2 text-sm sm:max-w-sm",value:(Q==null?void 0:Q.workspace)??C,onChange:E=>YB(E.target.value),children:[c.jsx("option",{value:"",children:"All workspaces"}),C&&!Q&&c.jsx("option",{value:C,children:C}),(De=B.data)==null?void 0:De.history.filter(E=>E.current).map(E=>{var N,H;return c.jsx("option",{value:E.workspace,children:((H=(N=e.data)==null?void 0:N.find(V=>V.id===E.project_id))==null?void 0:H.name)??E.workspace},E.id)})]}),c.jsxs("span",{"data-testid":"rules-status",className:"text-xs text-muted-foreground",children:["Enforcement ",(ZB=B.data)!=null&&ZB.enabled?"on":"off"]})]}),c.jsxs("div",{className:"overflow-x-auto",children:[c.jsxs("table",{"data-testid":"applied-rules-table",className:"w-full min-w-[860px] table-fixed text-left text-sm",children:[c.jsxs("colgroup",{children:[c.jsx("col",{style:{width:"18%"}}),c.jsx("col",{style:{width:"9%"}}),c.jsx("col",{style:{width:"10%"}}),c.jsx("col",{style:{width:"12%"}}),c.jsx("col",{style:{width:"17%"}}),c.jsx("col",{style:{width:"18%"}}),c.jsx("col",{style:{width:"136px"}})]}),c.jsx("thead",{className:"text-xs text-muted-foreground",children:c.jsx("tr",{children:["Rule","Status","Agents","Trigger","Action","Project / workspace","Actions"].map((E,N)=>c.jsx("th",{className:`px-3 py-3 font-medium ${N===6?"sticky right-0 bg-background":""}`,children:E},E))})}),QB.map(E=>{var N;return c.jsx("tbody",{"data-testid":"rule-revision","data-revision-id":E.id,children:(N=E.policy)==null?void 0:N.rules.map(H=>{var V,nB;return c.jsxs("tr",{"data-testid":"saved-event-rule",className:"border-t border-outline-variant",children:[c.jsx("td",{className:"px-3 py-3 font-medium",children:c.jsx("span",{className:"block truncate",title:H.id,children:H.id})}),c.jsx("td",{className:"px-4 py-3",children:H.enabled?"Enabled":"Disabled"}),c.jsx("td",{className:"px-3 py-3",children:H.scope.agents!=="all"?H.scope.agents.join(", "):"All agents"}),c.jsx("td",{className:"px-4 py-3 text-xs",children:H.scope.events.join(", ").split("_").join(" ")}),c.jsx("td",{className:"px-3 py-3",children:c.jsx("span",{className:"block truncate",title:xt(H),children:xt(H)})}),c.jsxs("td",{className:"px-4 py-3",children:[c.jsx("span",{className:"block truncate text-xs text-muted-foreground",title:E.workspace,children:((nB=(V=e.data)==null?void 0:V.find(TB=>TB.id===E.project_id))==null?void 0:nB.name)??"Unassigned"}),c.jsx("span",{className:"block truncate text-xs text-muted-foreground",title:E.workspace,children:E.workspace})]}),c.jsx("td",{className:"sticky right-0 bg-background px-3 py-3",children:c.jsxs("div",{className:"flex flex-wrap gap-2",children:[c.jsx(dB,{variant:"outline",size:"sm","data-testid":"event-rule-edit",onClick:TB=>be(E,H,TB.currentTarget),children:"Edit"}),c.jsx(dB,{variant:"ghost",size:"sm","data-testid":"event-rule-toggle",disabled:VB.isPending,onClick:()=>VB.mutate({policy:E,rule:H}),children:H.enabled?"Disable":"Enable"})]})})]},H.id)})},E.id)})]}),B.isPending&&c.jsx("p",{role:"status","data-testid":"page-loading",className:"p-8 text-sm text-muted-foreground",children:"Loading rules…"}),!B.isPending&&!B.error&&!QB.some(E=>{var N;return(N=E.policy)==null?void 0:N.rules.length})&&c.jsx("div",{className:"p-10 text-center text-sm text-muted-foreground","data-testid":"rules-empty",children:c.jsx("span",{"data-testid":"page-empty",children:"No applied rules. Add a rule from scratch or choose a template."})})]})]}),c.jsx(Xe,{value:"settings",className:"space-y-6 pt-4",children:!L&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4",children:[c.jsx("h3",{className:"font-medium",children:"Applies to"}),yB(),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Rules apply in this directory and its subdirectories."})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Y,{htmlFor:"rules-reason",children:"Change note (optional)"}),c.jsx(rB,{id:"rules-reason","data-testid":"rules-reason",value:u,onChange:E=>D(E.target.value)})]}),((ge=Q==null?void 0:Q.policy)==null?void 0:ge.rules.length)&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("h3",{className:"font-medium",children:"Agent assignments"}),Q.policy.rules.map(E=>c.jsxs("div",{className:"grid items-center gap-3 sm:grid-cols-2",children:[c.jsx(Y,{htmlFor:`agent-${E.id}`,children:E.id}),c.jsxs("select",{id:`agent-${E.id}`,"data-testid":"rule-agent-assignment",className:ke,value:w[E.id]??(E.scope.agents==="all"?"all":E.scope.agents.join(",")),onChange:N=>x(H=>({...H,[E.id]:N.target.value})),children:[c.jsx("option",{value:"all",children:"All agents"}),Nt.map(N=>c.jsx("option",{value:N,children:N},N)),E.scope.agents!=="all"&&E.scope.agents.length>1&&c.jsx("option",{value:E.scope.agents.join(","),children:E.scope.agents.join(", ")})]})]},E.id))]}),c.jsx(dB,{"data-testid":"rules-settings-save",disabled:PB.isPending||!C.trim()||!((WB=Q==null?void 0:Q.policy)!=null&&WB.rules.length),onClick:()=>PB.mutate(),children:"Save settings"}),PB.error&&c.jsx("p",{role:"alert","data-testid":"rules-settings-error",children:String(PB.error)}),c.jsxs("details",{"data-testid":"rule-connections",className:"space-y-3 border-t border-outline-variant pt-4",children:[c.jsx("summary",{className:"cursor-pointer font-medium",children:"Agent connections"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Claude SDK sessions connect when rule enforcement is enabled. Native agents need installed, trusted hooks and a supported host."}),Nt.map(E=>c.jsx("p",{className:"text-xs break-all",children:c.jsxs("code",{children:["orc rules install-hook ",E,' --target "',C?`${C.split("\\").join("/")}/`:"",".",E==="gemini"?"gemini":E,"/",E==="cursor"||E==="codex"?"hooks":"settings",'.json"']})},E))]}),c.jsxs("details",{"data-testid":"rules-history",className:"space-y-3 border-t border-outline-variant pt-4",children:[c.jsx("summary",{className:"cursor-pointer font-medium",children:"Policy history"}),(pe=B.data)==null?void 0:pe.history.filter(E=>!C||GB(E.workspace)===GB(C)).map(E=>c.jsxs("div",{"data-testid":"rule-history-entry",className:"space-y-2 border-t border-outline-variant py-3 text-xs",children:[c.jsxs("p",{className:"break-all",children:[E.workspace," · ",E.current?"Current":"Historical"," ·"," ",E.policy?`${E.policy.rules.length} rules`:"Disabled"]}),c.jsx("p",{children:E.reason}),E.current&&c.jsx(dB,{size:"sm","data-testid":"rule-revert",disabled:ue.isPending,onClick:()=>ue.mutate(E.id),children:"Restore previous policy"}),c.jsxs("details",{children:[c.jsx("summary",{children:"View policy"}),c.jsx("pre",{className:"whitespace-pre-wrap break-all",children:JSON.stringify(E.policy,null,2)})]})]},E.id))]}),c.jsxs("details",{"data-testid":"rules-decisions",className:"border-t border-outline-variant pt-4",children:[c.jsx("summary",{className:"cursor-pointer font-medium",children:"Activity"}),c.jsx("pre",{className:"text-xs whitespace-pre-wrap break-all",children:JSON.stringify({decisions:($B=B.data)==null?void 0:$B.decisions,actions:(Ee=B.data)==null?void 0:Ee.actions},null,2)})]})]})})]}),c.jsx(zt,{open:L,onOpenChange:y,children:c.jsxs(Xt,{className:"w-[640px] max-w-[100vw]","data-testid":"rule-editor-panel","aria-describedby":"rule-editor-description",onOpenAutoFocus:E=>{var N;L&&(E.preventDefault(),(N=document.getElementById("event-rule-id"))==null||N.focus())},onCloseAutoFocus:E=>{var N;E.preventDefault(),(N=IB.current)==null||N.focus()},children:[c.jsxs(Zt,{children:[c.jsx(Wt,{children:R?`Edit ${R.id}`:"Add rule"}),c.jsx($t,{id:"rule-editor-description",children:"Select a template to fill the form, or define a rule from scratch."})]}),c.jsxs(Bs,{className:"space-y-4","data-testid":"rule-editor-region",children:[!R&&c.jsxs("div",{className:"space-y-2","data-testid":"rule-catalog",children:[c.jsx(Y,{htmlFor:"rule-template",children:"Start with"}),c.jsxs("select",{id:"rule-template","data-testid":"rule-template",className:ke,value:bB,onChange:E=>{var V;const N=E.target.value;le(N);const H=N?Ms(N):void 0;if(H){const nB=new Set((V=tB==null?void 0:tB.policy)==null?void 0:V.rules.map(fe=>fe.id));let TB=2;for(;nB.has(H.id);)H.id=`${N}-${TB++}`}cB(H),qB(nB=>nB+1)},children:[c.jsx("option",{value:"",children:"From scratch"}),Ae.map(E=>c.jsx("option",{value:E.id,children:E.name},E.id))]}),bB&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("p",{"data-testid":"rule-template-description",className:"text-sm",children:(Be=Ae.find(E=>E.id===bB))==null?void 0:Be.description}),c.jsx("p",{"data-testid":"rule-template-limits",className:"text-xs text-muted-foreground",children:(de=Ae.find(E=>E.id===bB))==null?void 0:de.configuration})]})]}),C.trim()?c.jsxs("details",{className:"space-y-3",children:[c.jsxs("summary",{className:"cursor-pointer text-xs text-muted-foreground",children:["Applies to ",C]}),yB()]}):yB(),c.jsx(Js,{rule:R??M,isEditing:!!R,projectId:tB?tB.project_id:r||null,pending:mB.isPending||!C.trim(),onSave:E=>mB.mutate(E)},`${(R==null?void 0:R.id)??"new"}:${ce}`),mB.error&&c.jsx("p",{role:"alert","data-testid":"rule-save-error",children:String(mB.error)})]})]})}),f&&c.jsx("p",{role:"status","data-testid":"rules-message",className:"text-sm",children:f})]})}function Qs(){return c.jsxs("div",{"data-testid":"rules-view",children:[c.jsx(es,{title:"Rules"}),c.jsx("div",{className:"max-w-4xl",children:c.jsx(js,{})})]})}export{Qs as default};
28
+ `).map(T=>T.trim()).filter(Boolean):[]}:M==="block"?{type:M}:M==="inject_context"?{type:M,content:HB}:M==="job"?{type:M,job_id:mB}:M==="rewrite_command"?{type:M,argv:JSON.parse(XB),timeout_ms:ZB,rewrite_exit_codes:JSON.parse(WB),passthrough_exit_codes:JSON.parse($B)}:M==="orc_action"?{type:M,action:E,timeout_ms:H,...E==="sync_agent_memory"?{memory_directory:nB}:{},...E==="record_event"?{event_type:fe}:{}}:{type:M,mode:zB,argv:JSON.parse(VB),timeout_ms:yB}});Ke(""),t(d)}catch(d){Ke(d instanceof Error?d.message:String(d))}},MB=(d,T)=>$(_=>_.map((BB,uB)=>uB===d?{...BB,...T}:BB));return c.jsxs("div",{"data-testid":"event-rule-editor",className:"space-y-5 py-4",children:[c.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[c.jsxs("div",{children:[c.jsx(Y,{htmlFor:"event-rule-id",children:"Rule name"}),c.jsx(rB,{id:"event-rule-id","data-testid":"event-rule-id",value:C,onChange:d=>i(d.target.value)})]}),c.jsxs("div",{children:[c.jsx(Y,{htmlFor:"event-rule-reason",children:"Message / reason"}),c.jsx(rB,{id:"event-rule-reason","data-testid":"event-rule-reason",value:r,onChange:d=>a(d.target.value)})]})]}),c.jsxs("fieldset",{className:"space-y-3",children:[c.jsx("legend",{className:"font-medium mb-2",children:"1. Scope"}),c.jsx(Y,{htmlFor:"rule-agent",children:"Coding agent"}),c.jsxs("select",{id:"rule-agent","data-testid":"rule-agent",className:sB,value:u,onChange:d=>{D(d.target.value),I(["pre_tool"]),x([crypto.randomUUID()])},children:[c.jsx("option",{value:"all",children:"All agents"}),Object.entries(ve).map(([d,T])=>c.jsx("option",{value:d,children:T},d)),u.includes(",")&&c.jsx("option",{value:u,children:u})]}),c.jsx(Y,{children:"Events to listen to"}),f.map((d,T)=>c.jsxs("div",{className:"flex flex-wrap gap-2",children:[c.jsx("select",{"aria-label":`Event ${T+1}`,"data-testid":"rule-event",className:sB,value:d,onChange:_=>I(BB=>BB.map((uB,Mt)=>Mt===T?_.target.value:uB)),children:[...new Set(Te)].map(_=>c.jsx("option",{value:_,children:_.split("_").join(" ")},_))}),f.length>1&&c.jsx(dB,{variant:"outline",onClick:()=>{I(_=>_.filter((BB,uB)=>uB!==T)),x(_=>_.filter((BB,uB)=>uB!==T))},children:"Remove event"})]},w[T])),c.jsx(dB,{variant:"outline",disabled:f.length>=40,onClick:()=>{I(d=>[...d,"post_tool"]),x(d=>[...d,crypto.randomUUID()])},children:"Add event"}),c.jsx("div",{"data-testid":"rule-event-coverage",className:"text-xs text-muted-foreground space-y-1",children:ee.map(d=>c.jsxs("p",{children:[ve[d],":"," ",f.map(T=>{var _;return((_=ne[d].find(BB=>BB.event===T||`native:${BB.native}`===T))==null?void 0:_.native)??`${T} unavailable`}).join(", ")]},d))})]}),c.jsxs("fieldset",{className:"space-y-3",children:[c.jsx("legend",{className:"font-medium mb-2",children:"2. Filtering"}),c.jsxs("select",{"aria-label":"Combine conditions","data-testid":"rule-filter-match",className:sB,value:L,onChange:d=>y(d.target.value),children:[c.jsx("option",{value:"all",children:"Match all conditions (AND)"}),c.jsx("option",{value:"any",children:"Match any condition (OR)"})]}),R.map((d,T)=>c.jsxs("div",{"data-testid":"rule-condition",className:"space-y-2 border-l border-outline-variant pl-3 py-1",children:[c.jsxs("div",{className:"grid gap-2 md:grid-cols-3",children:[c.jsx(rB,{"aria-label":`Field ${T+1}`,"data-testid":"rule-filter-field",value:d.field,placeholder:"input.command or payload.prompt",onChange:_=>MB(T,{field:_.target.value})}),c.jsx("select",{"aria-label":`Operator ${T+1}`,"data-testid":"rule-filter-operator",className:sB,value:d.operator,onChange:_=>MB(T,{operator:_.target.value}),children:[["regex","Regex"],["contains","Contains"],["equals","Equals"],["in","In list (JSON)"],["starts_with","Starts with"],["ends_with","Ends with"],["exists","Exists"]].map(([_,BB])=>c.jsx("option",{value:_,children:BB},_))}),d.operator!=="exists"&&c.jsx(rB,{"aria-label":`Value ${T+1}`,"data-testid":"rule-filter-value",value:d.value,onChange:_=>MB(T,{value:_.target.value})})]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs",children:[d.operator==="equals"&&c.jsxs("select",{"aria-label":`Value type ${T+1}`,"data-testid":"rule-filter-value-type",className:sB,value:d.valueType,onChange:_=>MB(T,{valueType:_.target.value}),children:[c.jsx("option",{value:"string",children:"Text value"}),c.jsx("option",{value:"json",children:"JSON scalar (number, boolean, null)"})]}),c.jsxs("label",{children:[c.jsx("input",{type:"checkbox",checked:d.negate,onChange:_=>MB(T,{negate:_.target.checked})})," ","Negate (NOT)"]}),["regex","contains","starts_with","ends_with"].includes(d.operator)&&c.jsxs("label",{children:[c.jsx("input",{type:"checkbox",checked:d.ignoreCase,onChange:_=>MB(T,{ignoreCase:_.target.checked})})," ","Ignore case"]}),c.jsx(dB,{variant:"ghost",onClick:()=>$(_=>_.filter((BB,uB)=>uB!==T)),children:"Remove condition"})]})]},d.key)),c.jsx(dB,{variant:"outline",disabled:R.length>=32,onClick:()=>$(d=>[...d,{key:crypto.randomUUID(),field:"tool",operator:"equals",value:"",valueType:"string",negate:!1,ignoreCase:!1}]),children:"Add condition"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"No conditions matches every selected event. Regex uses RE2 syntax. Filters apply equally to every target."})]}),c.jsxs("fieldset",{className:"space-y-3",children:[c.jsx("legend",{className:"font-medium mb-2","data-testid":"rule-target-heading",children:"3. Target"}),c.jsxs("select",{"aria-label":"Target","data-testid":"rule-target",className:sB,value:M,onChange:d=>cB(d.target.value),children:[c.jsxs("option",{value:"block",disabled:!gB("block"),children:["Block",gB("block")?"":" (unavailable for this scope)"]}),c.jsxs("option",{value:"inject_context",disabled:!gB("context"),children:["Inject context",gB("context")?"":" (unavailable for this scope)"]}),c.jsx("option",{value:"job",children:"Run ORC job"}),c.jsx("option",{value:"ask_user",disabled:!gB("block"),children:"Ask user"}),c.jsx("option",{value:"script",children:"Run custom script"}),c.jsx("option",{value:"orc_action",children:"Run built-in ORC action"}),c.jsxs("option",{value:"rewrite_command",disabled:!gB("rewrite_command"),children:["Rewrite command with a processor",gB("rewrite_command")?"":" (select Claude pre tool)"]})]}),M==="ask_user"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx(Y,{htmlFor:"rule-request-kind",children:"Request"}),c.jsxs("select",{id:"rule-request-kind","data-testid":"rule-request-kind",className:sB,value:tB,onChange:d=>DB(d.target.value),children:[c.jsx("option",{value:"approval",children:"Approve or deny the proposed action"}),c.jsx("option",{value:"question",disabled:!gB("context"),children:"Answer a question"})]}),c.jsx(Y,{htmlFor:"rule-request-prompt",children:"Question / approval prompt"}),c.jsx(rB,{id:"rule-request-prompt","data-testid":"rule-request-prompt",value:bB,onChange:d=>le(d.target.value)}),c.jsx(Y,{htmlFor:"rule-request-expiry",children:"Wait limit (seconds)"}),c.jsx(rB,{id:"rule-request-expiry","data-testid":"rule-request-expiry",type:"number",min:1,max:604800,value:QB,onChange:d=>YB(Number(d.target.value))}),c.jsx("p",{className:"text-xs text-outline",children:"Expiration never grants approval. An installed native hook's timeout must be longer than this limit."}),tB==="question"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-request-choices",children:"Choices (one per line, optional)"}),c.jsx("textarea",{id:"rule-request-choices","data-testid":"rule-request-choices",className:sB,value:ce,onChange:d=>qB(d.target.value)})]}),c.jsx("p",{className:"text-xs text-outline",children:"Waits in Attention needed. Approval lets the agent act with its existing permissions."}),c.jsx("div",{className:"flex gap-4 text-sm",children:["telegram","slack"].map(d=>c.jsxs("label",{className:"flex gap-2 items-center",children:[c.jsx("input",{type:"checkbox","data-testid":`rule-notify-${d}`,checked:IB.includes(d),onChange:T=>Q(T.target.checked?[...IB,d]:IB.filter(_=>_!==d))}),"Notify ",d==="telegram"?"Telegram":"Slack"]},d))}),c.jsx("p",{className:"text-xs text-outline",children:"Uses authorized gateway chats with the same selected project. Channel replies never grant extra privileges."})]}),M==="orc_action"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-orc-action",children:"ORC action"}),c.jsx("select",{id:"rule-orc-action","data-testid":"rule-orc-action",className:sB,value:E,onChange:d=>N(d.target.value),children:kt.map(d=>c.jsx("option",{value:d,children:d.split("_").join(" ")},d))}),E==="sync_agent_memory"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-memory-directory",children:"Claude memory directory"}),c.jsx(rB,{id:"rule-memory-directory","data-testid":"rule-memory-directory",value:nB,onChange:d=>TB(d.target.value)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Use auto or the absolute local directory. Only Markdown topic files inside that directory are shared. Session end catches writes without file-tool events."})]}),E==="record_event"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-record-event-type",children:"Recorded event type"}),c.jsx("select",{id:"rule-record-event-type","data-testid":"rule-record-event-type",className:sB,value:fe,onChange:d=>Pt(d.target.value),children:["auto","file","task","rule","decision","git","env","error","plan","intent","subagent"].map(d=>c.jsx("option",{value:d,children:d},d))})]}),c.jsx(Y,{htmlFor:"rule-orc-timeout",children:"Action timeout (milliseconds)"}),c.jsx(rB,{id:"rule-orc-timeout","data-testid":"rule-orc-timeout",type:"number",min:100,max:2e3,value:H,onChange:d=>V(Number(d.target.value))}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Uses the existing ORC services and agent connection. Failures are visible in action history."})]}),M==="inject_context"&&c.jsx("textarea",{"aria-label":"Context to inject","data-testid":"rule-context",className:`${sB} min-h-24`,value:HB,onChange:d=>Le(d.target.value)}),M==="job"&&c.jsxs(c.Fragment,{children:[c.jsxs("select",{"aria-label":"ORC job","data-testid":"rule-job",className:sB,value:mB,onChange:d=>PB(d.target.value),children:[c.jsx("option",{value:"",children:"Select an enabled job"}),(qe=He.data)==null?void 0:qe.filter(d=>(d.project_id??null)===B&&!d.command.startsWith("__internal:")).map(d=>c.jsx("option",{value:d.id,children:d.name},d.id))]}),He.error&&c.jsx("p",{role:"alert",children:String(He.error)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Jobs run in the background and must belong to this policy's project."})]}),M==="script"&&c.jsxs(c.Fragment,{children:[c.jsxs("select",{"aria-label":"Script mode","data-testid":"rule-script-mode",className:sB,value:zB,onChange:d=>be(d.target.value),children:[c.jsx("option",{value:"sync",children:"Synchronous — return a decision or context"}),c.jsx("option",{value:"background",children:"Background — run through the job queue"})]}),c.jsx(Y,{htmlFor:"rule-script-argv",children:"Executable and arguments (JSON array)"}),c.jsx("textarea",{id:"rule-script-argv","data-testid":"rule-script-argv",className:`${sB} min-h-24 font-mono`,value:VB,onChange:d=>ue(d.target.value)}),c.jsx(Y,{htmlFor:"rule-script-timeout",children:"Timeout (milliseconds)"}),c.jsx(rB,{id:"rule-script-timeout","data-testid":"rule-script-timeout",type:"number",min:100,max:zB==="sync"?2e3:3e4,value:yB,onChange:d=>he(Number(d.target.value))}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Event JSON is sent to stdin. Synchronous stdout:"," ",'{"decision":"abstain","context":["..."]}'," or ",'{"decision":"deny","reason":"..."}',". Blocking/context results require event support. Background output is recorded in Jobs."]})]}),M==="rewrite_command"&&c.jsxs(c.Fragment,{children:[c.jsx(Y,{htmlFor:"rule-processor-argv",children:"Command processor (executable and arguments)"}),c.jsx("textarea",{id:"rule-processor-argv","data-testid":"rule-processor-argv",className:`${sB} min-h-24 font-mono`,value:XB,onChange:d=>De(d.target.value)}),c.jsx(Y,{htmlFor:"rule-processor-timeout",children:"Timeout (milliseconds)"}),c.jsx(rB,{id:"rule-processor-timeout","data-testid":"rule-processor-timeout",type:"number",min:100,max:2e3,value:ZB,onChange:d=>ge(Number(d.target.value))}),c.jsx(Y,{htmlFor:"rule-processor-rewrite-codes",children:"Exit codes returning a replacement (JSON array)"}),c.jsx(rB,{id:"rule-processor-rewrite-codes","data-testid":"rule-processor-rewrite-codes",value:WB,onChange:d=>pe(d.target.value)}),c.jsx(Y,{htmlFor:"rule-processor-passthrough-codes",children:"Exit codes keeping the original command (JSON array)"}),c.jsx(rB,{id:"rule-processor-passthrough-codes","data-testid":"rule-processor-passthrough-codes",value:$B,onChange:d=>Ee(d.target.value)}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use any trusted local CLI. Event JSON goes to stdin; ","{command}"," as a complete argument passes the original command without shell interpolation. Stdout must contain the replacement command. Claude Bash executes it and returns its output, with normal permission checks. RTK example: rewrite codes [0, 3], passthrough [1]. Other failures block the call."]})]})]}),c.jsxs("label",{className:"flex flex-wrap gap-2 text-sm",children:[c.jsx("input",{"data-testid":"event-rule-enabled",type:"checkbox",checked:Be,onChange:d=>de(d.target.checked)})," ","Enabled"]}),Ue&&c.jsx("p",{role:"alert","data-testid":"event-rule-error",className:"text-xs whitespace-pre-wrap",children:Ue}),c.jsx(dB,{"data-testid":"event-rule-save",disabled:e||M==="block"&&!gB("block")||M==="inject_context"&&!gB("context")||M==="rewrite_command"&&!gB("rewrite_command"),onClick:yt,children:s?"Save rule changes":"Save rule"})]})}const ke="w-full rounded-md border border-control-border bg-background p-2 text-sm",Nt=["claude","codex","cursor","gemini"];function GB(n){const B=n.trim().split("\\").join("/"),e=B.length>1?B.replace(/\/+$/,""):B;return/^[a-z]:\//i.test(B)||B.startsWith("//")?e.toLowerCase():e}function xt(n){return n.target.type==="orc_action"?n.target.action.split("_").join(" "):n.target.type.split("_").join(" ")}function js(){var he,XB,De,ZB,ge,WB,pe,$B,Ee,Be,de;const n=Kt(),B=qt({queryKey:["rules"],queryFn:()=>te.rules.list(),retry:!1}),e=Qt(),[t,s]=Xe("tab","applied",["applied","settings"]),[C,i]=Xe("workspace",""),[r,a]=S.useState(""),[u,D]=S.useState(""),[f,I]=S.useState(""),[w,x]=S.useState({}),[L,y]=S.useState(!1),[R,$]=S.useState(),[M,cB]=S.useState(),[tB,DB]=S.useState(),[bB,le]=S.useState(""),[ce,qB]=S.useState(0),IB=S.useRef(null);S.useEffect(()=>{if(!L)return;const E=requestAnimationFrame(()=>{var N;return(N=document.getElementById("event-rule-id"))==null?void 0:N.focus()});return()=>cancelAnimationFrame(E)},[L]);const Q=(he=B.data)==null?void 0:he.history.find(E=>E.current&&GB(E.workspace)===GB(C)),QB=((XB=B.data)==null?void 0:XB.history.filter(E=>E.current&&E.policy&&(!C||GB(E.workspace)===GB(C))))??[];function YB(E,N=!1){var H;i(E,{replace:N}),sessionStorage.setItem("orc_rules_workspace",E),L&&!R&&DB((H=B.data)==null?void 0:H.history.find(V=>V.current&&GB(V.workspace)===GB(E)))}S.useEffect(()=>{a((Q==null?void 0:Q.project_id)??""),x({})},[Q]);function HB(E){I(E),n.invalidateQueries({queryKey:["rules"]})}function Le(){var E;return(((E=Q==null?void 0:Q.policy)==null?void 0:E.rules)??[]).map(N=>{if(!w[N.id])return N;const H=w[N.id];return oe.parse({...N,scope:{...N.scope,agents:H==="all"?"all":H.split(",")}})})}const mB=me({mutationFn:E=>{var H,V;const N=tB;if((H=N==null?void 0:N.policy)!=null&&H.rules.some(nB=>nB.id===E.id&&nB.id!==(R==null?void 0:R.id)))throw new Error("A rule with this name already exists.");return te.rules.activate({workspace:C.trim(),project_id:N?N.project_id:r||null,rules:[...((V=N==null?void 0:N.policy)==null?void 0:V.rules.filter(nB=>nB.id!==((R==null?void 0:R.id)??E.id)))??[],E]},(N==null?void 0:N.id)??null,u.trim()||(R?"Updated ":"Added ")+E.id)},onSuccess:()=>{y(!1),$(void 0),cB(void 0),HB("Rule saved.")}}),PB=me({mutationFn:()=>{const E=Le();return te.rules.activate({workspace:C.trim(),project_id:r||null,rules:E},(Q==null?void 0:Q.id)??null,u.trim()||"Updated rule settings")},onSuccess:()=>HB("Settings saved.")}),VB=me({mutationFn:({policy:E,rule:N})=>{var H;return te.rules.activate({workspace:E.workspace,project_id:E.project_id,rules:((H=E.policy)==null?void 0:H.rules.map(V=>V.id===N.id?{...N,enabled:!N.enabled}:V))??[]},E.id,(N.enabled?"Disabled ":"Enabled ")+N.id)},onSuccess:()=>HB("Rule status updated."),onError:E=>I(String(E))}),ue=me({mutationFn:E=>te.rules.revert(E,u.trim()||"Restored previous rule policy"),onSuccess:()=>HB("Previous policy restored."),onError:E=>I(String(E))});function zB(E){IB.current=E,mB.reset(),$(void 0),cB(void 0),DB(Q),le(""),qB(N=>N+1),y(!0)}function be(E,N,H){IB.current=H,mB.reset(),YB(E.workspace),DB(E),a(E.project_id??""),$(structuredClone(N)),cB(void 0),qB(V=>V+1),y(!0)}function yB(){var E,N;return c.jsxs("div",{className:"grid gap-4 sm:grid-cols-[2fr_1fr]",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(Y,{htmlFor:"rules-workspace",children:"Workspace directory"}),c.jsx(rB,{id:"rules-workspace","data-testid":"rules-workspace",list:"rule-workspaces",value:C,disabled:L&&!!tB,onChange:H=>YB(H.target.value,!0),placeholder:"Absolute project directory"}),c.jsx("datalist",{id:"rule-workspaces",children:(E=B.data)==null?void 0:E.history.filter(H=>H.current).map(H=>c.jsx("option",{value:H.workspace},H.id))})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Y,{htmlFor:"rule-policy-project",children:"Project"}),c.jsxs("select",{id:"rule-policy-project","data-testid":"rule-policy-project",className:ke,value:r,disabled:L&&!!tB,onChange:H=>a(H.target.value),children:[c.jsx("option",{value:"",children:"Unassigned"}),(N=e.data)==null?void 0:N.map(H=>c.jsx("option",{value:H.id,children:H.name},H.id))]})]})]})}return c.jsxs("section",{"data-testid":"rules-panel",className:"space-y-4",children:[B.error&&c.jsx("p",{role:"alert","data-testid":"rules-error",children:c.jsx("span",{"data-testid":"page-error",children:String(B.error)})}),c.jsxs(Bs,{value:t,onValueChange:s,children:[c.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[c.jsxs(es,{className:"h-auto max-w-full flex-wrap",children:[c.jsx(Ve,{value:"applied","data-testid":"rules-applied-tab",children:"Applied rules"}),c.jsx(Ve,{value:"settings","data-testid":"rules-settings-tab",children:"Settings"})]}),c.jsx(dB,{"data-testid":"rule-new",onClick:E=>zB(E.currentTarget),children:"Add rule"})]}),c.jsxs(ze,{value:"applied",className:"space-y-4 pt-3",children:[c.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-4",children:[c.jsxs("select",{"data-testid":"rules-workspace-filter","aria-label":"Filter by workspace",className:"w-full min-w-0 max-w-full rounded-md border border-control-border bg-background p-2 text-sm sm:max-w-sm",value:(Q==null?void 0:Q.workspace)??C,onChange:E=>YB(E.target.value),children:[c.jsx("option",{value:"",children:"All workspaces"}),C&&!Q&&c.jsx("option",{value:C,children:C}),(De=B.data)==null?void 0:De.history.filter(E=>E.current).map(E=>{var N,H;return c.jsx("option",{value:E.workspace,children:((H=(N=e.data)==null?void 0:N.find(V=>V.id===E.project_id))==null?void 0:H.name)??E.workspace},E.id)})]}),c.jsxs("span",{"data-testid":"rules-status",className:"text-xs text-muted-foreground",children:["Enforcement ",(ZB=B.data)!=null&&ZB.enabled?"on":"off"]})]}),c.jsxs("div",{className:"overflow-x-auto",children:[c.jsxs("table",{"data-testid":"applied-rules-table",className:"w-full min-w-[860px] table-fixed text-left text-sm",children:[c.jsxs("colgroup",{children:[c.jsx("col",{style:{width:"18%"}}),c.jsx("col",{style:{width:"9%"}}),c.jsx("col",{style:{width:"10%"}}),c.jsx("col",{style:{width:"12%"}}),c.jsx("col",{style:{width:"17%"}}),c.jsx("col",{style:{width:"18%"}}),c.jsx("col",{style:{width:"136px"}})]}),c.jsx("thead",{className:"text-xs text-muted-foreground",children:c.jsx("tr",{children:["Rule","Status","Agents","Trigger","Action","Project / workspace","Actions"].map((E,N)=>c.jsx("th",{className:`px-3 py-3 font-medium ${N===6?"sticky right-0 bg-background":""}`,children:E},E))})}),QB.map(E=>{var N;return c.jsx("tbody",{"data-testid":"rule-revision","data-revision-id":E.id,children:(N=E.policy)==null?void 0:N.rules.map(H=>{var V,nB;return c.jsxs("tr",{"data-testid":"saved-event-rule",className:"border-t border-outline-variant",children:[c.jsx("td",{className:"px-3 py-3 font-medium",children:c.jsx("span",{className:"block truncate",title:H.id,children:H.id})}),c.jsx("td",{className:"px-4 py-3",children:H.enabled?"Enabled":"Disabled"}),c.jsx("td",{className:"px-3 py-3",children:H.scope.agents!=="all"?H.scope.agents.join(", "):"All agents"}),c.jsx("td",{className:"px-4 py-3 text-xs",children:H.scope.events.join(", ").split("_").join(" ")}),c.jsx("td",{className:"px-3 py-3",children:c.jsx("span",{className:"block truncate",title:xt(H),children:xt(H)})}),c.jsxs("td",{className:"px-4 py-3",children:[c.jsx("span",{className:"block truncate text-xs text-muted-foreground",title:E.workspace,children:((nB=(V=e.data)==null?void 0:V.find(TB=>TB.id===E.project_id))==null?void 0:nB.name)??"Unassigned"}),c.jsx("span",{className:"block truncate text-xs text-muted-foreground",title:E.workspace,children:E.workspace})]}),c.jsx("td",{className:"sticky right-0 bg-background px-3 py-3",children:c.jsxs("div",{className:"flex flex-wrap gap-2",children:[c.jsx(dB,{variant:"outline",size:"sm","data-testid":"event-rule-edit",onClick:TB=>be(E,H,TB.currentTarget),children:"Edit"}),c.jsx(dB,{variant:"ghost",size:"sm","data-testid":"event-rule-toggle",disabled:VB.isPending,onClick:()=>VB.mutate({policy:E,rule:H}),children:H.enabled?"Disable":"Enable"})]})})]},H.id)})},E.id)})]}),B.isPending&&c.jsx("p",{role:"status","data-testid":"page-loading",className:"p-8 text-sm text-muted-foreground",children:"Loading rules…"}),!B.isPending&&!B.error&&!QB.some(E=>{var N;return(N=E.policy)==null?void 0:N.rules.length})&&c.jsx("div",{className:"p-10 text-center text-sm text-muted-foreground","data-testid":"rules-empty",children:c.jsx("span",{"data-testid":"page-empty",children:"No applied rules. Add a rule from scratch or choose a template."})})]})]}),c.jsx(ze,{value:"settings",className:"space-y-6 pt-4",children:!L&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-4",children:[c.jsx("h3",{className:"font-medium",children:"Applies to"}),yB(),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Rules apply in this directory and its subdirectories."})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Y,{htmlFor:"rules-reason",children:"Change note (optional)"}),c.jsx(rB,{id:"rules-reason","data-testid":"rules-reason",value:u,onChange:E=>D(E.target.value)})]}),((ge=Q==null?void 0:Q.policy)==null?void 0:ge.rules.length)&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("h3",{className:"font-medium",children:"Agent assignments"}),Q.policy.rules.map(E=>c.jsxs("div",{className:"grid items-center gap-3 sm:grid-cols-2",children:[c.jsx(Y,{htmlFor:`agent-${E.id}`,children:E.id}),c.jsxs("select",{id:`agent-${E.id}`,"data-testid":"rule-agent-assignment",className:ke,value:w[E.id]??(E.scope.agents==="all"?"all":E.scope.agents.join(",")),onChange:N=>x(H=>({...H,[E.id]:N.target.value})),children:[c.jsx("option",{value:"all",children:"All agents"}),Nt.map(N=>c.jsx("option",{value:N,children:N},N)),E.scope.agents!=="all"&&E.scope.agents.length>1&&c.jsx("option",{value:E.scope.agents.join(","),children:E.scope.agents.join(", ")})]})]},E.id))]}),c.jsx(dB,{"data-testid":"rules-settings-save",disabled:PB.isPending||!C.trim()||!((WB=Q==null?void 0:Q.policy)!=null&&WB.rules.length),onClick:()=>PB.mutate(),children:"Save settings"}),PB.error&&c.jsx("p",{role:"alert","data-testid":"rules-settings-error",children:String(PB.error)}),c.jsxs("details",{"data-testid":"rule-connections",className:"space-y-3 border-t border-outline-variant pt-4",children:[c.jsx("summary",{className:"cursor-pointer font-medium",children:"Agent connections"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Claude SDK sessions connect when rule enforcement is enabled. Native agents need installed, trusted hooks and a supported host."}),Nt.map(E=>c.jsx("p",{className:"text-xs break-all",children:c.jsxs("code",{children:["orc rules install-hook ",E,' --target "',C?`${C.split("\\").join("/")}/`:"",".",E==="gemini"?"gemini":E,"/",E==="cursor"||E==="codex"?"hooks":"settings",'.json"']})},E))]}),c.jsxs("details",{"data-testid":"rules-history",className:"space-y-3 border-t border-outline-variant pt-4",children:[c.jsx("summary",{className:"cursor-pointer font-medium",children:"Policy history"}),(pe=B.data)==null?void 0:pe.history.filter(E=>!C||GB(E.workspace)===GB(C)).map(E=>c.jsxs("div",{"data-testid":"rule-history-entry",className:"space-y-2 border-t border-outline-variant py-3 text-xs",children:[c.jsxs("p",{className:"break-all",children:[E.workspace," · ",E.current?"Current":"Historical"," ·"," ",E.policy?`${E.policy.rules.length} rules`:"Disabled"]}),c.jsx("p",{children:E.reason}),E.current&&c.jsx(dB,{size:"sm","data-testid":"rule-revert",disabled:ue.isPending,onClick:()=>ue.mutate(E.id),children:"Restore previous policy"}),c.jsxs("details",{children:[c.jsx("summary",{children:"View policy"}),c.jsx("pre",{className:"whitespace-pre-wrap break-all",children:JSON.stringify(E.policy,null,2)})]})]},E.id))]}),c.jsxs("details",{"data-testid":"rules-decisions",className:"border-t border-outline-variant pt-4",children:[c.jsx("summary",{className:"cursor-pointer font-medium",children:"Activity"}),c.jsx("pre",{className:"text-xs whitespace-pre-wrap break-all",children:JSON.stringify({decisions:($B=B.data)==null?void 0:$B.decisions,actions:(Ee=B.data)==null?void 0:Ee.actions},null,2)})]})]})})]}),c.jsx(Yt,{open:L,onOpenChange:y,children:c.jsxs(Vt,{className:"w-[640px] max-w-[100vw]","data-testid":"rule-editor-panel","aria-describedby":"rule-editor-description",onOpenAutoFocus:E=>{var N;L&&(E.preventDefault(),(N=document.getElementById("event-rule-id"))==null||N.focus())},onCloseAutoFocus:E=>{var N;E.preventDefault(),(N=IB.current)==null||N.focus()},children:[c.jsxs(zt,{children:[c.jsx(Xt,{children:R?`Edit ${R.id}`:"Add rule"}),c.jsx(Zt,{id:"rule-editor-description",children:"Select a template to fill the form, or define a rule from scratch."})]}),c.jsxs(Wt,{className:"space-y-4","data-testid":"rule-editor-region",children:[!R&&c.jsxs("div",{className:"space-y-2","data-testid":"rule-catalog",children:[c.jsx(Y,{htmlFor:"rule-template",children:"Start with"}),c.jsxs("select",{id:"rule-template","data-testid":"rule-template",className:ke,value:bB,onChange:E=>{var V;const N=E.target.value;le(N);const H=N?Ms(N):void 0;if(H){const nB=new Set((V=tB==null?void 0:tB.policy)==null?void 0:V.rules.map(fe=>fe.id));let TB=2;for(;nB.has(H.id);)H.id=`${N}-${TB++}`}cB(H),qB(nB=>nB+1)},children:[c.jsx("option",{value:"",children:"From scratch"}),Ae.map(E=>c.jsx("option",{value:E.id,children:E.name},E.id))]}),bB&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("p",{"data-testid":"rule-template-description",className:"text-sm",children:(Be=Ae.find(E=>E.id===bB))==null?void 0:Be.description}),c.jsx("p",{"data-testid":"rule-template-limits",className:"text-xs text-muted-foreground",children:(de=Ae.find(E=>E.id===bB))==null?void 0:de.configuration})]})]}),C.trim()?c.jsxs("details",{className:"space-y-3",children:[c.jsxs("summary",{className:"cursor-pointer text-xs text-muted-foreground",children:["Applies to ",C]}),yB()]}):yB(),c.jsx(Js,{rule:R??M,isEditing:!!R,projectId:tB?tB.project_id:r||null,pending:mB.isPending||!C.trim(),onSave:E=>mB.mutate(E)},`${(R==null?void 0:R.id)??"new"}:${ce}`),mB.error&&c.jsx("p",{role:"alert","data-testid":"rule-save-error",children:String(mB.error)})]})]})}),f&&c.jsx("p",{role:"status","data-testid":"rules-message",className:"text-sm",children:f})]})}function zs(){return c.jsxs("div",{"data-testid":"rules-view",children:[c.jsx($t,{title:"Rules"}),c.jsx("div",{className:"max-w-4xl",children:c.jsx(js,{})})]})}export{zs as default};
@@ -1,5 +1,5 @@
1
- import{h as fe,i as Je,a as Ke,o as Ae,r as l,u as le,j as e,B as H,aa as ce,X as de,Y as xe,Z as ue,au as me,_ as ee,$ as W,av as Oe,d as z,aw as Qe,E as Ue,s as Fe,ax as Ge,L as Ve,ay as We,az as Ye,aA as Xe,p as He,aB as Ze,a4 as et,a5 as tt,a6 as st,a7 as at,D as ae,aC as he,A as ne,R as pe,aD as Be,C as nt,f as rt,a8 as it,S as ot,aE as lt,ad as ct,m as dt,aF as xt,aG as ut,ah as mt,t as ht,v as pt,w as qe,x as B,y as gt,z as I,V as ft}from"./index-CS_oHx6f.js";import{P as jt}from"./pencil-864Hty9z.js";import{R as Ie}from"./refresh-cw-CDVBz6mR.js";import{P as vt}from"./Pager-DCsiS5yC.js";import{u as bt}from"./useProjectScope-Duh5p4ZM.js";function yt({projectId:s}){var je,ve,be,ye,Ne,we,ke,Se,Ce,_e;const[d]=fe(),u=Je(),f=Ke(),p=Ae(),[h,x]=l.useState({key:"",offset:0}),[r,i]=l.useState(null),[w,k]=l.useState(!1),[c,$]=l.useState(!1),[b,o]=l.useState(""),[m,g]=l.useState(""),[A,L]=l.useState(s),[E,T]=l.useState(""),[R,J]=l.useState(""),[O,P]=l.useState(""),[D,U]=l.useState(""),[n,v]=l.useState(0),q=d.get("q")??"",F=d.get("agent")??"",t=d.get("ended")!=="0",N=JSON.stringify([s,q,F]),_=h.key===N?h.offset:0,C=a=>x({key:N,offset:a}),y=le({queryKey:["sessions","archive",s,q,F,_],queryFn:()=>z.sessions.archive({q,...s==="all"?{}:{project_id:s},...["claude","codex"].includes(F)?{agent:F}:{},offset:_,limit:20}),enabled:t,refetchInterval:1e4}),te=le({queryKey:["sessions","archive-transcript",r==null?void 0:r.id,r==null?void 0:r.revision,n],queryFn:()=>z.sessions.archiveTranscript(r==null?void 0:r.id,{revision:r==null?void 0:r.revision,offset:n,limit:50}),enabled:!!r});async function re(a){$(!0),o(""),g("");try{await a(),await f.invalidateQueries({queryKey:["sessions"]})}catch(S){o(S instanceof Error?S.message:"Request failed")}finally{$(!1)}}async function Me(a){var Te,$e;if(!(a!=null&&a.length))return;const S=($e=(Te=p.data)==null?void 0:Te.find(K=>K.id===A))==null?void 0:$e.name;if(!S){o("Select a project before uploading");return}await re(async()=>{var Pe,Ee,Re,De;let K=localStorage.getItem("orc_session_upload_source");K||(K=crypto.randomUUID(),localStorage.setItem("orc_session_upload_source",K));let Le=0;const Y=[];for(const se of Array.from(a))try{if(se.size>60*1024*1024)throw new Error("File exceeds 60 MiB");const X=await se.text(),ie=X.split(/\r?\n/).filter(Z=>Z.trim()).map(Z=>JSON.parse(Z)),Q=((Pe=ie[0])==null?void 0:Pe.type)==="session_meta",j=Q?ie[0].payload:ie.find(Z=>Z.sessionId),ze=await z.sessions.archiveUpload({project:S,source_id:K,agent:Q?"codex":"claude",session_id:Q?j==null?void 0:j.id:j==null?void 0:j.sessionId,title:se.name.slice(0,200),metadata:{cwd:(j==null?void 0:j.cwd)??"",subdirectory:"",...Q&&((Ee=j==null?void 0:j.git)!=null&&Ee.repository_url)?{repository:j.git.repository_url}:{},...Q&&((Re=j==null?void 0:j.git)!=null&&Re.branch)?{branch:j.git.branch}:{},...Q&&((De=j==null?void 0:j.git)!=null&&De.commit_hash)?{commit:j.git.commit_hash}:{}},bundle:{version:1,files:[{path:"session.jsonl",content:X}]}});["created","updated","unchanged","stale"].includes(ze.outcome)&&Le++}catch(X){Y.push(`${se.name}: ${X instanceof Error?X.message:"Upload failed"}`)}g(`${Le} of ${a.length} sessions synchronized${Y.length?`; ${Y.length} need attention`:""}.`),Y.length&&o(Y.join(`
2
- `))})}return t?e.jsxs("section",{className:"mt-8 space-y-3","data-testid":"session-archive",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-medium",children:"Archived sessions"}),e.jsx("p",{className:"text-xs text-outline",children:"Uploaded history stays available after the source computer is offline."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(H,{variant:"outline","data-testid":"archive-index",disabled:c,onClick:()=>void re(async()=>{const a=await z.sessions.archiveIndex(s==="all"||s==="unassigned"?void 0:s);g(`${a.indexed} sessions indexed; ${a.failed} failed; ${a.skipped} skipped.`)}),children:"Index discovered sessions"}),e.jsx(H,{"data-testid":"archive-upload-open",onClick:()=>{L(s),k(!0)},children:"Upload sessions"})]})]}),m&&e.jsx("p",{role:"status","data-testid":"archive-feedback",className:"text-sm",children:m}),(b||y.error)&&e.jsx("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-error",children:b||((je=y.error)==null?void 0:je.message)}),((ve=y.data)==null?void 0:ve.degraded)&&e.jsx("p",{role:"status","data-testid":"archive-degraded",className:"text-xs text-outline",children:y.data.degraded}),!!((be=y.data)!=null&&be.pending_chunks)&&e.jsxs("p",{className:"text-xs text-outline",children:[y.data.pending_chunks," passages waiting for embeddings"]}),e.jsxs("div",{className:"divide-y divide-outline-variant rounded border border-outline-variant",children:[y.isLoading&&e.jsx("p",{className:"p-4 text-sm",children:"Loading archived sessions…"}),!y.isLoading&&!((ye=y.data)!=null&&ye.sessions.length)&&e.jsx("p",{className:"p-4 text-sm text-outline",children:"No archived sessions match this view."}),(Ne=y.data)==null?void 0:Ne.sessions.map(a=>e.jsxs("button",{type:"button","data-testid":"archive-session-row","data-archive-id":a.id,className:"block w-full p-3 text-left hover:bg-surface-container",onClick:()=>{i(a),v(0),T(a.metadata.repository??""),J(a.metadata.branch??""),P(a.metadata.commit??""),U(a.metadata.subdirectory)},children:[e.jsx("span",{className:"block text-sm font-medium",children:a.title}),e.jsxs("span",{className:"text-xs text-outline",children:[a.agent," · ended · ",new Date(a.updated_at).toLocaleString()," · revision"," ",a.revision," · ",a.metadata.cwd]}),a.passages.map(S=>e.jsx("span",{className:"mt-1 block text-sm text-outline",children:S.snippet},S.citation)),a.embedding_error&&e.jsx("span",{className:"block text-xs text-error",children:a.embedding_error})]},a.id))]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(H,{variant:"ghost",disabled:_===0,onClick:()=>C(Math.max(0,_-20)),children:"Previous"}),e.jsx(H,{variant:"ghost",disabled:!((we=y.data)!=null&&we.has_more),onClick:()=>C(_+20),children:"Next"})]}),e.jsx(ce,{open:w,onOpenChange:k,children:e.jsxs(de,{children:[e.jsxs(xe,{children:[e.jsx(ue,{children:"Upload session histories"}),e.jsx(me,{children:"Select an existing project and native Claude/Codex JSONL files. This stores history without starting a terminal. For large collections, use the orc-platform sync script."})]}),e.jsx(ee,{htmlFor:"archive-project",children:"Project"}),e.jsxs("select",{id:"archive-project","data-testid":"archive-project",value:A,onChange:a=>L(a.target.value),className:"rounded border border-outline-variant bg-surface p-2",children:[e.jsx("option",{value:"all",children:"Select a project"}),(ke=p.data)==null?void 0:ke.map(a=>e.jsx("option",{value:a.id,children:a.name},a.id))]}),e.jsx(W,{"data-testid":"archive-files",type:"file",multiple:!0,accept:".jsonl",disabled:c||!((Se=p.data)!=null&&Se.some(a=>a.id===A)),onChange:a=>void Me(a.target.files)}),c&&e.jsx("p",{role:"status",children:"Uploading…"}),m&&e.jsx("p",{role:"status","data-testid":"archive-upload-feedback",children:m}),b&&e.jsx("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-error",children:b})]})}),e.jsx(ce,{open:!!r,onOpenChange:a=>{a||i(null)},children:e.jsxs(de,{className:"max-h-[90vh] max-w-3xl overflow-y-auto","data-testid":"archive-detail",children:[e.jsxs(xe,{children:[e.jsx(ue,{children:r==null?void 0:r.title}),e.jsxs(me,{children:["Archived history · revision ",r==null?void 0:r.revision,". Prepare a destination checkout to continue in a terminal."]})]}),te.error&&e.jsx("p",{role:"alert",children:te.error.message}),(Ce=te.data)==null?void 0:Ce.turns.map(a=>e.jsxs("div",{className:"border-b border-outline-variant py-2","data-testid":"archive-turn",children:[e.jsx("p",{className:"text-xs text-outline",children:a.role}),e.jsx(Oe,{plain:!0,children:a.blocks.map(S=>S.type==="tool_use"?`${S.name}
1
+ import{G as fe,H as ze,a as Ke,e as Ae,r as l,u as le,j as e,B as F,D as ce,m as de,n as xe,o as ue,U as me,p as ee,I as W,aY as Oe,d as J,L as Qe,aZ as Ge,a8 as Ve,a9 as We,aa as Ye,ab as Xe,a_ as Ue,A as Ze,E as et,ac as tt,S as st,a$ as at,ae as rt,X as nt}from"./index-C_jtMgr7.js";import{E as it}from"./EmptyState-Ctm7L70B.js";import{E as He}from"./ErrorState-BPTepwiG.js";import{e as ot,s as lt,L as ct,S as ae,b as he,f as re,R as pe}from"./ResumeActions-DHTOr6GQ.js";import{S as Fe}from"./StatusBadge-C5G1fdZh.js";import{d as dt,u as Be,e as xt,f as ut,g as mt}from"./useSessions-BrdK-12R.js";import{P as ht}from"./pencil-gxvh59uO.js";import{R as Ie}from"./refresh-cw-BQRdbjy6.js";import{P as pt}from"./Pager-ClYYU9et.js";import{T as gt,a as ft,b as qe,c as B,d as jt,e as I}from"./table-D3N_5Wee.js";import{V as vt}from"./ViewHeader-DXR0ZaMO.js";import{u as bt}from"./useProjectScope-Dk0mjyHf.js";function yt({projectId:s}){var je,ve,be,ye,Ne,we,ke,Se,Ce,_e;const[d]=fe(),u=ze(),f=Ke(),p=Ae(),[h,x]=l.useState({key:"",offset:0}),[n,i]=l.useState(null),[w,k]=l.useState(!1),[c,L]=l.useState(!1),[b,o]=l.useState(""),[m,g]=l.useState(""),[A,$]=l.useState(s),[E,T]=l.useState(""),[R,z]=l.useState(""),[O,P]=l.useState(""),[D,U]=l.useState(""),[r,v]=l.useState(0),q=d.get("q")??"",H=d.get("agent")??"",t=d.get("ended")!=="0",N=JSON.stringify([s,q,H]),_=h.key===N?h.offset:0,C=a=>x({key:N,offset:a}),y=le({queryKey:["sessions","archive",s,q,H,_],queryFn:()=>J.sessions.archive({q,...s==="all"?{}:{project_id:s},...["claude","codex"].includes(H)?{agent:H}:{},offset:_,limit:20}),enabled:t,refetchInterval:1e4}),te=le({queryKey:["sessions","archive-transcript",n==null?void 0:n.id,n==null?void 0:n.revision,r],queryFn:()=>J.sessions.archiveTranscript(n==null?void 0:n.id,{revision:n==null?void 0:n.revision,offset:r,limit:50}),enabled:!!n});async function ne(a){L(!0),o(""),g("");try{await a(),await f.invalidateQueries({queryKey:["sessions"]})}catch(S){o(S instanceof Error?S.message:"Request failed")}finally{L(!1)}}async function Me(a){var Te,Le;if(!(a!=null&&a.length))return;const S=(Le=(Te=p.data)==null?void 0:Te.find(K=>K.id===A))==null?void 0:Le.name;if(!S){o("Select a project before uploading");return}await ne(async()=>{var Pe,Ee,Re,De;let K=localStorage.getItem("orc_session_upload_source");K||(K=crypto.randomUUID(),localStorage.setItem("orc_session_upload_source",K));let $e=0;const Y=[];for(const se of Array.from(a))try{if(se.size>60*1024*1024)throw new Error("File exceeds 60 MiB");const X=await se.text(),ie=X.split(/\r?\n/).filter(Z=>Z.trim()).map(Z=>JSON.parse(Z)),Q=((Pe=ie[0])==null?void 0:Pe.type)==="session_meta",j=Q?ie[0].payload:ie.find(Z=>Z.sessionId),Je=await J.sessions.archiveUpload({project:S,source_id:K,agent:Q?"codex":"claude",session_id:Q?j==null?void 0:j.id:j==null?void 0:j.sessionId,title:se.name.slice(0,200),metadata:{cwd:(j==null?void 0:j.cwd)??"",subdirectory:"",...Q&&((Ee=j==null?void 0:j.git)!=null&&Ee.repository_url)?{repository:j.git.repository_url}:{},...Q&&((Re=j==null?void 0:j.git)!=null&&Re.branch)?{branch:j.git.branch}:{},...Q&&((De=j==null?void 0:j.git)!=null&&De.commit_hash)?{commit:j.git.commit_hash}:{}},bundle:{version:1,files:[{path:"session.jsonl",content:X}]}});["created","updated","unchanged","stale"].includes(Je.outcome)&&$e++}catch(X){Y.push(`${se.name}: ${X instanceof Error?X.message:"Upload failed"}`)}g(`${$e} of ${a.length} sessions synchronized${Y.length?`; ${Y.length} need attention`:""}.`),Y.length&&o(Y.join(`
2
+ `))})}return t?e.jsxs("section",{className:"mt-8 space-y-3","data-testid":"session-archive",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-medium",children:"Archived sessions"}),e.jsx("p",{className:"text-xs text-outline",children:"Uploaded history stays available after the source computer is offline."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(F,{variant:"outline","data-testid":"archive-index",disabled:c,onClick:()=>void ne(async()=>{const a=await J.sessions.archiveIndex(s==="all"||s==="unassigned"?void 0:s);g(`${a.indexed} sessions indexed; ${a.failed} failed; ${a.skipped} skipped.`)}),children:"Index discovered sessions"}),e.jsx(F,{"data-testid":"archive-upload-open",onClick:()=>{$(s),k(!0)},children:"Upload sessions"})]})]}),m&&e.jsx("p",{role:"status","data-testid":"archive-feedback",className:"text-sm",children:m}),(b||y.error)&&e.jsx("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-error",children:b||((je=y.error)==null?void 0:je.message)}),((ve=y.data)==null?void 0:ve.degraded)&&e.jsx("p",{role:"status","data-testid":"archive-degraded",className:"text-xs text-outline",children:y.data.degraded}),!!((be=y.data)!=null&&be.pending_chunks)&&e.jsxs("p",{className:"text-xs text-outline",children:[y.data.pending_chunks," passages waiting for embeddings"]}),e.jsxs("div",{className:"divide-y divide-outline-variant rounded border border-outline-variant",children:[y.isLoading&&e.jsx("p",{className:"p-4 text-sm",children:"Loading archived sessions…"}),!y.isLoading&&!((ye=y.data)!=null&&ye.sessions.length)&&e.jsx("p",{className:"p-4 text-sm text-outline",children:"No archived sessions match this view."}),(Ne=y.data)==null?void 0:Ne.sessions.map(a=>e.jsxs("button",{type:"button","data-testid":"archive-session-row","data-archive-id":a.id,className:"block w-full p-3 text-left hover:bg-surface-container",onClick:()=>{i(a),v(0),T(a.metadata.repository??""),z(a.metadata.branch??""),P(a.metadata.commit??""),U(a.metadata.subdirectory)},children:[e.jsx("span",{className:"block text-sm font-medium",children:a.title}),e.jsxs("span",{className:"text-xs text-outline",children:[a.agent," · ended · ",new Date(a.updated_at).toLocaleString()," · revision"," ",a.revision," · ",a.metadata.cwd]}),a.passages.map(S=>e.jsx("span",{className:"mt-1 block text-sm text-outline",children:S.snippet},S.citation)),a.embedding_error&&e.jsx("span",{className:"block text-xs text-error",children:a.embedding_error})]},a.id))]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(F,{variant:"ghost",disabled:_===0,onClick:()=>C(Math.max(0,_-20)),children:"Previous"}),e.jsx(F,{variant:"ghost",disabled:!((we=y.data)!=null&&we.has_more),onClick:()=>C(_+20),children:"Next"})]}),e.jsx(ce,{open:w,onOpenChange:k,children:e.jsxs(de,{children:[e.jsxs(xe,{children:[e.jsx(ue,{children:"Upload session histories"}),e.jsx(me,{children:"Select an existing project and native Claude/Codex JSONL files. This stores history without starting a terminal. For large collections, use the orc-platform sync script."})]}),e.jsx(ee,{htmlFor:"archive-project",children:"Project"}),e.jsxs("select",{id:"archive-project","data-testid":"archive-project",value:A,onChange:a=>$(a.target.value),className:"rounded border border-outline-variant bg-surface p-2",children:[e.jsx("option",{value:"all",children:"Select a project"}),(ke=p.data)==null?void 0:ke.map(a=>e.jsx("option",{value:a.id,children:a.name},a.id))]}),e.jsx(W,{"data-testid":"archive-files",type:"file",multiple:!0,accept:".jsonl",disabled:c||!((Se=p.data)!=null&&Se.some(a=>a.id===A)),onChange:a=>void Me(a.target.files)}),c&&e.jsx("p",{role:"status",children:"Uploading…"}),m&&e.jsx("p",{role:"status","data-testid":"archive-upload-feedback",children:m}),b&&e.jsx("p",{role:"alert",className:"whitespace-pre-wrap text-sm text-error",children:b})]})}),e.jsx(ce,{open:!!n,onOpenChange:a=>{a||i(null)},children:e.jsxs(de,{className:"max-h-[90vh] max-w-3xl overflow-y-auto","data-testid":"archive-detail",children:[e.jsxs(xe,{children:[e.jsx(ue,{children:n==null?void 0:n.title}),e.jsxs(me,{children:["Archived history · revision ",n==null?void 0:n.revision,". Prepare a destination checkout to continue in a terminal."]})]}),te.error&&e.jsx("p",{role:"alert",children:te.error.message}),(Ce=te.data)==null?void 0:Ce.turns.map(a=>e.jsxs("div",{className:"border-b border-outline-variant py-2","data-testid":"archive-turn",children:[e.jsx("p",{className:"text-xs text-outline",children:a.role}),e.jsx(Oe,{plain:!0,children:a.blocks.map(S=>S.type==="tool_use"?`${S.name}
3
3
  ${S.input}
4
4
  ${S.result??""}`:S.text).join(`
5
- `)})]},a.index)),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(H,{variant:"ghost",disabled:!n,onClick:()=>v(Math.max(0,n-50)),children:"Previous messages"}),e.jsx(H,{variant:"ghost",disabled:n+50>=(((_e=te.data)==null?void 0:_e.total)??0),onClick:()=>v(n+50),children:"Next messages"})]}),e.jsxs("div",{className:"space-y-2 border-t border-outline-variant pt-3",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Continue on ORC"}),e.jsx("p",{className:"text-xs text-outline",children:"Use the pushed repository, branch and exact commit for the work you want to continue. The destination project must have its repository configured."}),e.jsx(ee,{htmlFor:"archive-repository",children:"Repository"}),e.jsx(W,{id:"archive-repository","data-testid":"archive-repository",value:E,onChange:a=>T(a.target.value)}),e.jsx(ee,{htmlFor:"archive-branch",children:"Branch"}),e.jsx(W,{id:"archive-branch","data-testid":"archive-branch",value:R,onChange:a=>J(a.target.value)}),e.jsx(ee,{htmlFor:"archive-commit",children:"Pushed commit"}),e.jsx(W,{id:"archive-commit","data-testid":"archive-commit",value:O,onChange:a=>P(a.target.value)}),e.jsx(ee,{htmlFor:"archive-subdirectory",children:"Repository subdirectory"}),e.jsx(W,{id:"archive-subdirectory","data-testid":"archive-subdirectory",value:D,onChange:a=>U(a.target.value),placeholder:"Repository root"}),e.jsx(H,{"data-testid":"archive-resume",disabled:c||!E||!R||!/^[a-f0-9]{40}$/i.test(O),onClick:()=>void re(async()=>{if(!r)return;const a=await z.sessions.archiveResume(r.id,{revision:r.revision,repository:E,branch:R,commit:O,subdirectory:D});if(a.status!=="ready"||!a.live_session_id)throw new Error(a.error||"Session preparation failed");const S=await z.terminals.create({kind:r.agent,live_session_id:a.live_session_id});u(`/terminals/${S.id}`)}),children:c?"Preparing…":"Prepare and resume in terminal"}),b&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:b})]})]})})]}):null}function G({text:s,query:d}){const u=d.trim();if(u.length<2)return e.jsx(e.Fragment,{children:s});const f=s.split(new RegExp(`(${Qe(u)})`,"gi"));return e.jsx(e.Fragment,{children:f.map((p,h)=>p.toLowerCase()===u.toLowerCase()?e.jsx("mark",{className:"bg-primary/30 text-on-surface rounded-sm",children:p},h):p)})}function Nt({projectId:s,pending:d,onSelect:u}){var b;const[f,p]=l.useState(""),[h,x]=l.useState(!1),[r,i]=l.useState(null),w=le({queryKey:["tasks","session-picker",s],queryFn:()=>z.tasks.list({...s?{project_id:s}:{},limit:100})});async function k(o){i(null);try{await u(o)}catch(m){i(m instanceof Error?m.message:"Could not link task")}}async function c(){x(!0),i(null);try{const o=await z.tasks.get(f.trim());await k(o.id)}catch(o){i(o instanceof Error?o.message:"Task lookup failed")}finally{x(!1)}}const $=(((b=w.data)==null?void 0:b.tasks)??[]).filter(o=>`${o.title} ${o.id}`.toLowerCase().includes(f.trim().toLowerCase()));return e.jsxs("div",{className:"space-y-3",children:[e.jsx(W,{"data-testid":"session-task-search","aria-label":"Search tasks or enter a task ID",value:f,onChange:o=>{p(o.target.value),i(null)},placeholder:"Search recent tasks or paste a task ID"}),e.jsxs("p",{className:"text-xs text-outline",children:["Up to 100 recent tasks",s?" in this project":" across projects",". Older or other-project tasks can be linked by exact ID."]}),r&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:r}),w.error?e.jsx(Ue,{message:w.error.message,onRetry:()=>w.refetch()}):w.isLoading?e.jsx("p",{role:"status",children:"Loading tasks…"}):e.jsxs("div",{className:"max-h-72 overflow-y-auto divide-y divide-border",children:[$.map(o=>e.jsxs("button",{type:"button","data-testid":"session-task-option","data-task-id":o.id,disabled:d||h,onClick:()=>void k(o.id),className:"w-full min-h-11 py-2 text-left hover:bg-surface-highest disabled:opacity-50",children:[e.jsx("span",{className:"block text-sm break-words",children:o.title}),e.jsxs("span",{className:"inline-flex items-center gap-2 text-xs text-outline",children:[e.jsx(Fe,{status:o.status,className:"px-0"}),o.id]})]},o.id)),$.length===0&&e.jsx("p",{className:"py-4 text-sm text-outline",children:"No recent task matches. Paste its exact ID to look it up."})]}),f.trim()&&e.jsx(H,{variant:"outline",disabled:d||h,onClick:()=>void c(),children:h?"Looking up…":"Link by exact ID"})]})}function ge({session:s,linkTestId:d="open-task"}){const[u]=fe(),[f,p]=l.useState(!1),h=Ge(),x=u.get("project")??s.project_id;async function r(i){try{await h.mutateAsync({id:s.id,taskId:i}),p(!1)}catch{}}return e.jsxs("div",{className:"min-w-0 space-y-1",children:[s.task&&e.jsxs("div",{className:"min-w-0",children:[e.jsx(Ve,{"data-testid":d,to:We(`/tasks/${s.task.id}`,x),className:"block max-w-64 truncate text-sm text-primary hover:underline",title:s.task.title,children:s.task.title}),e.jsx(Fe,{status:s.task.status,className:"px-0"})]}),e.jsxs(ce,{open:f,onOpenChange:i=>{p(i),i&&h.reset()},children:[e.jsx(Ye,{asChild:!0,children:e.jsxs("button",{type:"button","data-testid":"link-task",className:"inline-flex min-h-9 items-center gap-1.5 text-xs text-outline hover:text-on-surface",children:[s.task?e.jsx(jt,{size:12}):e.jsx(Xe,{size:13}),s.task?"Change task":"Link task"]})}),e.jsxs(de,{"data-testid":"session-task-dialog",className:"max-h-[85dvh] w-[calc(100%-2rem)] overflow-y-auto",children:[e.jsxs(xe,{children:[e.jsx(ue,{children:"Link a task"}),e.jsxs(me,{children:["Choose a recent task for ",s.name??"this session",", or paste an exact task ID."]})]}),h.error&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:h.error.message}),e.jsx(Nt,{projectId:s.project_id,pending:h.isPending,onSelect:r}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.task&&e.jsx(H,{variant:"outline","data-testid":"session-task-unlink",disabled:h.isPending,onClick:()=>void r(null),children:"Unlink task"})})]})]})]})}const oe="session-search",wt={user:"border-border/65",assistant:"border-border/65",tool:"border-border/65 bg-transparent",system:"border-border/65 bg-transparent"},kt=["command","cmd","file_path","path","pattern","query","url","description"];function St(s){try{const d=JSON.parse(s);for(const u of kt)if(typeof d[u]=="string")return d[u]}catch{}return s}function Ct(s){try{return JSON.stringify(JSON.parse(s),null,2)}catch{return s}}function _t(s,d,u){l.useEffect(()=>{const f=s.current,p=CSS.highlights,h=window.Highlight;if(!f||!p||!h)return;const x=d.trim().toLowerCase(),r=()=>{var $;if(p.delete(oe),x.length<2)return;const k=[],c=document.createTreeWalker(f,NodeFilter.SHOW_TEXT);for(let b=c.nextNode();b;b=c.nextNode()){const o=(($=b.textContent)==null?void 0:$.toLowerCase())??"";for(let m=o.indexOf(x);m>=0;m=o.indexOf(x,m+x.length)){const g=new Range;g.setStart(b,m),g.setEnd(b,m+x.length),k.push(g)}}k.length>0&&p.set(oe,new h(...k))};r();let i;const w=new MutationObserver(()=>{clearTimeout(i),i=setTimeout(r,150)});return w.observe(f,{childList:!0,subtree:!0,characterData:!0}),()=>{clearTimeout(i),w.disconnect(),p.delete(oe)}},[s,d,u])}function Tt({block:s,open:d}){const u=s.result!==void 0;return e.jsxs("details",{open:d||void 0,"data-testid":"tool-box",className:"border-l border-border bg-background",children:[e.jsxs("summary",{className:"flex cursor-pointer items-center gap-2 px-2 py-1.5 font-label text-xs font-medium text-outline hover:text-on-surface",children:[e.jsx("span",{className:"text-secondary shrink-0",children:s.name}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono normal-case tracking-normal text-on-surface-variant",children:St(s.input)}),e.jsx("span",{className:`shrink-0 ${u?"text-outline":"text-tertiary"}`,children:u?"done":"no result"})]}),e.jsxs("div",{className:"space-y-2 border-t border-border px-2 py-2",children:[e.jsx("div",{className:"font-label text-[10px] font-medium text-outline",children:"input"}),e.jsx("pre",{className:"max-h-72 overflow-auto rounded-lg bg-background p-2 font-mono text-xs text-on-surface-variant whitespace-pre-wrap break-words",children:Ct(s.input)}),u&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"font-label text-[10px] font-medium text-outline",children:"result"}),e.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg bg-background p-2 font-mono text-xs text-on-surface-variant whitespace-pre-wrap break-words",children:s.result})]})]})]})}function $t({block:s,matched:d}){if(s.type==="text")return e.jsx(Oe,{revealContext:d,children:s.text});if(s.type==="tool_use")return e.jsx(Tt,{block:s,open:d});const u=s.type==="thinking"?"thinking":"result";return e.jsxs("details",{open:d||void 0,children:[e.jsx("summary",{className:"cursor-pointer font-label text-xs font-medium text-outline hover:text-on-surface",children:u}),s.type==="thinking"?e.jsx("div",{className:"mt-1",children:e.jsx(ct,{children:s.text})}):e.jsx("pre",{className:"mt-1 max-h-96 overflow-auto rounded-lg bg-background p-2 font-mono text-xs text-on-surface-variant whitespace-pre-wrap break-words",children:s.text})]})}function Lt({sessionId:s,initialQuery:d,onClose:u}){const[f,p]=l.useState(d),[h,x]=l.useState(0),{data:r}=He(!1),i=r==null?void 0:r.find(n=>n.id===s),w=i!==void 0&&i.status!=="stopped",k=f.trim().length>=2?f.trim():"",{data:c,isLoading:$,isFetching:b,error:o,refetch:m,dataUpdatedAt:g}=Ze(s,k),A=l.useRef(null),L=l.useRef(null),E=l.useRef(!0),T=l.useRef(0),[R,J]=l.useState(!0),O=l.useCallback(()=>{const n=A.current;n&&(n.scrollTo({top:n.scrollHeight}),requestAnimationFrame(()=>n.scrollTo({top:n.scrollHeight})))},[]);_t(L,k,c==null?void 0:c.turns);const P=(c==null?void 0:c.matches)??[],D=P[h];l.useEffect(()=>{var n;if(c){if(D!==void 0){E.current=!1,(n=document.getElementById(`turn-${D}`))==null||n.scrollIntoView({block:"center"});return}E.current&&O()}},[D,c,O]),l.useEffect(()=>{c&&R&&(T.current=c.total)},[c,R]);const U=n=>{P.length>0&&x(v=>(v+n+P.length)%P.length)};return e.jsx(et,{open:!!s,onOpenChange:n=>!n&&u(),children:e.jsxs(tt,{side:"right",className:"w-[1100px] max-w-[95vw]","data-testid":"live-session-detail",children:[e.jsxs(st,{children:[e.jsx(at,{className:"normal-case tracking-normal text-sm pr-8",children:(i==null?void 0:i.name)??"Session"}),i&&e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-5 gap-y-1 font-body text-xs text-on-surface tabular-nums",children:[e.jsx("span",{className:"font-medium text-primary",children:i.agent}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${ae[i.status].dot}`}),ae[i.status].label]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-on-surface-variant",children:"tokens "}),he(i)]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-on-surface-variant",children:"active "}),ne(i.last_activity_at)]}),e.jsx(ge,{session:i,linkTestId:"detail-open-task"}),e.jsx(pe,{session:i}),e.jsx("span",{className:"truncate max-w-full text-on-surface-variant",children:i.cwd})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[150px] flex-1",children:[e.jsx(Be,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-outline"}),e.jsx("input",{"data-testid":"transcript-search","aria-label":"Search this session",value:f,onChange:n=>{p(n.target.value),x(0)},placeholder:"Search this session",className:"w-full bg-background border border-control-border rounded-lg min-h-11 pl-7 pr-2 py-2 font-body text-xs text-on-surface"})]}),k&&e.jsx("span",{"data-testid":"transcript-match-count",className:"font-label text-xs font-medium text-outline",children:P.length===0?"no matches":`${h+1} / ${P.length}`}),e.jsx("button",{type:"button","aria-label":"Previous match",onClick:()=>U(-1),className:"min-h-11 min-w-11 p-2 text-outline hover:text-on-surface",children:e.jsx(nt,{className:"h-4 w-4"})}),e.jsx("button",{type:"button","aria-label":"Next match",onClick:()=>U(1),className:"min-h-11 min-w-11 p-2 text-outline hover:text-on-surface",children:e.jsx(rt,{className:"h-4 w-4"})}),e.jsxs("button",{type:"button","data-testid":"transcript-refresh",onClick:()=>{E.current=!0,m()},className:"min-h-11 px-2 inline-flex items-center gap-1 font-label text-xs font-medium text-primary hover:text-on-surface",children:[e.jsx(Ie,{className:`h-3 w-3 ${b?"animate-spin":""}`}),"Refresh"]})]}),c&&e.jsxs("div",{"data-testid":"transcript-status",className:"mt-2 font-body text-xs text-on-surface-variant tabular-nums",children:[c.total," turns",w?` · live, updated ${new Date(g).toLocaleTimeString()}`:""]})]}),e.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[e.jsx(it,{ref:A,onScroll:n=>{const v=n.currentTarget,q=v.scrollHeight-v.scrollTop-v.clientHeight<160;E.current=q,J(q)},children:$?e.jsx("div",{className:"space-y-4",children:[...Array(5)].map((n,v)=>e.jsx(ot,{className:"h-16 w-full bg-surface-highest"},v))}):o||!c?e.jsxs("div",{"data-testid":"transcript-unavailable",className:"font-body text-xs text-outline py-12 text-center",children:[o?`Could not load the conversation: ${o.message}`:"No conversation was recorded for this session.",e.jsx("p",{className:"mt-2",children:"Resume actions remain available when the native agent session exists."}),e.jsx("button",{type:"button",className:"mt-3 min-h-11 text-primary hover:underline",onClick:()=>m(),children:"Retry conversation"})]}):e.jsx("div",{ref:L,className:"space-y-3",children:c.turns.map(n=>{const v=P.includes(n.index),q=n.blocks.map((F,t)=>e.jsx($t,{block:F,matched:v},t));return e.jsxs("div",{id:`turn-${n.index}`,"data-testid":"transcript-turn","data-role":n.role,style:{contentVisibility:"auto",containIntrinsicSize:"auto 120px"},className:`border-b px-4 py-3 text-on-surface space-y-2 ${wt[n.role]} ${n.index===D?"ring-1 ring-primary":""}`,children:[e.jsxs("div",{className:"font-label text-xs font-medium text-outline",children:[n.role,n.time?` · ${ne(n.time)}`:""]}),n.role==="system"?e.jsxs("details",{open:v||void 0,children:[e.jsx("summary",{className:"cursor-pointer font-label text-xs font-medium text-outline hover:text-on-surface",children:"injected context"}),e.jsx("div",{className:"mt-2 space-y-2",children:q})]}):q]},n.index)})})}),c&&!R&&e.jsxs("button",{type:"button","data-testid":"jump-to-latest",onClick:()=>{E.current=!0,O()},className:"absolute bottom-4 right-6 inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 font-body text-xs text-primary shadow-lg hover:bg-surface-bright",children:[e.jsx(lt,{className:"h-3.5 w-3.5"}),"Jump to latest",c.total>T.current&&` · ${c.total-T.current} new`]})]})]})})}const Pt=["claude","codex","cursor","cursor-agent","gemini"],V=25,M="font-label text-xs font-medium text-outline";function Et({projectId:s}){var F;const d=dt("sm"),[u,f]=fe(),p=u.get("agent")??"",h=u.get("ended")!=="0",x=u.get("q")??"",r=u.get("order")==="asc"?"asc":"desc",i=u.get("session"),[w,k]=l.useState(x),[c,$]=l.useState({order:r,page:0}),b=c.order===r?c.page:0,o=l.useCallback(t=>$({order:r,page:t}),[r]),m=l.useCallback((t,N)=>{o(0),f(_=>{const C=new URLSearchParams(_);return N?C.set(t,N):C.delete(t),C},{replace:t==="q"})},[f,o]);l.useEffect(()=>k(x),[x]),l.useEffect(()=>{if(w===x)return;const t=setTimeout(()=>m("q",w.trim()||null),350);return()=>clearTimeout(t)},[w,x,m]);const g=x.trim().length>=2,A=He(!h),L=xt(g?x.trim():"",p),{data:E}=Ae(),T=ut(),R=new Map((E??[]).map(t=>[t.id,t.name])),J=g?((F=L.data)==null?void 0:F.hits)??[]:A.data??[],O=[...new Set([...Pt,...J.map(t=>t.agent)])],P=g?L.isLoading:A.isLoading,D=g?L:A,U=J.filter(t=>{var N;return(!p||t.agent===p)&&(h||t.status!=="stopped"||((N=t.handoff)==null?void 0:N.status)==="ready")}),n=U.filter(t=>s==="all"?!0:s==="unassigned"?t.project_id===null:t.project_id===s).sort((t,N)=>{const C=new Date(t.last_activity_at??t.created_at).getTime()-new Date(N.last_activity_at??N.created_at).getTime()||t.id.localeCompare(N.id);return r==="asc"?C:-C}),v=Math.min(b,Math.max(0,Math.ceil(n.length/V)-1))*V,q=s==="unassigned"?"unassigned":R.get(s)??s;return e.jsxs("section",{className:"mb-8","data-testid":"live-sessions",children:[e.jsx("p",{className:"mb-4 text-sm text-outline",children:"Discovered from your coding agents. Working sessions update automatically; waiting sessions remain available to resume."}),e.jsxs("div",{className:"mb-3 relative",children:[e.jsx(Be,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-outline"}),e.jsx("input",{"data-testid":"session-search","aria-label":"Search agent sessions",value:w,onChange:t=>k(t.target.value),placeholder:"Search agent sessions: titles, summaries and conversation text",className:"w-full bg-background border border-control-border rounded-lg pl-9 pr-3 py-2 font-body text-xs text-on-surface placeholder:text-outline"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[e.jsxs("h2",{className:"font-label text-xs font-medium text-outline",children:[g?"Search results":"Agent sessions"," · ",n.length,n.length!==U.length&&e.jsxs("span",{"data-testid":"scope-hint",className:"normal-case tracking-normal",children:[" ","of ",U.length," · scope: ",q]}),g&&L.data&&e.jsxs("span",{"data-testid":"search-meta",className:"normal-case tracking-normal",children:[" ","· ",(L.data.ms/1e3).toFixed(1),"s",L.data.rg?"":" · titles and summaries only (install ripgrep for content)"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("select",{"aria-label":"Sort sessions by date","data-testid":"session-date-sort",value:r,onChange:t=>m("order",t.target.value==="asc"?"asc":null),className:"min-h-11 rounded-md border border-control-border bg-background px-3 text-sm text-on-surface",children:[e.jsx("option",{value:"desc",children:"Last active: newest first"}),e.jsx("option",{value:"asc",children:"Last active: oldest first"})]}),e.jsxs("select",{"data-testid":"agent-filter","aria-label":"Agent",className:"bg-background border border-control-border rounded-lg min-h-11 px-3 py-2 font-label text-xs font-medium text-on-surface",value:p,onChange:t=>m("agent",t.target.value||null),children:[e.jsx("option",{value:"",children:"all agents"}),O.map(t=>e.jsx("option",{value:t,children:t},t))]}),e.jsxs("label",{className:"flex items-center gap-2 font-label text-xs font-medium text-outline cursor-pointer",children:[e.jsx("input",{type:"checkbox","data-testid":"show-ended",checked:h,onChange:t=>m("ended",t.target.checked?"1":"0")}),"Show ended"]}),e.jsxs("button",{type:"button","data-testid":"sync-sessions",disabled:T.isPending,className:"min-h-11 px-2 inline-flex items-center gap-1 font-label text-xs font-medium text-primary hover:text-on-surface disabled:opacity-50",onClick:()=>T.mutate(),children:[e.jsx(Ie,{className:`h-3 w-3 ${T.isPending?"animate-spin":""}`}),T.isPending?"Syncing":"Refresh"]})]})]}),T.error&&e.jsx("p",{role:"alert",className:"mb-3 text-sm text-error",children:T.error.message}),D.error?e.jsx(Ue,{message:D.error.message,onRetry:()=>D.refetch()}):P?e.jsx("p",{role:"status",className:"py-8 text-sm text-outline",children:"Loading sessions…"}):n.length===0?e.jsx(mt,{message:g?"No sessions match":"No active agent sessions. Enable Show ended to browse previous conversations."}):e.jsxs("div",{className:"min-w-0 overflow-hidden",children:[d?e.jsxs(ht,{children:[e.jsx(pt,{children:e.jsxs(qe,{className:"border-b border-border hover:bg-transparent",children:[e.jsx(B,{className:`${M} w-40`,children:"Status"}),e.jsx(B,{className:`${M} w-20`,children:"Agent"}),e.jsx(B,{className:M,children:"Session"}),e.jsx(B,{className:`${M} w-28`,children:"Project"}),e.jsx(B,{className:`${M} w-20 text-right`,children:"Tokens"}),e.jsx(B,{className:`${M} w-36`,children:"Last active"}),e.jsx(B,{className:`${M} w-56`,children:"Task"}),e.jsx(B,{className:`${M} w-24`})]})}),e.jsx(gt,{children:n.slice(v,v+V).map(t=>{var _,C;const N=ae[t.status];return e.jsxs(qe,{"data-testid":"live-session-row","data-session-id":t.session_id,"data-agent":t.agent,className:"border-b border-border/65 cursor-pointer hover:bg-surface-high",onClick:y=>{y.target.closest("button, a, input, [role='dialog']")||m("session",t.id)},children:[e.jsx(I,{className:"font-label text-xs text-on-surface",children:e.jsxs("span",{className:"inline-flex items-center gap-2","data-testid":"live-status",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${N.dot}`}),((_=t.handoff)==null?void 0:_.status)==="ready"?"Ready":N.label]})}),e.jsx(I,{className:"font-label text-xs font-medium text-primary",children:t.agent}),e.jsxs(I,{className:"max-w-md",children:[e.jsx("button",{type:"button",className:"block max-w-full text-left font-body text-sm font-medium text-on-surface truncate hover:text-primary",onClick:y=>{y.stopPropagation(),m("session",t.id)},children:e.jsx(G,{text:t.name??"Untitled session",query:g?x:""})}),t.summary&&t.summary!==t.name&&e.jsx("div",{className:"font-body text-xs text-outline truncate",title:t.summary,children:e.jsx(G,{text:t.summary,query:g?x:""})}),(C=t.snippets)==null?void 0:C.map(y=>e.jsx("div",{"data-testid":"search-snippet",className:"font-mono text-xs text-on-surface-variant truncate",title:y,children:e.jsx(G,{text:y,query:x})},y)),e.jsx("div",{className:"font-label text-xs text-outline truncate",title:t.cwd??void 0,children:t.cwd??""})]}),e.jsx(I,{className:"font-label text-xs text-outline",children:t.project_id&&R.get(t.project_id)||"—"}),e.jsx(I,{"data-testid":"live-tokens",className:"font-body text-xs text-on-surface-variant text-right",children:he(t)}),e.jsx(I,{className:"font-body text-xs text-on-surface-variant",children:ne(t.last_activity_at)}),e.jsx(I,{children:e.jsx(ge,{session:t})}),e.jsx(I,{className:"text-right",children:e.jsx("div",{className:"inline-flex items-center gap-3",children:e.jsx(pe,{session:t})})})]},t.id)})})]}):e.jsx("div",{className:"divide-y divide-border",children:n.slice(v,v+V).map(t=>{var N,_;return e.jsxs("article",{"data-testid":"live-session-row","data-session-id":t.session_id,"data-agent":t.agent,className:"py-4 space-y-3",children:[e.jsx("button",{type:"button",className:"text-left text-sm font-medium break-words hover:text-primary",onClick:()=>m("session",t.id),children:e.jsx(G,{text:t.name??"Untitled session",query:g?x:""})}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-outline",children:[e.jsx("span",{className:"text-primary",children:t.agent}),e.jsx("span",{"data-testid":"live-status",children:((N=t.handoff)==null?void 0:N.status)==="ready"?"Ready":ae[t.status].label}),e.jsxs("span",{"data-testid":"live-tokens",children:[he(t)," tokens"]}),e.jsx("span",{children:ne(t.last_activity_at)})]}),t.summary&&e.jsx("p",{className:"text-sm text-outline break-words",children:e.jsx(G,{text:t.summary,query:g?x:""})}),(_=t.snippets)==null?void 0:_.map(C=>e.jsx("p",{"data-testid":"search-snippet",className:"text-xs break-words text-on-surface-variant",children:e.jsx(G,{text:C,query:x})},C)),e.jsxs("p",{className:"text-xs text-outline break-all",children:[t.project_id&&R.get(t.project_id)||"Unassigned",t.cwd?` · ${t.cwd}`:""]}),e.jsx(ge,{session:t}),e.jsx(pe,{session:t})]},t.id)})}),e.jsx(vt,{page:v/V,pageSize:V,total:n.length,onPage:o})]}),e.jsx(Lt,{sessionId:i,initialQuery:g?x.trim():"",onClose:()=>m("session",null)},i??"closed")]})}function Ut({projectId:s}){const d=bt(s);return e.jsxs("div",{children:[e.jsx(ft,{title:"Sessions"}),e.jsx(Et,{projectId:d},d),e.jsx(yt,{projectId:d},`archive-${d}`)]})}export{Ut as default};
5
+ `)})]},a.index)),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(F,{variant:"ghost",disabled:!r,onClick:()=>v(Math.max(0,r-50)),children:"Previous messages"}),e.jsx(F,{variant:"ghost",disabled:r+50>=(((_e=te.data)==null?void 0:_e.total)??0),onClick:()=>v(r+50),children:"Next messages"})]}),e.jsxs("div",{className:"space-y-2 border-t border-outline-variant pt-3",children:[e.jsx("h3",{className:"text-sm font-medium",children:"Continue on ORC"}),e.jsx("p",{className:"text-xs text-outline",children:"Use the pushed repository, branch and exact commit for the work you want to continue. The destination project must have its repository configured."}),e.jsx(ee,{htmlFor:"archive-repository",children:"Repository"}),e.jsx(W,{id:"archive-repository","data-testid":"archive-repository",value:E,onChange:a=>T(a.target.value)}),e.jsx(ee,{htmlFor:"archive-branch",children:"Branch"}),e.jsx(W,{id:"archive-branch","data-testid":"archive-branch",value:R,onChange:a=>z(a.target.value)}),e.jsx(ee,{htmlFor:"archive-commit",children:"Pushed commit"}),e.jsx(W,{id:"archive-commit","data-testid":"archive-commit",value:O,onChange:a=>P(a.target.value)}),e.jsx(ee,{htmlFor:"archive-subdirectory",children:"Repository subdirectory"}),e.jsx(W,{id:"archive-subdirectory","data-testid":"archive-subdirectory",value:D,onChange:a=>U(a.target.value),placeholder:"Repository root"}),e.jsx(F,{"data-testid":"archive-resume",disabled:c||!E||!R||!/^[a-f0-9]{40}$/i.test(O),onClick:()=>void ne(async()=>{if(!n)return;const a=await J.sessions.archiveResume(n.id,{revision:n.revision,repository:E,branch:R,commit:O,subdirectory:D});if(a.status!=="ready"||!a.live_session_id)throw new Error(a.error||"Session preparation failed");const S=await J.terminals.create({kind:n.agent,live_session_id:a.live_session_id});u(`/terminals/${S.id}`)}),children:c?"Preparing…":"Prepare and resume in terminal"}),b&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:b})]})]})})]}):null}function G({text:s,query:d}){const u=d.trim();if(u.length<2)return e.jsx(e.Fragment,{children:s});const f=s.split(new RegExp(`(${ot(u)})`,"gi"));return e.jsx(e.Fragment,{children:f.map((p,h)=>p.toLowerCase()===u.toLowerCase()?e.jsx("mark",{className:"bg-primary/30 text-on-surface rounded-sm",children:p},h):p)})}function Nt({projectId:s,pending:d,onSelect:u}){var b;const[f,p]=l.useState(""),[h,x]=l.useState(!1),[n,i]=l.useState(null),w=le({queryKey:["tasks","session-picker",s],queryFn:()=>J.tasks.list({...s?{project_id:s}:{},limit:100})});async function k(o){i(null);try{await u(o)}catch(m){i(m instanceof Error?m.message:"Could not link task")}}async function c(){x(!0),i(null);try{const o=await J.tasks.get(f.trim());await k(o.id)}catch(o){i(o instanceof Error?o.message:"Task lookup failed")}finally{x(!1)}}const L=(((b=w.data)==null?void 0:b.tasks)??[]).filter(o=>`${o.title} ${o.id}`.toLowerCase().includes(f.trim().toLowerCase()));return e.jsxs("div",{className:"space-y-3",children:[e.jsx(W,{"data-testid":"session-task-search","aria-label":"Search tasks or enter a task ID",value:f,onChange:o=>{p(o.target.value),i(null)},placeholder:"Search recent tasks or paste a task ID"}),e.jsxs("p",{className:"text-xs text-outline",children:["Up to 100 recent tasks",s?" in this project":" across projects",". Older or other-project tasks can be linked by exact ID."]}),n&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:n}),w.error?e.jsx(He,{message:w.error.message,onRetry:()=>w.refetch()}):w.isLoading?e.jsx("p",{role:"status",children:"Loading tasks…"}):e.jsxs("div",{className:"max-h-72 overflow-y-auto divide-y divide-border",children:[L.map(o=>e.jsxs("button",{type:"button","data-testid":"session-task-option","data-task-id":o.id,disabled:d||h,onClick:()=>void k(o.id),className:"w-full min-h-11 py-2 text-left hover:bg-surface-highest disabled:opacity-50",children:[e.jsx("span",{className:"block text-sm break-words",children:o.title}),e.jsxs("span",{className:"inline-flex items-center gap-2 text-xs text-outline",children:[e.jsx(Fe,{status:o.status,className:"px-0"}),o.id]})]},o.id)),L.length===0&&e.jsx("p",{className:"py-4 text-sm text-outline",children:"No recent task matches. Paste its exact ID to look it up."})]}),f.trim()&&e.jsx(F,{variant:"outline",disabled:d||h,onClick:()=>void c(),children:h?"Looking up…":"Link by exact ID"})]})}function ge({session:s,linkTestId:d="open-task"}){const[u]=fe(),[f,p]=l.useState(!1),h=dt(),x=u.get("project")??s.project_id;async function n(i){try{await h.mutateAsync({id:s.id,taskId:i}),p(!1)}catch{}}return e.jsxs("div",{className:"min-w-0 space-y-1",children:[s.task&&e.jsxs("div",{className:"min-w-0",children:[e.jsx(Qe,{"data-testid":d,to:lt(`/tasks/${s.task.id}`,x),className:"block max-w-64 truncate text-sm text-primary hover:underline",title:s.task.title,children:s.task.title}),e.jsx(Fe,{status:s.task.status,className:"px-0"})]}),e.jsxs(ce,{open:f,onOpenChange:i=>{p(i),i&&h.reset()},children:[e.jsx(Ge,{asChild:!0,children:e.jsxs("button",{type:"button","data-testid":"link-task",className:"inline-flex min-h-9 items-center gap-1.5 text-xs text-outline hover:text-on-surface",children:[s.task?e.jsx(ht,{size:12}):e.jsx(ct,{size:13}),s.task?"Change task":"Link task"]})}),e.jsxs(de,{"data-testid":"session-task-dialog",className:"max-h-[85dvh] w-[calc(100%-2rem)] overflow-y-auto",children:[e.jsxs(xe,{children:[e.jsx(ue,{children:"Link a task"}),e.jsxs(me,{children:["Choose a recent task for ",s.name??"this session",", or paste an exact task ID."]})]}),h.error&&e.jsx("p",{role:"alert",className:"text-sm text-error",children:h.error.message}),e.jsx(Nt,{projectId:s.project_id,pending:h.isPending,onSelect:n}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.task&&e.jsx(F,{variant:"outline","data-testid":"session-task-unlink",disabled:h.isPending,onClick:()=>void n(null),children:"Unlink task"})})]})]})]})}const oe="session-search",wt={user:"border-border/65",assistant:"border-border/65",tool:"border-border/65 bg-transparent",system:"border-border/65 bg-transparent"},kt=["command","cmd","file_path","path","pattern","query","url","description"];function St(s){try{const d=JSON.parse(s);for(const u of kt)if(typeof d[u]=="string")return d[u]}catch{}return s}function Ct(s){try{return JSON.stringify(JSON.parse(s),null,2)}catch{return s}}function _t(s,d,u){l.useEffect(()=>{const f=s.current,p=CSS.highlights,h=window.Highlight;if(!f||!p||!h)return;const x=d.trim().toLowerCase(),n=()=>{var L;if(p.delete(oe),x.length<2)return;const k=[],c=document.createTreeWalker(f,NodeFilter.SHOW_TEXT);for(let b=c.nextNode();b;b=c.nextNode()){const o=((L=b.textContent)==null?void 0:L.toLowerCase())??"";for(let m=o.indexOf(x);m>=0;m=o.indexOf(x,m+x.length)){const g=new Range;g.setStart(b,m),g.setEnd(b,m+x.length),k.push(g)}}k.length>0&&p.set(oe,new h(...k))};n();let i;const w=new MutationObserver(()=>{clearTimeout(i),i=setTimeout(n,150)});return w.observe(f,{childList:!0,subtree:!0,characterData:!0}),()=>{clearTimeout(i),w.disconnect(),p.delete(oe)}},[s,d,u])}function Tt({block:s,open:d}){const u=s.result!==void 0;return e.jsxs("details",{open:d||void 0,"data-testid":"tool-box",className:"border-l border-border bg-background",children:[e.jsxs("summary",{className:"flex cursor-pointer items-center gap-2 px-2 py-1.5 font-label text-xs font-medium text-outline hover:text-on-surface",children:[e.jsx("span",{className:"text-secondary shrink-0",children:s.name}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono normal-case tracking-normal text-on-surface-variant",children:St(s.input)}),e.jsx("span",{className:`shrink-0 ${u?"text-outline":"text-tertiary"}`,children:u?"done":"no result"})]}),e.jsxs("div",{className:"space-y-2 border-t border-border px-2 py-2",children:[e.jsx("div",{className:"font-label text-[10px] font-medium text-outline",children:"input"}),e.jsx("pre",{className:"max-h-72 overflow-auto rounded-lg bg-background p-2 font-mono text-xs text-on-surface-variant whitespace-pre-wrap break-words",children:Ct(s.input)}),u&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"font-label text-[10px] font-medium text-outline",children:"result"}),e.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg bg-background p-2 font-mono text-xs text-on-surface-variant whitespace-pre-wrap break-words",children:s.result})]})]})]})}function Lt({block:s,matched:d}){if(s.type==="text")return e.jsx(Oe,{revealContext:d,children:s.text});if(s.type==="tool_use")return e.jsx(Tt,{block:s,open:d});const u=s.type==="thinking"?"thinking":"result";return e.jsxs("details",{open:d||void 0,children:[e.jsx("summary",{className:"cursor-pointer font-label text-xs font-medium text-outline hover:text-on-surface",children:u}),s.type==="thinking"?e.jsx("div",{className:"mt-1",children:e.jsx(rt,{children:s.text})}):e.jsx("pre",{className:"mt-1 max-h-96 overflow-auto rounded-lg bg-background p-2 font-mono text-xs text-on-surface-variant whitespace-pre-wrap break-words",children:s.text})]})}function $t({sessionId:s,initialQuery:d,onClose:u}){const[f,p]=l.useState(d),[h,x]=l.useState(0),{data:n}=Be(!1),i=n==null?void 0:n.find(r=>r.id===s),w=i!==void 0&&i.status!=="stopped",k=f.trim().length>=2?f.trim():"",{data:c,isLoading:L,isFetching:b,error:o,refetch:m,dataUpdatedAt:g}=xt(s,k),A=l.useRef(null),$=l.useRef(null),E=l.useRef(!0),T=l.useRef(0),[R,z]=l.useState(!0),O=l.useCallback(()=>{const r=A.current;r&&(r.scrollTo({top:r.scrollHeight}),requestAnimationFrame(()=>r.scrollTo({top:r.scrollHeight})))},[]);_t($,k,c==null?void 0:c.turns);const P=(c==null?void 0:c.matches)??[],D=P[h];l.useEffect(()=>{var r;if(c){if(D!==void 0){E.current=!1,(r=document.getElementById(`turn-${D}`))==null||r.scrollIntoView({block:"center"});return}E.current&&O()}},[D,c,O]),l.useEffect(()=>{c&&R&&(T.current=c.total)},[c,R]);const U=r=>{P.length>0&&x(v=>(v+r+P.length)%P.length)};return e.jsx(Ve,{open:!!s,onOpenChange:r=>!r&&u(),children:e.jsxs(We,{side:"right",className:"w-[1100px] max-w-[95vw]","data-testid":"live-session-detail",children:[e.jsxs(Ye,{children:[e.jsx(Xe,{className:"normal-case tracking-normal text-sm pr-8",children:(i==null?void 0:i.name)??"Session"}),i&&e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-5 gap-y-1 font-body text-xs text-on-surface tabular-nums",children:[e.jsx("span",{className:"font-medium text-primary",children:i.agent}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${ae[i.status].dot}`}),ae[i.status].label]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-on-surface-variant",children:"tokens "}),he(i)]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-on-surface-variant",children:"active "}),re(i.last_activity_at)]}),e.jsx(ge,{session:i,linkTestId:"detail-open-task"}),e.jsx(pe,{session:i}),e.jsx("span",{className:"truncate max-w-full text-on-surface-variant",children:i.cwd})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[150px] flex-1",children:[e.jsx(Ue,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-outline"}),e.jsx("input",{"data-testid":"transcript-search","aria-label":"Search this session",value:f,onChange:r=>{p(r.target.value),x(0)},placeholder:"Search this session",className:"w-full bg-background border border-control-border rounded-lg min-h-11 pl-7 pr-2 py-2 font-body text-xs text-on-surface"})]}),k&&e.jsx("span",{"data-testid":"transcript-match-count",className:"font-label text-xs font-medium text-outline",children:P.length===0?"no matches":`${h+1} / ${P.length}`}),e.jsx("button",{type:"button","aria-label":"Previous match",onClick:()=>U(-1),className:"min-h-11 min-w-11 p-2 text-outline hover:text-on-surface",children:e.jsx(Ze,{className:"h-4 w-4"})}),e.jsx("button",{type:"button","aria-label":"Next match",onClick:()=>U(1),className:"min-h-11 min-w-11 p-2 text-outline hover:text-on-surface",children:e.jsx(et,{className:"h-4 w-4"})}),e.jsxs("button",{type:"button","data-testid":"transcript-refresh",onClick:()=>{E.current=!0,m()},className:"min-h-11 px-2 inline-flex items-center gap-1 font-label text-xs font-medium text-primary hover:text-on-surface",children:[e.jsx(Ie,{className:`h-3 w-3 ${b?"animate-spin":""}`}),"Refresh"]})]}),c&&e.jsxs("div",{"data-testid":"transcript-status",className:"mt-2 font-body text-xs text-on-surface-variant tabular-nums",children:[c.total," turns",w?` · live, updated ${new Date(g).toLocaleTimeString()}`:""]})]}),e.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[e.jsx(tt,{ref:A,onScroll:r=>{const v=r.currentTarget,q=v.scrollHeight-v.scrollTop-v.clientHeight<160;E.current=q,z(q)},children:L?e.jsx("div",{className:"space-y-4",children:[...Array(5)].map((r,v)=>e.jsx(st,{className:"h-16 w-full bg-surface-highest"},v))}):o||!c?e.jsxs("div",{"data-testid":"transcript-unavailable",className:"font-body text-xs text-outline py-12 text-center",children:[o?`Could not load the conversation: ${o.message}`:"No conversation was recorded for this session.",e.jsx("p",{className:"mt-2",children:"Resume actions remain available when the native agent session exists."}),e.jsx("button",{type:"button",className:"mt-3 min-h-11 text-primary hover:underline",onClick:()=>m(),children:"Retry conversation"})]}):e.jsx("div",{ref:$,className:"space-y-3",children:c.turns.map(r=>{const v=P.includes(r.index),q=r.blocks.map((H,t)=>e.jsx(Lt,{block:H,matched:v},t));return e.jsxs("div",{id:`turn-${r.index}`,"data-testid":"transcript-turn","data-role":r.role,style:{contentVisibility:"auto",containIntrinsicSize:"auto 120px"},className:`border-b px-4 py-3 text-on-surface space-y-2 ${wt[r.role]} ${r.index===D?"ring-1 ring-primary":""}`,children:[e.jsxs("div",{className:"font-label text-xs font-medium text-outline",children:[r.role,r.time?` · ${re(r.time)}`:""]}),r.role==="system"?e.jsxs("details",{open:v||void 0,children:[e.jsx("summary",{className:"cursor-pointer font-label text-xs font-medium text-outline hover:text-on-surface",children:"injected context"}),e.jsx("div",{className:"mt-2 space-y-2",children:q})]}):q]},r.index)})})}),c&&!R&&e.jsxs("button",{type:"button","data-testid":"jump-to-latest",onClick:()=>{E.current=!0,O()},className:"absolute bottom-4 right-6 inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 font-body text-xs text-primary shadow-lg hover:bg-surface-bright",children:[e.jsx(at,{className:"h-3.5 w-3.5"}),"Jump to latest",c.total>T.current&&` · ${c.total-T.current} new`]})]})]})})}const Pt=["claude","codex","cursor","cursor-agent","gemini"],V=25,M="font-label text-xs font-medium text-outline";function Et({projectId:s}){var H;const d=nt("sm"),[u,f]=fe(),p=u.get("agent")??"",h=u.get("ended")!=="0",x=u.get("q")??"",n=u.get("order")==="asc"?"asc":"desc",i=u.get("session"),[w,k]=l.useState(x),[c,L]=l.useState({order:n,page:0}),b=c.order===n?c.page:0,o=l.useCallback(t=>L({order:n,page:t}),[n]),m=l.useCallback((t,N)=>{o(0),f(_=>{const C=new URLSearchParams(_);return N?C.set(t,N):C.delete(t),C},{replace:t==="q"})},[f,o]);l.useEffect(()=>k(x),[x]),l.useEffect(()=>{if(w===x)return;const t=setTimeout(()=>m("q",w.trim()||null),350);return()=>clearTimeout(t)},[w,x,m]);const g=x.trim().length>=2,A=Be(!h),$=ut(g?x.trim():"",p),{data:E}=Ae(),T=mt(),R=new Map((E??[]).map(t=>[t.id,t.name])),z=g?((H=$.data)==null?void 0:H.hits)??[]:A.data??[],O=[...new Set([...Pt,...z.map(t=>t.agent)])],P=g?$.isLoading:A.isLoading,D=g?$:A,U=z.filter(t=>{var N;return(!p||t.agent===p)&&(h||t.status!=="stopped"||((N=t.handoff)==null?void 0:N.status)==="ready")}),r=U.filter(t=>s==="all"?!0:s==="unassigned"?t.project_id===null:t.project_id===s).sort((t,N)=>{const C=new Date(t.last_activity_at??t.created_at).getTime()-new Date(N.last_activity_at??N.created_at).getTime()||t.id.localeCompare(N.id);return n==="asc"?C:-C}),v=Math.min(b,Math.max(0,Math.ceil(r.length/V)-1))*V,q=s==="unassigned"?"unassigned":R.get(s)??s;return e.jsxs("section",{className:"mb-8","data-testid":"live-sessions",children:[e.jsx("p",{className:"mb-4 text-sm text-outline",children:"Discovered from your coding agents. Working sessions update automatically; waiting sessions remain available to resume."}),e.jsxs("div",{className:"mb-3 relative",children:[e.jsx(Ue,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-outline"}),e.jsx("input",{"data-testid":"session-search","aria-label":"Search agent sessions",value:w,onChange:t=>k(t.target.value),placeholder:"Search agent sessions: titles, summaries and conversation text",className:"w-full bg-background border border-control-border rounded-lg pl-9 pr-3 py-2 font-body text-xs text-on-surface placeholder:text-outline"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[e.jsxs("h2",{className:"font-label text-xs font-medium text-outline",children:[g?"Search results":"Agent sessions"," · ",r.length,r.length!==U.length&&e.jsxs("span",{"data-testid":"scope-hint",className:"normal-case tracking-normal",children:[" ","of ",U.length," · scope: ",q]}),g&&$.data&&e.jsxs("span",{"data-testid":"search-meta",className:"normal-case tracking-normal",children:[" ","· ",($.data.ms/1e3).toFixed(1),"s",$.data.rg?"":" · titles and summaries only (install ripgrep for content)"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("select",{"aria-label":"Sort sessions by date","data-testid":"session-date-sort",value:n,onChange:t=>m("order",t.target.value==="asc"?"asc":null),className:"min-h-11 rounded-md border border-control-border bg-background px-3 text-sm text-on-surface",children:[e.jsx("option",{value:"desc",children:"Last active: newest first"}),e.jsx("option",{value:"asc",children:"Last active: oldest first"})]}),e.jsxs("select",{"data-testid":"agent-filter","aria-label":"Agent",className:"bg-background border border-control-border rounded-lg min-h-11 px-3 py-2 font-label text-xs font-medium text-on-surface",value:p,onChange:t=>m("agent",t.target.value||null),children:[e.jsx("option",{value:"",children:"all agents"}),O.map(t=>e.jsx("option",{value:t,children:t},t))]}),e.jsxs("label",{className:"flex items-center gap-2 font-label text-xs font-medium text-outline cursor-pointer",children:[e.jsx("input",{type:"checkbox","data-testid":"show-ended",checked:h,onChange:t=>m("ended",t.target.checked?"1":"0")}),"Show ended"]}),e.jsxs("button",{type:"button","data-testid":"sync-sessions",disabled:T.isPending,className:"min-h-11 px-2 inline-flex items-center gap-1 font-label text-xs font-medium text-primary hover:text-on-surface disabled:opacity-50",onClick:()=>T.mutate(),children:[e.jsx(Ie,{className:`h-3 w-3 ${T.isPending?"animate-spin":""}`}),T.isPending?"Syncing":"Refresh"]})]})]}),T.error&&e.jsx("p",{role:"alert",className:"mb-3 text-sm text-error",children:T.error.message}),D.error?e.jsx(He,{message:D.error.message,onRetry:()=>D.refetch()}):P?e.jsx("p",{role:"status",className:"py-8 text-sm text-outline",children:"Loading sessions…"}):r.length===0?e.jsx(it,{message:g?"No sessions match":"No active agent sessions. Enable Show ended to browse previous conversations."}):e.jsxs("div",{className:"min-w-0 overflow-hidden",children:[d?e.jsxs(gt,{children:[e.jsx(ft,{children:e.jsxs(qe,{className:"border-b border-border hover:bg-transparent",children:[e.jsx(B,{className:`${M} w-40`,children:"Status"}),e.jsx(B,{className:`${M} w-20`,children:"Agent"}),e.jsx(B,{className:M,children:"Session"}),e.jsx(B,{className:`${M} w-28`,children:"Project"}),e.jsx(B,{className:`${M} w-20 text-right`,children:"Tokens"}),e.jsx(B,{className:`${M} w-36`,children:"Last active"}),e.jsx(B,{className:`${M} w-56`,children:"Task"}),e.jsx(B,{className:`${M} w-24`})]})}),e.jsx(jt,{children:r.slice(v,v+V).map(t=>{var _,C;const N=ae[t.status];return e.jsxs(qe,{"data-testid":"live-session-row","data-session-id":t.session_id,"data-agent":t.agent,className:"border-b border-border/65 cursor-pointer hover:bg-surface-high",onClick:y=>{y.target.closest("button, a, input, [role='dialog']")||m("session",t.id)},children:[e.jsx(I,{className:"font-label text-xs text-on-surface",children:e.jsxs("span",{className:"inline-flex items-center gap-2","data-testid":"live-status",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${N.dot}`}),((_=t.handoff)==null?void 0:_.status)==="ready"?"Ready":N.label]})}),e.jsx(I,{className:"font-label text-xs font-medium text-primary",children:t.agent}),e.jsxs(I,{className:"max-w-md",children:[e.jsx("button",{type:"button",className:"block max-w-full text-left font-body text-sm font-medium text-on-surface truncate hover:text-primary",onClick:y=>{y.stopPropagation(),m("session",t.id)},children:e.jsx(G,{text:t.name??"Untitled session",query:g?x:""})}),t.summary&&t.summary!==t.name&&e.jsx("div",{className:"font-body text-xs text-outline truncate",title:t.summary,children:e.jsx(G,{text:t.summary,query:g?x:""})}),(C=t.snippets)==null?void 0:C.map(y=>e.jsx("div",{"data-testid":"search-snippet",className:"font-mono text-xs text-on-surface-variant truncate",title:y,children:e.jsx(G,{text:y,query:x})},y)),e.jsx("div",{className:"font-label text-xs text-outline truncate",title:t.cwd??void 0,children:t.cwd??""})]}),e.jsx(I,{className:"font-label text-xs text-outline",children:t.project_id&&R.get(t.project_id)||"—"}),e.jsx(I,{"data-testid":"live-tokens",className:"font-body text-xs text-on-surface-variant text-right",children:he(t)}),e.jsx(I,{className:"font-body text-xs text-on-surface-variant",children:re(t.last_activity_at)}),e.jsx(I,{children:e.jsx(ge,{session:t})}),e.jsx(I,{className:"text-right",children:e.jsx("div",{className:"inline-flex items-center gap-3",children:e.jsx(pe,{session:t})})})]},t.id)})})]}):e.jsx("div",{className:"divide-y divide-border",children:r.slice(v,v+V).map(t=>{var N,_;return e.jsxs("article",{"data-testid":"live-session-row","data-session-id":t.session_id,"data-agent":t.agent,className:"py-4 space-y-3",children:[e.jsx("button",{type:"button",className:"text-left text-sm font-medium break-words hover:text-primary",onClick:()=>m("session",t.id),children:e.jsx(G,{text:t.name??"Untitled session",query:g?x:""})}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-outline",children:[e.jsx("span",{className:"text-primary",children:t.agent}),e.jsx("span",{"data-testid":"live-status",children:((N=t.handoff)==null?void 0:N.status)==="ready"?"Ready":ae[t.status].label}),e.jsxs("span",{"data-testid":"live-tokens",children:[he(t)," tokens"]}),e.jsx("span",{children:re(t.last_activity_at)})]}),t.summary&&e.jsx("p",{className:"text-sm text-outline break-words",children:e.jsx(G,{text:t.summary,query:g?x:""})}),(_=t.snippets)==null?void 0:_.map(C=>e.jsx("p",{"data-testid":"search-snippet",className:"text-xs break-words text-on-surface-variant",children:e.jsx(G,{text:C,query:x})},C)),e.jsxs("p",{className:"text-xs text-outline break-all",children:[t.project_id&&R.get(t.project_id)||"Unassigned",t.cwd?` · ${t.cwd}`:""]}),e.jsx(ge,{session:t}),e.jsx(pe,{session:t})]},t.id)})}),e.jsx(pt,{page:v/V,pageSize:V,total:r.length,onPage:o})]}),e.jsx($t,{sessionId:i,initialQuery:g?x.trim():"",onClose:()=>m("session",null)},i??"closed")]})}function zt({projectId:s}){const d=bt(s);return e.jsxs("div",{children:[e.jsx(vt,{title:"Sessions"}),e.jsx(Et,{projectId:d},d),e.jsx(yt,{projectId:d},`archive-${d}`)]})}export{zt as default};