@overdeck/desktop 0.45.13 → 0.45.16

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 (336) hide show
  1. package/package.json +1 -1
  2. package/server/{acceptance-criteria-CfujPRrz.js → acceptance-criteria-BZ_nQS1f.js} +2 -2
  3. package/server/{advancing-selfheal-Bn5QiLtn.js → advancing-selfheal-DJYAvGv-.js} +6 -5
  4. package/server/{agent-gc-Cl9Nm0Zu.js → agent-gc-D0wDIeV1.js} +3 -3
  5. package/server/{agent-state-C6Rm6FPR.js → agent-state-lGvgPP4m.js} +1 -1
  6. package/server/{agent-state-service-U8feBf8t.js → agent-state-service-CZrayD_G.js} +1 -1
  7. package/server/{agent-state-service-JhFzYCP_.js → agent-state-service-DFslS5go.js} +9 -52
  8. package/server/{agents-DqQa4Dq_.js → agents-B9GwfCyp.js} +155 -153
  9. package/server/{agents-CxbuBjID.js → agents-CEcaxSkR.js} +1 -1
  10. package/server/{archive-planning-CPitEZo4.js → archive-planning-CbghE9-o.js} +5 -5
  11. package/server/{archive-planning-DmpT1_14.js → archive-planning-CoyIbgGK.js} +1 -1
  12. package/server/{artifact-index-jobs-sMnNtPhy.js → artifact-index-jobs-CcSrUoSE.js} +2 -2
  13. package/server/auto-commit-IW-eik_b.js +3 -0
  14. package/server/{backlog-auto-trigger-Cf9C8fwD.js → backlog-auto-trigger-BfgDsII0.js} +3 -3
  15. package/server/{bd-process-lock-D1aJxeYv.js → bd-process-lock-XAXAet9O.js} +32 -11
  16. package/server/{beads-CivpXztb.js → beads-B1u04n3o.js} +1 -1
  17. package/server/{beads-DRoj6-e1.js → beads-BeSMEjGT.js} +96 -196
  18. package/server/{beads-query-tOsAYP5h.js → beads-query-Dl4FhT8J.js} +24 -99
  19. package/server/beads-restore-BUItPOjI.js +23 -0
  20. package/server/behavior-BTpYbAv4.js +10 -0
  21. package/server/{briefing-freshness-BL3Q6p7R.js → briefing-freshness-DESTCWo-.js} +4 -4
  22. package/server/{checkpoint-manager-DCxjQvP_.js → checkpoint-manager-BwFdegJF.js} +2 -2
  23. package/server/{checkpoint-manager-j5URlFY7.js → checkpoint-manager-DWSXooZV.js} +1 -1
  24. package/server/checkpoint-worker.js +1 -1
  25. package/server/{checkpoints-BoX1H2Hf.js → checkpoints-BtUonbs3.js} +2 -2
  26. package/server/{checkpoints-Bu_M_Q9W.js → checkpoints-fjadfOKF.js} +1 -1
  27. package/server/{claude-hooks-provision-D-jGXmu1.js → claude-hooks-provision-DAtxutOs.js} +132 -114
  28. package/server/claude-hooks-provision-DiK62u0k.js +3 -0
  29. package/server/{claude-permissions-DxIjkOVl.js → claude-permissions-CThLgf8d.js} +2 -2
  30. package/server/{claude-settings-overlay-BPDS6GfE.js → claude-settings-overlay-BF9MPIwx.js} +2 -2
  31. package/server/{claude-settings-overlay-5b9X2S0C.js → claude-settings-overlay-Dx_Uqcmv.js} +1 -1
  32. package/server/{cli-s7bPWy-E.js → cli-ByKIIMfT.js} +9 -9
  33. package/server/cli-D9cUTbBr.js +3 -0
  34. package/server/{cliproxy-BituqWtR.js → cliproxy-B4c1BUvs.js} +2 -2
  35. package/server/{cliproxy-D3sHB0sI.js → cliproxy-C_GuT5DU.js} +1 -1
  36. package/server/{close-issue-CrBE7voz.js → close-issue-BOuLKr6e.js} +5 -5
  37. package/server/{closed-issue-reaper-BRQBc7Xa.js → closed-issue-reaper-CksfuiFD.js} +1 -1
  38. package/server/{closed-issue-reaper-DX9mYUji.js → closed-issue-reaper-DCAYzNXW.js} +102 -30
  39. package/server/{codex-Bi1ITSOo.js → codex-BYPz6ZdF.js} +1 -1
  40. package/server/{codex-CO0HrK3j.js → codex-BbqIRZjd.js} +6 -5
  41. package/server/{behavior-D3d2mVyD.js → codex-parser-mFYZh8vR.js} +3 -9
  42. package/server/{compact-beads-DUkCUFxA.js → compact-beads-CyJtoXJi.js} +15 -8
  43. package/server/{compact-beads-CrA8-k10.js → compact-beads-N00E4EVa.js} +1 -1
  44. package/server/{config-DsCxzjXK.js → config-DVLdmnMJ.js} +2 -2
  45. package/server/{config-B4_d7z7z.js → config-Dj6N8EP9.js} +1 -1
  46. package/server/{config-yaml-C_djSurJ.js → config-yaml-cNOZcEww.js} +118 -23
  47. package/server/{conflict-gate-D47Kl78u.js → conflict-gate-BMKm_5DV.js} +3 -3
  48. package/server/{conflict-gate-CpOn9KC-.js → conflict-gate-CuXUv-bP.js} +1 -1
  49. package/server/{context-layers-CHl3Nroz.js → context-layers-CeAwSYNt.js} +2 -2
  50. package/server/{context-layers-BNhUBTkf.js → context-layers-c0JqYHcS.js} +3 -3
  51. package/server/{control-settings-KyYNXZLv.js → control-settings-D4EFsRBd.js} +4 -4
  52. package/server/{conversation-compaction-D3aS5PnS.js → conversation-compaction-BCggyih4.js} +8 -8
  53. package/server/{conversation-compaction-D4Wed1BJ.js → conversation-compaction-kHVfVRg3.js} +1 -1
  54. package/server/{conversation-service-CFZIjs-M.js → conversation-service-B8LFQQm1.js} +6 -5
  55. package/server/{conversation-service-DcDB5usR.js → conversation-service-BTzObqGi.js} +1 -1
  56. package/server/{conversations-BSOU5qnu.js → conversations-B-lcHv-5.js} +4 -4
  57. package/server/{conversations-BbDPrz89.js → conversations-BM7zlXjr.js} +1 -1
  58. package/server/{cost-BE_ulOrw.js → cost-BcpRQ-7o.js} +3 -3
  59. package/server/{cost-CaiG63FG.js → cost-D9kPIY_5.js} +2 -2
  60. package/server/{cost-sync-D6AX8jv-.js → cost-sync-DF6odxK9.js} +3 -3
  61. package/server/{dag-BQFtXOuJ.js → dag-DKI3sOmX.js} +3 -3
  62. package/server/{dangerous-git-ops-04Ba-Qu3.js → dangerous-git-ops-Bn18PEcN.js} +1 -1
  63. package/server/dashboard-db-worker.js +6 -6
  64. package/server/{deacon-Bz-6Wjmn.js → deacon-DONuopff.js} +3 -3
  65. package/server/{deacon-2EvA9Ci3.js → deacon-DdARMjZq.js} +188 -1601
  66. package/server/{deacon-swarm-DYYOzHRH.js → deacon-swarm-BNGkmYR_.js} +12 -105
  67. package/server/deacon-swarm-CvdFekIO.js +2 -0
  68. package/server/deacon.js +7 -7
  69. package/server/{devcontainer-renderer-Dx0C7VWJ.js → devcontainer-renderer-C-34Sxyz.js} +3 -3
  70. package/server/{dist-ya66D9ze.js → dist-BMXvKiZP.js} +1 -1
  71. package/server/dist-BNwrgsUO.js +3 -0
  72. package/server/{dist-src-Byxt1ifL.js → dist-src-BgGUblXg.js} +1 -1
  73. package/server/{docker-D2TbXDO6.js → docker-apZ9pBYw.js} +67 -28
  74. package/server/{ensure-devcontainer-BTiMfFp5.js → ensure-devcontainer-Bqi1EF1P.js} +4 -4
  75. package/server/{ensure-devcontainer-BIShzs3M.js → ensure-devcontainer-Dq3KoOIl.js} +1 -1
  76. package/server/{esm-shims-DiV9jHa_.js → esm-shims-BEjvINX3.js} +1 -1
  77. package/server/{event-store-C02Gprug.js → event-store-CqDgfbAs.js} +1 -1
  78. package/server/{event-store-C71x6h0i.js → event-store-D89fMfXS.js} +3 -3
  79. package/server/{events-BFDuPV6n.js → events-S_C0pvl6.js} +3 -3
  80. package/server/{events-D2gP2-Yv.js → events-rIGncmP1.js} +1 -1
  81. package/server/export-BJHSVwKP.js +87 -0
  82. package/server/{factory-ByfbrCab.js → factory-DV18m0rc.js} +5 -5
  83. package/server/{feature-registry-population-CSH66UO8.js → feature-registry-population-CqZSnqQi.js} +4 -4
  84. package/server/{feature-registry-storage-DW7dUefc.js → feature-registry-storage-BeXmNBwK.js} +2 -2
  85. package/server/{features-x_aLR7U9.js → features-u5XeMaOK.js} +2 -2
  86. package/server/{feedback-target-BFo9fScH.js → feedback-target-CwyWf0Dg.js} +6 -6
  87. package/server/{feedback-target-C4VMPTZu.js → feedback-target-DDG1PWl3.js} +1 -1
  88. package/server/{feedback-writer-DCyd75yJ.js → feedback-writer-BsJiw5aT.js} +1 -1
  89. package/server/{feedback-writer-B9ZqnnX3.js → feedback-writer-D20HSXre.js} +4 -4
  90. package/server/{flywheel-DwQCoZQG.js → flywheel-9Y1X7IM-.js} +13 -13
  91. package/server/{flywheel-D9NKvWqb.js → flywheel-Dczmgchd.js} +23 -15
  92. package/server/{flywheel-DB48X7Nn.js → flywheel-RCnHAgc4.js} +1 -1
  93. package/server/{flywheel-merge-order-DrjmFXg4.js → flywheel-merge-order-CtCYsFJP.js} +7 -7
  94. package/server/{flywheel-merge-order-f1bi5XIf.js → flywheel-merge-order-DEtEd3aK.js} +1 -1
  95. package/server/forge-8y6aEPTB.js +2 -0
  96. package/server/{forge-C-SoKy8U.js → forge-DFDThFil.js} +2 -2
  97. package/server/{from-fu7ZumnY.js → from-NSJypkI8.js} +1 -1
  98. package/server/{fts-db-CL-YzSRG.js → fts-db-C5A_TTOM.js} +2 -2
  99. package/server/{fts-operations-Bylu5NjM.js → fts-operations-DvCSimfU.js} +2 -2
  100. package/server/{git-utils-Ym380hJZ.js → git-utils-C0neHvQx.js} +1 -1
  101. package/server/{git-utils-C8koBs8j.js → git-utils-Dr0L7mFk.js} +2 -2
  102. package/server/{github-app-DIr70YLg.js → github-app-Bwt9lK4A.js} +1 -1
  103. package/server/{github-app-DhycHVLF.js → github-app-u9-SX7Gc.js} +2 -2
  104. package/server/{github-client-7gkcXcBS.js → github-client-Btyy3uan.js} +3 -3
  105. package/server/{github-client-Ji9lUTNF.js → github-client-Do3k-N1W.js} +1 -1
  106. package/server/{github-pr-lookup-rt7T9FwA.js → github-pr-lookup-DOF1U2WW.js} +2 -2
  107. package/server/{harness-resolve-CvGXUnAF.js → harness-resolve-C6g2R0Cd.js} +3 -3
  108. package/server/{health-events-D4E1DLN-.js → health-events-B4u-2a9m.js} +2 -2
  109. package/server/{health-events-DDfkoO5a.js → health-events-Bos3sk5g.js} +1 -1
  110. package/server/{hooks-D_6pAbuJ.js → hooks-BCoOjL_R.js} +2 -2
  111. package/server/{hooks-DvdnCVv6.js → hooks-uEr8WTx_.js} +1 -1
  112. package/server/{hume-DkVOs1Qi.js → hume-BqxYKbUf.js} +2 -2
  113. package/server/hume-CerGi2RH.js +3 -0
  114. package/server/{idle-stack-reaper-cDRXDpgE.js → idle-stack-reaper-DbZ8ukMd.js} +2 -2
  115. package/server/{idle-stack-reaper-DNbV9-fj.js → idle-stack-reaper-H0W6XtHh.js} +1 -1
  116. package/server/{infra-Clew3DpF.js → infra-Ba9mS6e6.js} +3 -3
  117. package/server/{injection-QCIHOpk6.js → injection-C1DKXeIZ.js} +1 -1
  118. package/server/{injection-ql0Nddcn.js → injection-yrMBxzVq.js} +7 -7
  119. package/server/{inspect-agent-DY18KEx4.js → inspect-agent-B-mnb4uh.js} +9 -9
  120. package/server/inspect-agent-CWkeAB7J.js +2 -0
  121. package/server/{internal-token-C90jBp-y.js → internal-token-BPYEaXFh.js} +1 -1
  122. package/server/{internal-token-BeXjPLKy.js → internal-token-BtqSbKTx.js} +2 -2
  123. package/server/{io-CbAFXQge.js → io-VEGSAqsd.js} +15 -22
  124. package/server/{issue-closed-BYC2TCk-.js → issue-closed-BxcePXL-.js} +4 -4
  125. package/server/{issue-lifecycle-BoJa6qIt.js → issue-lifecycle--8MRxrG1.js} +22 -22
  126. package/server/{issue-lifecycle-CLHbj8RS.js → issue-lifecycle-CdMUauyb.js} +1 -1
  127. package/server/{issue-service-singleton-BS9NENuR.js → issue-service-singleton-CkTUI-eu.js} +10 -10
  128. package/server/{issue-service-singleton-3g_CCY-1.js → issue-service-singleton-MZsDhAob.js} +1 -1
  129. package/server/{issues-BPcqPqfV.js → issues-CBAsuoAO.js} +2 -2
  130. package/server/jsonl-parser-BUW5_sSK.js +245 -0
  131. package/server/{label-cleanup-CwiCSZrb.js → label-cleanup-htK6fBRU.js} +3 -3
  132. package/server/{layers-OHHLphl0.js → layers-jjL16At6.js} +2 -2
  133. package/server/{lifecycle-B8IdvUbt.js → lifecycle-Ck2UR27D.js} +7 -7
  134. package/server/{lifecycle-io-BMCH1Bxg.js → lifecycle-io-DXv8Utct.js} +1 -1
  135. package/server/{lifecycle-io-C73m5e6R.js → lifecycle-io-IehcRt2v.js} +36 -47
  136. package/server/{linear-client-BMxgycoy.js → linear-client-By7hjwuN.js} +1 -1
  137. package/server/{linear-client-CgQlM4aT.js → linear-client-D9cSQfvD.js} +3 -3
  138. package/server/memory-fts-worker.js +1 -1
  139. package/server/{merge-BRkVaIx-.js → merge-BLcEZNXz.js} +1 -1
  140. package/server/{merge-B7Oi-g6k.js → merge-BN8FGJ2q.js} +3 -3
  141. package/server/{merge-agent-DNFFsiEm.js → merge-agent-B3u2szOL.js} +29 -29
  142. package/server/{merge-agent-Bwm34MZ5.js → merge-agent-ejC7Wos8.js} +1 -1
  143. package/server/{merge-batch-BpYXUaqJ.js → merge-batch-DyqlgYGp.js} +1 -1
  144. package/server/{merge-blockers-DIOZmqdK.js → merge-blockers-cq-aS2KG.js} +2 -2
  145. package/server/merge-ops-CFkQtXEj.js +2 -0
  146. package/server/{merge-rebase-C8WH39MB.js → merge-rebase-Dl7yIxtV.js} +2 -2
  147. package/server/{merge-set-CsEE2CyQ.js → merge-set-CZ9Nbay0.js} +3 -3
  148. package/server/{merge-set-DOsBTBQc.js → merge-set-Dy0D0r3i.js} +1 -1
  149. package/server/{merge-sync-CcLM2vwW.js → merge-sync-CG9kDCdT.js} +1 -1
  150. package/server/{merge-sync-C2B322Ot.js → merge-sync-D7jWLgCC.js} +2 -2
  151. package/server/{merge-train-BIm7-7cy.js → merge-train-CH33XJOH.js} +3 -3
  152. package/server/{merge-train-deps-DG1oQ2DT.js → merge-train-deps-JoVdGnOg.js} +4 -4
  153. package/server/{merge-verification-BAbjxEd5.js → merge-verification-D4wTChdX.js} +4 -4
  154. package/server/{multipart-parser-jKtKAXtl.js → multipart-parser-Csn8U-K9.js} +2 -2
  155. package/server/{no-resume-mode-yrPEQ_pC.js → no-resume-mode-Gh5R_YLF.js} +1 -1
  156. package/server/node_modules/.package-lock.json +1 -1
  157. package/server/{orphan-proposed-reconciler-BqVGaOIj.js → orphan-proposed-reconciler-BIcNu4tl.js} +1 -1
  158. package/server/{orphan-proposed-reconciler-zHrwJ3xr.js → orphan-proposed-reconciler-DI_IS1p_.js} +15 -39
  159. package/server/package-lock.json +2 -2
  160. package/server/package.json +1 -1
  161. package/server/{pan-dir-BlNrLzW7.js → pan-dir-CQIfKG8c.js} +4 -4
  162. package/server/{paths-CiVeo4N_.js → paths-Blj6A9AJ.js} +2 -2
  163. package/server/{pickup-KLRUhThD.js → pickup-BtvRBbvI.js} +1 -1
  164. package/server/{pipeline-notifier-nkWCe042.js → pipeline-notifier-BH4PAi-w.js} +1 -1
  165. package/server/{pipeline-notifier-DBF6dHxH.js → pipeline-notifier-D_WYtEwl.js} +2 -2
  166. package/server/project-pipelines-jMTitpeO.js +162 -0
  167. package/server/projects-CrBE6IhN.js +3 -0
  168. package/server/{prompts-CXbQvevY.js → prompts-B3njaImU.js} +2 -2
  169. package/server/{providers-CUdAb5Qu.js → providers-BbEyFhPX.js} +7 -7
  170. package/server/providers-DnPxkHoG.js +3 -0
  171. package/server/public/assets/chunk-BO2N2NFS-3qh9TUJi.js +103 -0
  172. package/server/public/assets/{diagram-OG6HWLK6-NACO1xW5.js → diagram-OG6HWLK6-D8UVTPj7.js} +1 -1
  173. package/server/public/assets/{dist-DQD-ZjQY.js → dist-BvLLn1YC.js} +3 -3
  174. package/server/public/assets/{dist-D1FjqGgm.js → dist-CyubL7Wj.js} +1 -1
  175. package/server/public/assets/{ganttDiagram-6RSMTGT7-CEMAKgmE.js → ganttDiagram-6RSMTGT7-BI4E1LbQ.js} +1 -1
  176. package/server/public/assets/{highlighted-body-OFNGDK62-D5lC7FW8.js → highlighted-body-OFNGDK62-D_bapWkF.js} +1 -1
  177. package/server/public/assets/index-BAZxZ-8I.js +796 -0
  178. package/server/public/assets/index-FBG3JBfq.css +1 -0
  179. package/server/public/assets/{linear-DDHAMRPB.js → linear-CEdobObr.js} +1 -1
  180. package/server/public/assets/mermaid-GHXKKRXX-BYP8MI37.js +1 -0
  181. package/server/public/assets/{pieDiagram-4H26LBE5-DwBdeKBb.js → pieDiagram-4H26LBE5-DT79L01f.js} +1 -1
  182. package/server/public/assets/{prod-DAZt0c4G.js → prod-CR_K2DFV.js} +4 -4
  183. package/server/public/assets/{quadrantDiagram-W4KKPZXB-CNDLp-_m.js → quadrantDiagram-W4KKPZXB-BEkKXXrL.js} +1 -1
  184. package/server/public/assets/{sankeyDiagram-5OEKKPKP-oIUL_uO1.js → sankeyDiagram-5OEKKPKP-BxSCqn-j.js} +1 -1
  185. package/server/public/assets/{xychartDiagram-2RQKCTM6-B-IM6Cck.js → xychartDiagram-2RQKCTM6-DicwJGG_.js} +1 -1
  186. package/server/public/index.html +2 -2
  187. package/server/{pull-requests-DZ-V7_LB.js → pull-requests-43LPDfM8.js} +1 -1
  188. package/server/{pull-requests-kTRl7cWC.js → pull-requests-DyUkQl4W.js} +3 -3
  189. package/server/{rally-xCTZ-UcI.js → rally-BtWjybOa.js} +3 -3
  190. package/server/{rally-api-jOk4vit_.js → rally-api-B-YA_oXx.js} +1 -1
  191. package/server/{rally-api-DpZo3WwF.js → rally-api-B-osULNL.js} +2 -2
  192. package/server/{rally-client-BQjm3aaq.js → rally-client-CzFymP7P.js} +1 -1
  193. package/server/{rally-client-CoWZeVEj.js → rally-client-sErNQBO0.js} +5 -5
  194. package/server/rally-oggyp4cs.js +3 -0
  195. package/server/{reap-terminal-sessions-CAmURC2h.js → reap-terminal-sessions-2s-fvilz.js} +1 -1
  196. package/server/{reap-terminal-sessions-BwJb2DLJ.js → reap-terminal-sessions-DnDQ7pf9.js} +1 -1
  197. package/server/{rebuild-stack-BZ7j27xY.js → rebuild-stack-CoU-HqZj.js} +6 -6
  198. package/server/{rebuild-stack-r-cxcr26.js → rebuild-stack-nGD_nPZo.js} +1 -1
  199. package/server/{reconstruct-cache-13EkMg_i.js → reconstruct-cache-Wj8GrYB0.js} +6 -6
  200. package/server/record-lEYK__LD.js +3 -0
  201. package/server/recovery-trip-BT7nb9OV.js +98 -0
  202. package/server/{release-engine-YLTnEO_K.js → release-engine-CBLQXDlH.js} +5 -5
  203. package/server/{release-set-DwvT_Opu.js → release-set-BNiqi7hy.js} +3 -3
  204. package/server/{remote-B062S1Kc.js → remote-DW_TWQnr.js} +3 -3
  205. package/server/{remote-9u9WL0NJ.js → remote-DcO9An_f.js} +3 -3
  206. package/server/{remote-agents-BBTg-vLT.js → remote-agents-C4cyxHQS.js} +6 -6
  207. package/server/{remote-agents-B4eWgwNd.js → remote-agents-Cv-U-_V8.js} +1 -1
  208. package/server/{remote-completion-B0rmBnbL.js → remote-completion-PhXGGFQy.js} +13 -13
  209. package/server/resolver-C7dLn8OK.js +158 -0
  210. package/server/resume-BYZBIab-.js +3 -0
  211. package/server/{review-agent-tfR5RDzG.js → review-agent-Dn-yn7Zj.js} +23 -23
  212. package/server/{review-agent-Bf9XjLnl.js → review-agent-u5q3ip7H.js} +1 -1
  213. package/server/{review-artifacts-D0_IE6DQ.js → review-artifacts-D4T04aYI.js} +6 -6
  214. package/server/{review-context-CXO5ml5D.js → review-context-Rc0VDLG_.js} +8 -8
  215. package/server/{review-monitor-DfFUSx0J.js → review-monitor-BC--miCO.js} +2 -2
  216. package/server/{review-status-B0Axo-Ma.js → review-status-CG0iDuWa.js} +1 -1
  217. package/server/{review-status-BcfwcAcO.js → review-status-Dc1l4dVz.js} +18 -18
  218. package/server/{review-status-enrichment-Cp5kFTGl.js → review-status-enrichment-C1a1OG_1.js} +3 -3
  219. package/server/{review-status-sync-CEFty1pW.js → review-status-sync-CAr-hfnJ.js} +2 -2
  220. package/server/{review-status-sync-Bc0c_u12.js → review-status-sync-CfSixhhX.js} +1 -1
  221. package/server/{review-verdict-feedback-BOKRLLDf.js → review-verdict-feedback-CVDbIDBe.js} +7 -7
  222. package/server/{review-verdict-feedback-BnGtT0vN.js → review-verdict-feedback-D2Q960wX.js} +1 -1
  223. package/server/{rollup-BVqFuiS9.js → rollup-CakjztPl.js} +1 -1
  224. package/server/{rollup-C22QDVxh.js → rollup-DctoIu-A.js} +8 -8
  225. package/server/{scanner-BLCnuXqY.js → scanner-BTM1jc_u.js} +7 -7
  226. package/server/{sequence-io-BozlUb6f.js → sequence-io-pnoIDGv4.js} +4 -4
  227. package/server/{sequencer-agent-BEDEHfd2.js → sequencer-agent-9Soi-WL-.js} +10 -6
  228. package/server/server.js +1239 -1836
  229. package/server/{service-C8jKYZ0w.js → service-DfTVoqJg.js} +1668 -1408
  230. package/server/{session-fork-BDGksK4e.js → session-fork-C4jAFHj8.js} +2 -2
  231. package/server/session-history-DanhhiCw.js +168 -0
  232. package/server/{settings-CSLhh6qR.js → settings-Cuc12oP_.js} +2 -2
  233. package/server/settings-Cy7SCFO9.js +2 -0
  234. package/server/{settings-DrRQCren.js → settings-DfT3f86D.js} +3 -3
  235. package/server/{shadow-engineering-BMcBN-Of.js → shadow-engineering-bKuKTCn-.js} +3 -3
  236. package/server/{shadow-state-CHqWHD3T.js → shadow-state-CVHpRWlb.js} +1 -1
  237. package/server/{shadow-state-B4ayC7nx.js → shadow-state-DJz6_pb_.js} +2 -2
  238. package/server/{ship-log-CDVmOlZP.js → ship-log-CwqPFfqx.js} +1 -1
  239. package/server/{smart-compaction-V9DBrGcr.js → smart-compaction-B4KlpZGN.js} +1 -1
  240. package/server/{smart-compaction-C-F5sP9P.js → smart-compaction-CiWfGfRZ.js} +7 -7
  241. package/server/{spawn-planning-session-dSpOU0lP.js → spawn-planning-session-CU-DwyDl.js} +15 -15
  242. package/server/{spawn-planning-session-Bz4_JES2.js → spawn-planning-session-D5N3RuLG.js} +1 -1
  243. package/server/{specialist-completion-Coz3eTSr.js → specialist-completion-CJcv-NXH.js} +1 -1
  244. package/server/{specialist-context-fmb03vXQ.js → specialist-context-B2HlbNxS.js} +5 -5
  245. package/server/{specialist-handoff-logger-B9HK_lRu.js → specialist-handoff-logger-CQyF1ygu.js} +2 -2
  246. package/server/{specialist-logs-B24R2B9Y.js → specialist-logs-CdcUpfjj.js} +3 -3
  247. package/server/{specialists-CL7E8yUg.js → specialists-CFgw_0Q6.js} +1657 -113
  248. package/server/{specialists-BGNZ0_ZW.js → specialists-CwzFdapR.js} +20 -256
  249. package/server/{specialists-B6f5-5nG.js → specialists-D7AcFi1u.js} +1 -1
  250. package/server/{specialists-Chvvwf5z.js → specialists-k22_Btaq.js} +1 -1
  251. package/server/specs-RzcDgozr.js +3 -0
  252. package/server/{src-DGAEtABV.js → src-B4TTzNSr.js} +84 -2
  253. package/server/{src-BVxZuHMg.js → src-BvpMg4EB.js} +3 -3
  254. package/server/{src-D-VXCC9C.js → src-D4YUZrwR.js} +6 -6
  255. package/server/{stack-health-C-le5erA.js → stack-health-CSgcYcr8.js} +2 -2
  256. package/server/{stack-health-BKbTTOT2.js → stack-health-DVN7zRnL.js} +1 -1
  257. package/server/{state-home-CoyWsECg.js → state-home-CEvD_v5F.js} +6 -6
  258. package/server/{state-mapping-BvAgFK8n.js → state-mapping-C13UaCL7.js} +1 -1
  259. package/server/stuck-remediation-CxsyxwFO.js +1513 -0
  260. package/server/stuck-remediation-nTIvhGOR.js +2 -0
  261. package/server/{summary-fork-BF_0vxrq.js → summary-fork-CnRMPCYd.js} +2 -2
  262. package/server/{summary-fork-BlE30Q-I.js → summary-fork-gKSoFAnK.js} +8 -8
  263. package/server/{supervisor-BSeML_p0.js → supervisor-CZMs8s0M.js} +2 -2
  264. package/server/supervisor-CfX192ma.js +2 -0
  265. package/server/{swarm-readiness-CQ4sjrXc.js → swarm-readiness-h6-pwY8w.js} +3 -3
  266. package/server/{system-prerequisites-DnmLYOnU.js → system-prerequisites-DZZTi2G6.js} +1 -1
  267. package/server/{teardown-workspace-CpcjDrZ4.js → teardown-workspace-B4D-oCVg.js} +37 -68
  268. package/server/{test-agent-queue-Bq298zZl.js → test-agent-queue-CnuYku4B.js} +6 -6
  269. package/server/{test-verdict-CCDd25uN.js → test-verdict-CRsPpByy.js} +1 -1
  270. package/server/{test-verdict-Bm4uv_AA.js → test-verdict-CXMLATGc.js} +1 -1
  271. package/server/{tldr-daemon-Rn1Zue0P.js → tldr-daemon-CgZQ3jmZ.js} +1 -1
  272. package/server/{tldr-daemon-CaSUXd9r.js → tldr-daemon-CuA8hz21.js} +2 -2
  273. package/server/{tmux-CbcrkUx5.js → tmux-By8E_Yv_.js} +1 -1
  274. package/server/{tmux-BVc-NeKM.js → tmux-C3g9VFcg.js} +2 -2
  275. package/server/{token-D2OC_9ms.js → token-g_sJ19g3.js} +2 -2
  276. package/server/token-util-C9u4An3K.js +3 -0
  277. package/server/{token-util-CROoF5ic.js → token-util-DiwnnbJo.js} +1 -1
  278. package/server/{tracker-config-EsBoOWEy.js → tracker-config-BzfVj41Z.js} +1 -1
  279. package/server/{tracker-config-C1Y_2CIo.js → tracker-config-dQxC15vH.js} +2 -2
  280. package/server/{tracker-utils-lph9C3Pw.js → tracker-utils--z8FLSWn.js} +2 -2
  281. package/server/{tracker-utils-DSb9cfrF.js → tracker-utils-DkKyRT0H.js} +1 -1
  282. package/server/{traefik-connect-5EP1WS_Z.js → traefik-connect-CZYB3dlm.js} +1 -1
  283. package/server/{tunnel-BFBCeo97.js → tunnel-BpWZs0Jy.js} +3 -3
  284. package/server/{tunnel-DDe-ATFF.js → tunnel-CN2px87h.js} +1 -1
  285. package/server/{typed-errors-DSPn_xWP.js → typed-errors-CrN1AByg.js} +1 -1
  286. package/server/{typed-errors-BEJhbjJg.js → typed-errors-sLpGfegz.js} +1 -1
  287. package/server/{types-CE1m_daD.js → types-BLS_Zbmd.js} +1 -1
  288. package/server/{types-B5u3NxMl.js → types-tlXf80x3.js} +1 -1
  289. package/server/{uat-train-DtKHHy1U.js → uat-train-BRo6DM7p.js} +24 -24
  290. package/server/{uat-train-8T24rPzc.js → uat-train-utGVmqdm.js} +1 -1
  291. package/server/{validation-lyudzPvD.js → validation-CsPVsoA0.js} +4 -4
  292. package/server/{validation-COOXwNXU.js → validation-Dq_wwcw3.js} +1 -1
  293. package/server/{verification-runner-DO0nYTJx.js → verification-runner-CMT5WRMS.js} +12 -12
  294. package/server/{verification-runner-Dd1FX8Qk.js → verification-runner-D0Uh-9jc.js} +1 -1
  295. package/server/{vtt-parser-C57tEF7-.js → vtt-parser-C_XPlifj.js} +1 -1
  296. package/server/{work-agent-prompt-B2F3ZwKm.js → work-agent-prompt-ZTAb2Hyf.js} +12 -12
  297. package/server/workflows-BLwxUMP7.js +2 -0
  298. package/server/{workflows-Clz_AFwR.js → workflows-CXRwhw_o.js} +14 -14
  299. package/server/{workspace-D0rCFemz.js → workspace-9UEsKuiP.js} +1 -1
  300. package/server/{workspace-CY_2-Ddv.js → workspace-CNfuj1-5.js} +3 -3
  301. package/server/{workspace-config-DA8U97k9.js → workspace-config-ChWOECy0.js} +1 -1
  302. package/server/{workspace-manager-BIfpzqdU.js → workspace-manager-BO-6k3sP.js} +1 -1
  303. package/server/{workspace-manager-D6NgGkiF.js → workspace-manager-D8AByFIT.js} +13 -13
  304. package/server/{workspace-metadata-C8yn8kAH.js → workspace-metadata-CvC268MN.js} +2 -2
  305. package/server/{workspace-metadata-DfgR40YU.js → workspace-metadata-DZiJtnuF.js} +1 -1
  306. package/server/{workspaces-DOeHyKmA.js → workspaces-D-uIoqbg.js} +104 -122
  307. package/server/writer-BUweuRPx.js +3 -0
  308. package/server/writer-CrP2xuBn.js +251 -0
  309. package/sync-sources/hooks/ask-user-question-hook +7 -1
  310. package/sync-sources/hooks/record-cost-event.js +4 -3
  311. package/sync-sources/hooks/record-cost-event.js.map +1 -1
  312. package/server/agent-runtime-mirror-DrWxopNA.js +0 -37
  313. package/server/auto-commit-wZ9X7Isd.js +0 -3
  314. package/server/bd-mutex-BItGvLQ8.js +0 -35
  315. package/server/beads-restore-CMbDSB5R.js +0 -60
  316. package/server/cli-CqgiSAU8.js +0 -3
  317. package/server/deacon-swarm-B8pgK2a7.js +0 -2
  318. package/server/dist-BYSj075e.js +0 -3
  319. package/server/forge-CUCYK7h_.js +0 -2
  320. package/server/hume-x9voULey.js +0 -3
  321. package/server/inspect-agent-D8UBDgfR.js +0 -2
  322. package/server/merge-ops-B7m-hBEZ.js +0 -2
  323. package/server/projects-BqRMlDOv.js +0 -3
  324. package/server/providers-gZ0cUgQM.js +0 -3
  325. package/server/public/assets/chunk-BO2N2NFS-C-6y8VFI.js +0 -103
  326. package/server/public/assets/index-BDqWyuZQ.js +0 -796
  327. package/server/public/assets/index-CZiADHcL.css +0 -1
  328. package/server/public/assets/mermaid-GHXKKRXX-DRM2ANcR.js +0 -1
  329. package/server/rally-CRteqXe0.js +0 -3
  330. package/server/record-CJsjvRO4.js +0 -3
  331. package/server/resume-R7xkSmLW.js +0 -3
  332. package/server/settings-CSaXtkoA.js +0 -2
  333. package/server/specs-oaaYaA5c.js +0 -3
  334. package/server/supervisor-03Tj_Wra.js +0 -2
  335. package/server/token-util-xNaV-00f.js +0 -3
  336. package/server/workflows-B4fIN8VP.js +0 -2
@@ -0,0 +1,1513 @@
1
+ import { Br as encodeClaudeProjectDir, Fn as init_projects, Jr as init_paths, dr as FsError, nr as init_issue_id, qn as resolveProjectFromIssueSync, qr as getOverdeckHome, tr as extractPrefixSync, vr as TmuxError, xr as init_errors } from "./config-yaml-cNOZcEww.js";
2
+ import { D as listPaneValuesSync, P as sendKeys, R as sessionExistsSync, T as killSessionSync, i as capturePane, x as init_tmux } from "./tmux-C3g9VFcg.js";
3
+ import { n as CLAUDE_CODE_BEHAVIOR } from "./src-B4TTzNSr.js";
4
+ import { c as init_review_status, s as getReviewStatusSync } from "./review-status-Dc1l4dVz.js";
5
+ import { An as getAgentDir, B as createOhmypiRuntimeSync, E as resumeAgent, Hn as markAgentTroubled, Jn as saveAgentStateSync, Pn as getAgentStateSync, Q as listRunningAgentsSync, U as spawnAgent, V as init_ohmypi, _t as init_config, cn as determineModel, en as init_pi_fifo, fr as getAgentRuntimeState, hr as saveAgentRuntimeState, ht as DEFAULT_CLOISTER_CONFIG, j as messageAgent, pr as getAgentRuntimeStateSync, t as init_agents, yt as loadCloisterConfigSync } from "./agents-B9GwfCyp.js";
6
+ import { c as logDeaconEventSync, o as init_persistent_logger } from "./session-history-DanhhiCw.js";
7
+ import { t as init_behavior } from "./behavior-BTpYbAv4.js";
8
+ import { a as init_tracker_config, t as getGitHubConfig } from "./tracker-config-dQxC15vH.js";
9
+ import { a as init_launcher_generator } from "./state-home-CEvD_v5F.js";
10
+ import { i as createCodexRuntimeSync, l as init_codex } from "./codex-BbqIRZjd.js";
11
+ import { f as isFlywheelGloballyPaused, i as getFlywheelActiveRunId, s as init_control_settings } from "./control-settings-D4EFsRBd.js";
12
+ import { o as queryReadyBeadsByIssueLabels, r as init_beads_query, s as resolveBeadsQueryRoot } from "./beads-query-Dl4FhT8J.js";
13
+ import { a as init_jsonl_parser, i as getSessionFilesSync, r as getProjectDirsSync, s as parseClaudeSessionSync } from "./jsonl-parser-BUW5_sSK.js";
14
+ import { t as recordRecoveryFailure } from "./recovery-trip-BT7nb9OV.js";
15
+ import "node:path";
16
+ import { Effect } from "effect";
17
+ import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
18
+ import { join as join$1 } from "path";
19
+ import { homedir } from "os";
20
+ import "node:os";
21
+ import "node:fs";
22
+ import { readFile, readdir, stat as stat$1 } from "fs/promises";
23
+ import { exec } from "node:child_process";
24
+ import { promisify } from "node:util";
25
+ import { exec as exec$1 } from "child_process";
26
+ import { promisify as promisify$1 } from "util";
27
+ import "node:crypto";
28
+ //#region ../../lib/agent-input-detection.ts
29
+ init_paths();
30
+ init_issue_id();
31
+ init_projects();
32
+ init_behavior();
33
+ init_persistent_logger();
34
+ init_review_status();
35
+ init_codex();
36
+ init_launcher_generator();
37
+ init_beads_query();
38
+ init_agents();
39
+ init_tmux();
40
+ init_errors();
41
+ const ANSI_PATTERN = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
42
+ const MAX_PROMPT_CHARS = 2e3;
43
+ const PANE_DETECTION_CACHE_TTL_MS = 1e4;
44
+ const MAX_PANE_DETECTION_CACHE_ENTRIES = 256;
45
+ const MAX_CONCURRENT_PANE_DETECTIONS = 4;
46
+ const paneDetectionCache = /* @__PURE__ */ new Map();
47
+ const paneDetectionInFlight = /* @__PURE__ */ new Map();
48
+ const paneDetectionWaiters = [];
49
+ let activePaneDetections = 0;
50
+ function getPaneDetectionCacheKey(agentId, options) {
51
+ return `${agentId}:${options.isPlanning === true ? "planning" : "agent"}:${options.lines ?? 90}`;
52
+ }
53
+ function sweepPaneDetectionCache(now = Date.now()) {
54
+ for (const [key, entry] of paneDetectionCache) if (entry.expiresAt <= now) paneDetectionCache.delete(key);
55
+ while (paneDetectionCache.size > MAX_PANE_DETECTION_CACHE_ENTRIES) {
56
+ const oldestKey = paneDetectionCache.keys().next().value;
57
+ if (!oldestKey) break;
58
+ paneDetectionCache.delete(oldestKey);
59
+ }
60
+ }
61
+ async function withPaneDetectionSlot(fn) {
62
+ if (activePaneDetections >= MAX_CONCURRENT_PANE_DETECTIONS) await new Promise((resolve) => paneDetectionWaiters.push(resolve));
63
+ activePaneDetections += 1;
64
+ try {
65
+ return await fn();
66
+ } finally {
67
+ activePaneDetections = Math.max(0, activePaneDetections - 1);
68
+ paneDetectionWaiters.shift()?.();
69
+ }
70
+ }
71
+ function cleanPaneLine(line) {
72
+ return line.replace(ANSI_PATTERN, "").replace(/[\x00-\x1f\x7f]/g, "").replace(/\s+$/g, "");
73
+ }
74
+ function compactPrompt(prompt) {
75
+ const compact = prompt.split("\n").map((line) => line.trim()).filter(Boolean).join("\n").trim();
76
+ if (compact.length <= MAX_PROMPT_CHARS) return compact;
77
+ return `${compact.slice(0, MAX_PROMPT_CHARS - 1)}…`;
78
+ }
79
+ function normalizeAwaitingInputPrompt(prompt) {
80
+ return compactPrompt(prompt);
81
+ }
82
+ function snippetAround(lines, index, before = 8, after = 4) {
83
+ const start = Math.max(0, index - before);
84
+ const end = Math.min(lines.length, index + after + 1);
85
+ return compactPrompt(lines.slice(start, end).join("\n"));
86
+ }
87
+ function lastIndexMatching(lines, predicate) {
88
+ for (let i = lines.length - 1; i >= 0; i -= 1) if (predicate(lines[i], i)) return i;
89
+ return -1;
90
+ }
91
+ function isRecentPromptIndex(lines, index) {
92
+ if (index < 0) return false;
93
+ return lines.length - index <= 25;
94
+ }
95
+ function isCurrentPromptIndex(lines, index, maxTrailingLines = 0) {
96
+ if (index < 0) return false;
97
+ return lines.length - index <= maxTrailingLines + 1;
98
+ }
99
+ function findPermissionMenuEndIndex(lines, menuStartIndex) {
100
+ if (menuStartIndex < 0) return -1;
101
+ const end = Math.min(lines.length, menuStartIndex + 8);
102
+ for (let i = menuStartIndex; i < end; i += 1) if (/\s*3\.\s*No\b/i.test(lines[i])) return i;
103
+ return menuStartIndex;
104
+ }
105
+ function looksLikeClaudePermissionMenu(text) {
106
+ return /(?:^|\n)\s*❯?\s*1\.\s*Yes\b/i.test(text) && /(?:^|\n)\s*2\.\s*Yes,?\s*(?:and\s*)?(?:allow|don't ask|always)/i.test(text) && /(?:^|\n)\s*3\.\s*No\b/i.test(text);
107
+ }
108
+ function looksLikePermissionText(text) {
109
+ return /permission|allow(?:\s+this)?|tool use|bash command|mcp tool|do you want to proceed|do you want to continue/i.test(text);
110
+ }
111
+ function looksLikeGenericConfirmation(line) {
112
+ return /(?:\?|:)\s*(?:\[[Yy]\/[Nn]\]|\[[Nn]\/[Yy]\]|\([Yy]\/[Nn]\)|\([Nn]\/[Yy]\)|\[y\/N\]|\[Y\/n\])\s*$/i.test(line) || /\b(?:continue|proceed|confirm|approve|allow|run|execute|overwrite|delete|remove)\b.*(?:\[[Yy]\/[Nn]\]|\([Yy]\/[Nn]\)|\[y\/N\]|\[Y\/n\])/i.test(line);
113
+ }
114
+ function looksLikePiPermission(text) {
115
+ return /(?:permission|approval|approve|allow).{0,80}(?:required|request|prompt|action|command)/i.test(text) || /(?:allow|approve|run|execute)\s+(?:this\s+)?(?:command|tool|action)/i.test(text);
116
+ }
117
+ function looksLikePlanningDone(text) {
118
+ return /planning finalized\s*[—-]\s*click done/i.test(text) || /click Done in the dashboard/i.test(text) || /planning (?:is )?complete.{0,120}(?:click|press|select) Done/i.test(text);
119
+ }
120
+ /**
121
+ * PAN-1520 (covers #1197) — Claude Code session-resume dialog. Fires when an
122
+ * agent is resumed via `claude --resume <session>` and a prior session is
123
+ * still considered active or interrupted. The dialog blocks tool execution
124
+ * until acknowledged. Conservative patterns — we want false-negatives over
125
+ * false-positives, so we only match strings that clearly indicate a resume
126
+ * choice point.
127
+ */
128
+ function looksLikeSessionResumeDialog(text) {
129
+ return /this session (?:is|was)\s+(?:still\s+)?(?:active|interrupted|running)/i.test(text) || /resume (?:the\s+)?previous session/i.test(text) || /(?:continue|resume) (?:this\s+)?session\??.{0,40}(?:\[[Yy]\/[Nn]\]|\([Yy]\/[Nn]\)|press\s+enter)/i.test(text) || /press enter to (?:continue|resume)/i.test(text);
130
+ }
131
+ /**
132
+ * PAN-1834 — Codex/gpt-5.5 rate-limit / model-switch modal. The harness shows a
133
+ * choice between keeping the current model and switching to an alternative.
134
+ * To avoid matching prose that merely mentions rate limits, require BOTH option
135
+ * lines to be present near the bottom of the pane.
136
+ */
137
+ function looksLikeRateLimitModelSwitchModal(text) {
138
+ return /keep current model/i.test(text) && /switch to\s+\S+/i.test(text);
139
+ }
140
+ /**
141
+ * PAN-1690 — Codex TUI approval prompt header. Codex asks for approval with a
142
+ * distinctive "Would you like to …?" prompt box (command run, edits, network/
143
+ * host grants) followed by a numbered Yes/…/No menu. Unlike Claude's menu,
144
+ * Codex renders option descriptions and a footer hint *below* "3. No", so the
145
+ * trailing-line heuristics the Claude path relies on never fire — we key on the
146
+ * header instead. Verb list pulled from the codex binary; see PAN-1690.
147
+ */
148
+ function looksLikeCodexApprovalHeader(line) {
149
+ return /Would you like to (?:run the following command|grant these permissions?|make the following edits|allow|apply)\b/i.test(line);
150
+ }
151
+ function detectAwaitingInputFromPaneSync(pane, options = {}) {
152
+ const lines = pane.split("\n").map(cleanPaneLine).filter((line) => line.trim().length > 0);
153
+ if (lines.length === 0) return null;
154
+ const recentText = lines.slice(-45).join("\n");
155
+ if (looksLikeClaudePermissionMenu(recentText) && looksLikePermissionText(recentText)) {
156
+ const menuIndex = lastIndexMatching(lines, (line) => /❯?\s*1\.\s*Yes\b/i.test(line));
157
+ const menuEndIndex = findPermissionMenuEndIndex(lines, menuIndex);
158
+ if (isRecentPromptIndex(lines, menuIndex) && isCurrentPromptIndex(lines, menuEndIndex)) return {
159
+ reason: "tool_permission",
160
+ prompt: snippetAround(lines, menuIndex, 10, 3)
161
+ };
162
+ }
163
+ const codexHeaderIndex = lastIndexMatching(lines, looksLikeCodexApprovalHeader);
164
+ if (codexHeaderIndex >= 0 && isRecentPromptIndex(lines, codexHeaderIndex)) {
165
+ const optionIndex = lastIndexMatching(lines, (line) => /^[^\w]*1\.\s*Yes\b/i.test(line));
166
+ if (optionIndex > codexHeaderIndex && lines.length - optionIndex <= 12) return {
167
+ reason: "tool_permission",
168
+ prompt: snippetAround(lines, codexHeaderIndex, 1, 14)
169
+ };
170
+ }
171
+ const piIndex = lastIndexMatching(lines, (line) => looksLikePiPermission(line) || looksLikeGenericConfirmation(line));
172
+ if (isRecentPromptIndex(lines, piIndex) && isCurrentPromptIndex(lines, piIndex)) {
173
+ const snippet = snippetAround(lines, piIndex, 6, 2);
174
+ return {
175
+ reason: looksLikeGenericConfirmation(lines[piIndex]) ? "confirmation" : "tool_permission",
176
+ prompt: snippet
177
+ };
178
+ }
179
+ if (options.isPlanning && looksLikePlanningDone(recentText)) {
180
+ const doneIndex = lastIndexMatching(lines, (line) => /done|planning/i.test(line));
181
+ return {
182
+ reason: "planning_done",
183
+ prompt: snippetAround(lines, doneIndex >= 0 ? doneIndex : lines.length - 1, 8, 2)
184
+ };
185
+ }
186
+ if (looksLikeSessionResumeDialog(recentText)) {
187
+ const resumeIndex = lastIndexMatching(lines, (line) => looksLikeSessionResumeDialog(line));
188
+ return {
189
+ reason: "session_resume",
190
+ prompt: snippetAround(lines, resumeIndex >= 0 ? resumeIndex : lines.length - 1, 8, 2)
191
+ };
192
+ }
193
+ if (looksLikeRateLimitModelSwitchModal(recentText)) {
194
+ const rateLimitIndex = lastIndexMatching(lines, (line) => /keep current model|switch to\s+\S+/i.test(line));
195
+ if (isRecentPromptIndex(lines, rateLimitIndex)) return {
196
+ reason: "rate_limit",
197
+ prompt: snippetAround(lines, rateLimitIndex >= 0 ? rateLimitIndex : lines.length - 1, 8, 2)
198
+ };
199
+ }
200
+ return null;
201
+ }
202
+ async function detectAwaitingInputForAgentPromise(agentId, options = {}) {
203
+ const cacheEnabled = options.cache !== false;
204
+ const cacheKey = getPaneDetectionCacheKey(agentId, options);
205
+ const now = Date.now();
206
+ if (cacheEnabled) {
207
+ sweepPaneDetectionCache(now);
208
+ const cached = paneDetectionCache.get(cacheKey);
209
+ if (cached && cached.expiresAt > now) {
210
+ paneDetectionCache.delete(cacheKey);
211
+ paneDetectionCache.set(cacheKey, cached);
212
+ return cached.detection;
213
+ }
214
+ const inFlight = paneDetectionInFlight.get(cacheKey);
215
+ if (inFlight) return inFlight;
216
+ }
217
+ const detectionPromise = withPaneDetectionSlot(async () => {
218
+ const detection = detectAwaitingInputFromPaneSync(await Effect.runPromise(capturePane(agentId, options.lines ?? 90)), options);
219
+ if (cacheEnabled) {
220
+ paneDetectionCache.set(cacheKey, {
221
+ expiresAt: Date.now() + PANE_DETECTION_CACHE_TTL_MS,
222
+ detection
223
+ });
224
+ sweepPaneDetectionCache();
225
+ }
226
+ return detection;
227
+ });
228
+ if (!cacheEnabled) return detectionPromise;
229
+ paneDetectionInFlight.set(cacheKey, detectionPromise);
230
+ try {
231
+ return await detectionPromise;
232
+ } finally {
233
+ paneDetectionInFlight.delete(cacheKey);
234
+ }
235
+ }
236
+ /**
237
+ * Effect-native variant of detectAwaitingInputForAgent. Fails with TmuxError if
238
+ * the pane capture fails outside the in-cache fast path.
239
+ */
240
+ const detectAwaitingInputForAgent = (agentId, options = {}) => Effect.tryPromise({
241
+ try: () => detectAwaitingInputForAgentPromise(agentId, options),
242
+ catch: (cause) => new TmuxError({
243
+ command: "capture-pane",
244
+ message: `failed to detect awaiting input for ${agentId}`,
245
+ cause
246
+ })
247
+ });
248
+ /**
249
+ * PAN-1690 — parse a Codex approval prompt (as captured by the codex-aware
250
+ * branch of detectAwaitingInputFromPaneSync) into its header, detail, and
251
+ * numbered options, so the dashboard can render the menu and answer it without
252
+ * the terminal. Returns null when the text doesn't contain a usable menu
253
+ * (fewer than two numbered options). Option lines tolerate a leading selection
254
+ * cursor (❯ › > etc.); the footer hint and other non-numbered lines are
255
+ * naturally excluded.
256
+ */
257
+ function parseCodexApprovalPrompt(text) {
258
+ const lines = text.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
259
+ if (lines.length === 0) return null;
260
+ const headerIndex = lines.findIndex((l) => looksLikeCodexApprovalHeader(l));
261
+ if (headerIndex < 0) return null;
262
+ const optionRe = /^[^\w]*(\d+)\.\s*(.+?)\s*$/;
263
+ const options = [];
264
+ const detailLines = [];
265
+ let firstOptionSeen = false;
266
+ for (let i = headerIndex + 1; i < lines.length; i += 1) {
267
+ const m = optionRe.exec(lines[i]);
268
+ if (m) {
269
+ firstOptionSeen = true;
270
+ options.push({
271
+ number: Number(m[1]),
272
+ label: m[2].trim()
273
+ });
274
+ } else if (!firstOptionSeen) detailLines.push(lines[i]);
275
+ }
276
+ if (options.length < 2) return null;
277
+ return {
278
+ header: lines[headerIndex],
279
+ detail: detailLines.join("\n"),
280
+ options
281
+ };
282
+ }
283
+ //#endregion
284
+ //#region ../../lib/agent-enrichment.ts
285
+ /**
286
+ * Agent enrichment utilities (PAN-440 / PAN-1048)
287
+ *
288
+ * Shared functions for computing enrichment fields:
289
+ * role, hasPendingQuestion, pendingQuestionCount, resolution, resolutionCount
290
+ *
291
+ * Used by both the legacy REST /api/agents endpoint and the new
292
+ * AgentEnrichmentService background poller.
293
+ *
294
+ * PAN-1048: replaced the legacy `agentPhase` string with the role primitive —
295
+ * the dashboard derives label/status from `role` + lifecycle state.
296
+ */
297
+ init_errors();
298
+ init_tracker_config();
299
+ const execAsync$1 = promisify$1(exec$1);
300
+ function appendPaneDetectionKind(detection, kinds) {
301
+ if (detection?.reason === "session_resume" && !kinds.includes("sessionResume")) kinds.push("sessionResume");
302
+ if (detection?.reason === "rate_limit" && !kinds.includes("rateLimit")) kinds.push("rateLimit");
303
+ }
304
+ function isOwnActiveSpecialist(role) {
305
+ return role === "review" || role === "test" || role === "ship";
306
+ }
307
+ function getClaudeProjectDir(workspacePath) {
308
+ return join$1(homedir(), ".claude", "projects", encodeClaudeProjectDir(workspacePath));
309
+ }
310
+ async function getActiveSessionPath(projectDir) {
311
+ if (!existsSync(projectDir)) return null;
312
+ try {
313
+ const jsonlFiles = (await readdir(projectDir)).filter((f) => f.endsWith(".jsonl"));
314
+ if (jsonlFiles.length === 0) return null;
315
+ const withMtime = (await Promise.all(jsonlFiles.map(async (f) => {
316
+ try {
317
+ return {
318
+ name: f,
319
+ path: join$1(projectDir, f),
320
+ mtime: (await stat$1(join$1(projectDir, f))).mtime.getTime()
321
+ };
322
+ } catch {
323
+ return null;
324
+ }
325
+ }))).filter((x) => x !== null);
326
+ if (withMtime.length === 0) return null;
327
+ withMtime.sort((a, b) => b.mtime - a.mtime);
328
+ return withMtime[0].path;
329
+ } catch {
330
+ return null;
331
+ }
332
+ }
333
+ function getProjectPathByPrefix(issuePrefix) {
334
+ const resolved = resolveProjectFromIssueSync(`${issuePrefix}-1`);
335
+ if (resolved) return resolved.projectPath;
336
+ const config = getGitHubConfig();
337
+ if (config) {
338
+ for (const { owner, repo, prefix } of config.repos) if ((prefix || repo.toUpperCase().replace(/-CLI$/, "").replace(/-/g, "")).toUpperCase() === issuePrefix.toUpperCase()) {
339
+ const possiblePaths = [
340
+ join$1(homedir(), "Projects", repo),
341
+ join$1(homedir(), "Projects", repo.replace(/-cli$/, "")),
342
+ join$1(homedir(), "Projects", owner, repo)
343
+ ];
344
+ for (const path of possiblePaths) if (existsSync(path)) return path;
345
+ }
346
+ }
347
+ return join$1(homedir(), "Projects");
348
+ }
349
+ async function getAgentWorkspacePromise(agentId) {
350
+ const workspace = getAgentStateSync(agentId)?.workspace;
351
+ if (workspace) return workspace;
352
+ try {
353
+ const { stdout: paneCwd } = await execAsync$1(`tmux display-message -t ${agentId} -p '#{pane_current_path}' 2>/dev/null`, { encoding: "utf-8" });
354
+ const trimmed = paneCwd.trim();
355
+ if (trimmed && existsSync(trimmed)) return trimmed;
356
+ } catch {}
357
+ const issueId = agentId.replace(/^(agent-|planning-)/, "").toUpperCase();
358
+ const prefix = extractPrefixSync(issueId);
359
+ if (!prefix) return null;
360
+ try {
361
+ const projectPath = getProjectPathByPrefix(prefix);
362
+ const workspacePath = join$1(projectPath, "workspaces", `feature-${issueId.toLowerCase()}`);
363
+ if (existsSync(workspacePath)) return workspacePath;
364
+ return projectPath;
365
+ } catch {
366
+ return null;
367
+ }
368
+ }
369
+ async function getAgentJsonlPathPromise(agentId) {
370
+ const workspace = await Effect.runPromise(getAgentWorkspace(agentId));
371
+ if (!workspace) return null;
372
+ return await getActiveSessionPath(getClaudeProjectDir(workspace));
373
+ }
374
+ /**
375
+ * Count outstanding AskUserQuestions across ALL of an agent's workspace JSONL
376
+ * session files — not just the newest one. Claude Code rotates session files,
377
+ * so an open AskUserQuestion can sit in a file that is not the most-recently-
378
+ * modified. The complete-planning guard MUST be robust to that: scanning only
379
+ * the active file let TIN-1 complete planning while the operator's question was
380
+ * still open. Returns 0 only when no file has an unanswered AUQ.
381
+ */
382
+ async function countPendingAskUserQuestionsForAgentPromise(agentId) {
383
+ const workspace = await Effect.runPromise(getAgentWorkspace(agentId));
384
+ if (!workspace) return 0;
385
+ const projectDir = getClaudeProjectDir(workspace);
386
+ if (!existsSync(projectDir)) return 0;
387
+ let files;
388
+ try {
389
+ files = (await readdir(projectDir)).filter((f) => f.endsWith(".jsonl"));
390
+ } catch {
391
+ return 0;
392
+ }
393
+ let total = 0;
394
+ for (const f of files) try {
395
+ const scan = await scanPendingInputsPromise(join$1(projectDir, f));
396
+ total += scan.askUserQuestions.length;
397
+ } catch {}
398
+ return total;
399
+ }
400
+ /** Effect-native: count pending AskUserQuestions across all of an agent's JSONL files. */
401
+ const countPendingAskUserQuestionsForAgent = (agentId) => Effect.promise(() => countPendingAskUserQuestionsForAgentPromise(agentId));
402
+ /**
403
+ * Read the last `maxBytes` from a file. Efficient for large JSONL files where
404
+ * only recent entries (at the end) are relevant.
405
+ */
406
+ async function readFileTail(filePath, maxBytes) {
407
+ try {
408
+ const fileStat = await stat$1(filePath);
409
+ const start = Math.max(0, fileStat.size - maxBytes);
410
+ if (start === 0) return readFile(filePath, "utf-8");
411
+ const { createReadStream } = await import("node:fs");
412
+ return new Promise((resolve, reject) => {
413
+ const stream = createReadStream(filePath, {
414
+ start,
415
+ encoding: "utf-8"
416
+ });
417
+ let data = "";
418
+ stream.on("data", (chunk) => {
419
+ data += chunk;
420
+ });
421
+ stream.on("end", () => resolve(data));
422
+ stream.on("error", reject);
423
+ });
424
+ } catch {
425
+ return "";
426
+ }
427
+ }
428
+ const ASK_USER_QUESTION_HOOK_DENY_MARKER = "PAN-1520";
429
+ const ASK_USER_QUESTION_HOOK_DENY_PHRASE = "surfaced to the operator in the Overdeck dashboard";
430
+ function isHookDenyText(text) {
431
+ return text.includes(ASK_USER_QUESTION_HOOK_DENY_MARKER) || text.includes(ASK_USER_QUESTION_HOOK_DENY_PHRASE);
432
+ }
433
+ function isAskUserQuestionHookDenyToolResult(item) {
434
+ if (item.is_error !== true) return false;
435
+ const content = item.content;
436
+ if (typeof content === "string") return isHookDenyText(content);
437
+ if (Array.isArray(content)) return content.some((part) => {
438
+ if (typeof part === "string") return isHookDenyText(part);
439
+ if (part && typeof part === "object" && "text" in part) {
440
+ const text = part.text;
441
+ return typeof text === "string" && isHookDenyText(text);
442
+ }
443
+ return false;
444
+ });
445
+ return false;
446
+ }
447
+ async function getPendingQuestionsPromise(jsonlPath) {
448
+ return (await scanPendingInputsPromise(jsonlPath)).askUserQuestions;
449
+ }
450
+ /**
451
+ * PAN-1520 — does this user-message entry carry operator text (i.e. an answer)
452
+ * rather than just being a wrapper for a tool_result? When the hook denies an
453
+ * AskUserQuestion the agent restates the question as plain text; the operator's
454
+ * next user message — whether typed in the terminal, sent from the conversation
455
+ * composer, or delivered by the answer-question route — is the actual answer.
456
+ * The presence of that user-text turn after the deny is what resolves the AUQ.
457
+ */
458
+ function isUserTextEntry(entry) {
459
+ if (!entry || typeof entry !== "object") return false;
460
+ const e = entry;
461
+ if (e.type !== "user") return false;
462
+ const content = e.message?.content;
463
+ if (typeof content === "string") return content.trim().length > 0;
464
+ if (Array.isArray(content)) return content.some((item) => {
465
+ if (!item || typeof item !== "object") return false;
466
+ return item.type !== "tool_result";
467
+ });
468
+ return false;
469
+ }
470
+ async function scanPendingInputsPromise(jsonlPath) {
471
+ if (!existsSync(jsonlPath)) return {
472
+ askUserQuestions: [],
473
+ enterPlanModeOpen: false,
474
+ exitPlanModePending: false
475
+ };
476
+ try {
477
+ const lines = (await readFileTail(jsonlPath, 512e3)).split("\n").filter((line) => line.trim());
478
+ const askToolCalls = /* @__PURE__ */ new Map();
479
+ const askAnswered = /* @__PURE__ */ new Set();
480
+ const askDeniedAwaitingUser = /* @__PURE__ */ new Set();
481
+ const exitPlanModeIds = /* @__PURE__ */ new Set();
482
+ const exitPlanModeCalls = /* @__PURE__ */ new Map();
483
+ const exitPlanModeAnswered = /* @__PURE__ */ new Set();
484
+ const enterPlanModeIds = /* @__PURE__ */ new Set();
485
+ const exitPlanModeFiredAfterEnter = /* @__PURE__ */ new Set();
486
+ for (const line of lines) try {
487
+ const entry = JSON.parse(line);
488
+ if (isUserTextEntry(entry)) {
489
+ for (const id of askDeniedAwaitingUser) askAnswered.add(id);
490
+ askDeniedAwaitingUser.clear();
491
+ }
492
+ const messageContent = entry.message?.content;
493
+ if (!Array.isArray(messageContent)) continue;
494
+ for (const item of messageContent) {
495
+ if (item.type === "tool_use") {
496
+ if (item.name === "AskUserQuestion" && typeof item.id === "string") askToolCalls.set(item.id, {
497
+ toolId: item.id,
498
+ timestamp: entry.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
499
+ questions: item.input?.questions || []
500
+ });
501
+ else if (item.name === "ExitPlanMode" && typeof item.id === "string") {
502
+ exitPlanModeIds.add(item.id);
503
+ exitPlanModeFiredAfterEnter.add(item.id);
504
+ if (typeof item.input?.plan === "string" && item.input.plan.trim()) exitPlanModeCalls.set(item.id, {
505
+ plan: item.input.plan,
506
+ timestamp: entry.timestamp || (/* @__PURE__ */ new Date()).toISOString()
507
+ });
508
+ } else if (item.name === "EnterPlanMode" && typeof item.id === "string") enterPlanModeIds.add(item.id);
509
+ }
510
+ if (item.type === "tool_result" && typeof item.tool_use_id === "string") {
511
+ if (askToolCalls.has(item.tool_use_id)) if (isAskUserQuestionHookDenyToolResult(item)) askDeniedAwaitingUser.add(item.tool_use_id);
512
+ else {
513
+ askAnswered.add(item.tool_use_id);
514
+ askDeniedAwaitingUser.delete(item.tool_use_id);
515
+ }
516
+ if (exitPlanModeIds.has(item.tool_use_id)) exitPlanModeAnswered.add(item.tool_use_id);
517
+ }
518
+ }
519
+ } catch {}
520
+ const askUserQuestions = Array.from(askToolCalls.entries()).filter(([id]) => !askAnswered.has(id)).map(([, question]) => question);
521
+ const pendingExitPlanId = Array.from(exitPlanModeIds).find((id) => !exitPlanModeAnswered.has(id));
522
+ const exitPlanModePending = pendingExitPlanId !== void 0;
523
+ const pendingCall = pendingExitPlanId ? exitPlanModeCalls.get(pendingExitPlanId) : void 0;
524
+ const pendingProposedPlan = pendingExitPlanId && pendingCall ? {
525
+ toolUseId: pendingExitPlanId,
526
+ askedAt: pendingCall.timestamp,
527
+ plan: pendingCall.plan
528
+ } : void 0;
529
+ return {
530
+ askUserQuestions,
531
+ enterPlanModeOpen: enterPlanModeIds.size > 0 && exitPlanModeFiredAfterEnter.size === 0,
532
+ exitPlanModePending,
533
+ ...pendingProposedPlan ? { pendingProposedPlan } : {}
534
+ };
535
+ } catch {
536
+ return {
537
+ askUserQuestions: [],
538
+ enterPlanModeOpen: false,
539
+ exitPlanModePending: false
540
+ };
541
+ }
542
+ }
543
+ async function getAgentPendingQuestionsPromise(agentId) {
544
+ const jsonlPath = await Effect.runPromise(getAgentJsonlPath(agentId));
545
+ if (!jsonlPath) return [];
546
+ return [...await Effect.runPromise(getPendingQuestions(jsonlPath))];
547
+ }
548
+ async function getAgentJsonlMtimePromise(agentId) {
549
+ const jsonlPath = await Effect.runPromise(getAgentJsonlPath(agentId));
550
+ if (!jsonlPath || !existsSync(jsonlPath)) return null;
551
+ try {
552
+ return (await stat$1(jsonlPath)).mtime.getTime();
553
+ } catch {
554
+ return null;
555
+ }
556
+ }
557
+ async function computeAgentEnrichmentPromise(agentId, startedAt, hasActiveSpecialist, skipJsonlScan) {
558
+ const isPlanning = agentId.startsWith("planning-");
559
+ const stateRole = getAgentStateSync(agentId)?.role;
560
+ const role = stateRole === "plan" || stateRole === "work" || stateRole === "review" || stateRole === "test" || stateRole === "ship" || stateRole === "flywheel" ? stateRole : isPlanning ? "plan" : void 0;
561
+ const runtimeState = await Effect.runPromise(getAgentRuntimeState(agentId));
562
+ let pendingQuestions = [];
563
+ let enterPlanModeOpen = false;
564
+ let exitPlanModePending = false;
565
+ let scannedProposedPlan;
566
+ if (!skipJsonlScan) {
567
+ const jsonlPath = await Effect.runPromise(getAgentJsonlPath(agentId));
568
+ if (jsonlPath) {
569
+ const scan = await scanPendingInputsPromise(jsonlPath);
570
+ pendingQuestions = [...scan.askUserQuestions];
571
+ enterPlanModeOpen = scan.enterPlanModeOpen;
572
+ exitPlanModePending = scan.exitPlanModePending;
573
+ scannedProposedPlan = scan.pendingProposedPlan;
574
+ }
575
+ if (pendingQuestions.length > 0 && startedAt) {
576
+ const agentStartTime = new Date(startedAt).getTime();
577
+ pendingQuestions = pendingQuestions.filter((q) => {
578
+ const qTime = new Date(q.timestamp).getTime();
579
+ return !isNaN(qTime) && qTime >= agentStartTime;
580
+ });
581
+ }
582
+ }
583
+ const questionDetection = pendingQuestions.length > 0 ? {
584
+ reason: "user_question",
585
+ prompt: normalizeAwaitingInputPrompt(pendingQuestions[0]?.questions.map((q) => q.question).filter(Boolean).join("\n") || "Agent is waiting for a user answer")
586
+ } : null;
587
+ const runtimeDetection = runtimeState?.state === "waiting-on-human" ? {
588
+ reason: runtimeState.waitingReason || "other",
589
+ prompt: normalizeAwaitingInputPrompt(runtimeState.waitingNotification || "Agent is waiting for human input")
590
+ } : null;
591
+ const paneDetection = !questionDetection && !runtimeDetection ? await Effect.runPromise(detectAwaitingInputForAgent(agentId, { isPlanning })) : null;
592
+ const fallbackDetection = runtimeState?.resolution === "needs_input" ? {
593
+ reason: "other",
594
+ prompt: normalizeAwaitingInputPrompt("Agent stopped because it needs human input or hit a blocker")
595
+ } : null;
596
+ const detection = questionDetection ?? runtimeDetection ?? paneDetection ?? fallbackDetection;
597
+ const shouldSuppressPendingInput = hasActiveSpecialist === true && !isOwnActiveSpecialist(role);
598
+ const hasPendingQuestion = !shouldSuppressPendingInput && detection !== null;
599
+ const pendingInputKinds = [];
600
+ let pendingAskUserQuestion;
601
+ if (!shouldSuppressPendingInput) {
602
+ if (pendingQuestions.length > 0) {
603
+ pendingInputKinds.push("askUserQuestion");
604
+ const first = pendingQuestions[0];
605
+ pendingAskUserQuestion = {
606
+ toolUseId: first.toolId,
607
+ askedAt: first.timestamp,
608
+ questions: first.questions.map((q) => ({
609
+ question: q.question,
610
+ header: q.header,
611
+ multiSelect: q.multiSelect,
612
+ options: q.options.map((o) => ({
613
+ label: o.label,
614
+ description: o.description
615
+ }))
616
+ }))
617
+ };
618
+ }
619
+ if (exitPlanModePending) pendingInputKinds.push("exitPlanMode");
620
+ if (enterPlanModeOpen && !exitPlanModePending) pendingInputKinds.push("enterPlanMode");
621
+ appendPaneDetectionKind(detection, pendingInputKinds);
622
+ }
623
+ const pendingProposedPlan = !shouldSuppressPendingInput && exitPlanModePending ? scannedProposedPlan : void 0;
624
+ return {
625
+ role,
626
+ hasPendingQuestion,
627
+ pendingQuestionCount: pendingQuestions.length,
628
+ pendingQuestionPrompt: detection?.prompt,
629
+ pendingQuestionReason: detection?.reason,
630
+ pendingInputCount: pendingInputKinds.length,
631
+ pendingInputKinds,
632
+ pendingAskUserQuestion,
633
+ pendingProposedPlan,
634
+ resolution: runtimeState?.resolution || "working",
635
+ resolutionCount: runtimeState?.resolutionCount || 0
636
+ };
637
+ }
638
+ /**
639
+ * Effect-native variant of computeAgentEnrichment. Fails with FsError if any
640
+ * underlying filesystem read fails outside the swallowed branches.
641
+ */
642
+ const computeAgentEnrichment = (agentId, startedAt, hasActiveSpecialist, skipJsonlScan) => Effect.tryPromise({
643
+ try: () => computeAgentEnrichmentPromise(agentId, startedAt, hasActiveSpecialist, skipJsonlScan),
644
+ catch: (cause) => new FsError({
645
+ path: getAgentDir(agentId),
646
+ operation: "computeAgentEnrichment",
647
+ cause
648
+ })
649
+ });
650
+ /** Effect-native: resolve the workspace path for an agent (null on failure). */
651
+ const getAgentWorkspace = (agentId) => Effect.promise(() => getAgentWorkspacePromise(agentId));
652
+ /** Effect-native: resolve the active JSONL session path for an agent (null on failure). */
653
+ const getAgentJsonlPath = (agentId) => Effect.promise(() => getAgentJsonlPathPromise(agentId));
654
+ /** Effect-native: get the mtime of the agent's active JSONL session file. */
655
+ const getAgentJsonlMtime = (agentId) => Effect.promise(() => getAgentJsonlMtimePromise(agentId));
656
+ /** Effect-native: parse pending questions from a JSONL file. */
657
+ const getPendingQuestions = (jsonlPath) => Effect.promise(() => getPendingQuestionsPromise(jsonlPath));
658
+ /** Effect-native: get pending questions for an agent by id. */
659
+ const getAgentPendingQuestions = (agentId) => Effect.promise(() => getAgentPendingQuestionsPromise(agentId));
660
+ //#endregion
661
+ //#region ../../lib/runtimes/claude-code.ts
662
+ init_config();
663
+ /**
664
+ * Claude Code Runtime Implementation
665
+ *
666
+ * Implements AgentRuntime for Claude Code CLI.
667
+ *
668
+ * Session storage: ~/.claude/projects/<workspace-hash>/<session-id>.jsonl
669
+ * Session index: ~/.claude/projects/<workspace-hash>/sessions-index.json
670
+ */
671
+ init_agents();
672
+ init_tmux();
673
+ init_jsonl_parser();
674
+ init_errors();
675
+ const CLAUDE_PROJECTS_DIR = join$1(homedir(), ".claude", "projects");
676
+ /**
677
+ * Claude Code Runtime implementation
678
+ */
679
+ var ClaudeCodeRuntimeSync = class {
680
+ name = "claude-code";
681
+ getHarnessBehavior() {
682
+ return CLAUDE_CODE_BEHAVIOR;
683
+ }
684
+ /**
685
+ * Get the project directory for a workspace
686
+ *
687
+ * Claude Code hashes the workspace path to create project directories.
688
+ * We need to find the project directory that contains sessions for this workspace.
689
+ */
690
+ getProjectDirForWorkspace(workspace) {
691
+ if (!existsSync(CLAUDE_PROJECTS_DIR)) return null;
692
+ const projectDirs = getProjectDirsSync();
693
+ for (const projectDir of projectDirs) {
694
+ const indexPath = join$1(projectDir, "sessions-index.json");
695
+ if (existsSync(indexPath)) try {
696
+ if (readFileSync(indexPath, "utf-8").includes(workspace)) return projectDir;
697
+ } catch {}
698
+ }
699
+ return null;
700
+ }
701
+ /**
702
+ * Get the active session ID for an agent from the sessions index
703
+ */
704
+ getActiveSessionId(projectDir) {
705
+ const indexPath = join$1(projectDir, "sessions-index.json");
706
+ if (!existsSync(indexPath)) return null;
707
+ try {
708
+ const indexContent = readFileSync(indexPath, "utf-8");
709
+ const index = JSON.parse(indexContent);
710
+ if (index.sessions && Array.isArray(index.sessions)) {
711
+ const sessions = index.sessions;
712
+ if (sessions.length === 0) return null;
713
+ return sessions.sort((a, b) => {
714
+ return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
715
+ })[0].sessionId;
716
+ }
717
+ } catch {}
718
+ return null;
719
+ }
720
+ /**
721
+ * Get the most recent JSONL file for a project
722
+ */
723
+ getMostRecentJSONL(projectDir) {
724
+ const files = getSessionFilesSync(projectDir);
725
+ return files.length > 0 ? files[0] : null;
726
+ }
727
+ /**
728
+ * Get the session path for an agent
729
+ */
730
+ getSessionPath(agentId) {
731
+ const state = getAgentStateSync(agentId);
732
+ if (!state) return null;
733
+ const projectDir = this.getProjectDirForWorkspace(state.workspace);
734
+ if (!projectDir) return null;
735
+ const sessionId = this.getActiveSessionId(projectDir);
736
+ if (sessionId) {
737
+ const sessionPath = join$1(projectDir, `${sessionId}.jsonl`);
738
+ if (existsSync(sessionPath)) return sessionPath;
739
+ }
740
+ return this.getMostRecentJSONL(projectDir);
741
+ }
742
+ /**
743
+ * Get last activity timestamp for an agent
744
+ *
745
+ * Uses passive detection via JSONL file modification time.
746
+ */
747
+ getLastActivity(agentId) {
748
+ const sessionPath = this.getSessionPath(agentId);
749
+ if (!sessionPath || !existsSync(sessionPath)) return null;
750
+ try {
751
+ return statSync(sessionPath).mtime;
752
+ } catch {
753
+ return null;
754
+ }
755
+ }
756
+ /**
757
+ * Read active heartbeat file if it exists
758
+ */
759
+ getActiveHeartbeat(agentId) {
760
+ const heartbeatPath = join$1(homedir(), ".overdeck", "heartbeats", `${agentId}.json`);
761
+ if (!existsSync(heartbeatPath)) return null;
762
+ try {
763
+ const content = readFileSync(heartbeatPath, "utf-8");
764
+ const data = JSON.parse(content);
765
+ const timestamp = new Date(data.timestamp);
766
+ if ((/* @__PURE__ */ new Date()).getTime() - timestamp.getTime() > 300 * 1e3) return null;
767
+ return {
768
+ timestamp,
769
+ agentId: data.agent_id || agentId,
770
+ source: "active-heartbeat",
771
+ confidence: "high",
772
+ toolName: data.tool_name,
773
+ lastAction: data.last_action,
774
+ currentTask: data.current_task,
775
+ gitBranch: data.git_branch,
776
+ workspace: data.workspace,
777
+ pid: data.pid,
778
+ sessionId: data.session_id
779
+ };
780
+ } catch {
781
+ return null;
782
+ }
783
+ }
784
+ /**
785
+ * Get passive heartbeat from file timestamps
786
+ */
787
+ getPassiveHeartbeat(agentId) {
788
+ const lastActivity = this.getLastActivity(agentId);
789
+ if (!lastActivity) return null;
790
+ return {
791
+ timestamp: lastActivity,
792
+ agentId,
793
+ source: "jsonl",
794
+ confidence: "medium"
795
+ };
796
+ }
797
+ /**
798
+ * Get heartbeat for an agent
799
+ *
800
+ * Tries active heartbeat first (if hooks configured), falls back to passive.
801
+ */
802
+ getHeartbeat(agentId) {
803
+ const activeHeartbeat = this.getActiveHeartbeat(agentId);
804
+ if (activeHeartbeat) return activeHeartbeat;
805
+ return this.getPassiveHeartbeat(agentId);
806
+ }
807
+ /**
808
+ * Get token usage for an agent's current session
809
+ */
810
+ getTokenUsage(agentId) {
811
+ const sessionPath = this.getSessionPath(agentId);
812
+ if (!sessionPath) return null;
813
+ const sessionUsage = parseClaudeSessionSync(sessionPath);
814
+ if (!sessionUsage) return null;
815
+ return sessionUsage.usage;
816
+ }
817
+ /**
818
+ * Get cost breakdown for an agent's current session
819
+ */
820
+ getSessionCost(agentId) {
821
+ const sessionPath = this.getSessionPath(agentId);
822
+ if (!sessionPath) return null;
823
+ const sessionUsage = parseClaudeSessionSync(sessionPath);
824
+ if (!sessionUsage) return null;
825
+ const inputPrice = 3 / 1e6;
826
+ const outputPrice = 15 / 1e6;
827
+ const cacheReadPrice = .3 / 1e6;
828
+ const cacheWritePrice = 3.75 / 1e6;
829
+ const usage = sessionUsage.usage;
830
+ const inputCost = usage.inputTokens * inputPrice;
831
+ const outputCost = usage.outputTokens * outputPrice;
832
+ const cacheReadCost = (usage.cacheReadTokens || 0) * cacheReadPrice;
833
+ const cacheWriteCost = (usage.cacheWriteTokens || 0) * cacheWritePrice;
834
+ return {
835
+ inputCost,
836
+ outputCost,
837
+ cacheReadCost,
838
+ cacheWriteCost,
839
+ totalCost: inputCost + outputCost + cacheReadCost + cacheWriteCost,
840
+ currency: "USD"
841
+ };
842
+ }
843
+ /**
844
+ * Send a message to a running agent
845
+ */
846
+ async sendMessage(agentId, message) {
847
+ if (!sessionExistsSync(agentId)) throw new Error(`Agent ${agentId} is not running`);
848
+ await Effect.runPromise(sendKeys(agentId, message));
849
+ const mailDir = join$1(getAgentDir(agentId), "mail");
850
+ mkdirSync(mailDir, { recursive: true });
851
+ writeFileSync(join$1(mailDir, `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`), `# Message\n\n${message}\n`);
852
+ }
853
+ /**
854
+ * Kill an agent
855
+ */
856
+ killAgent(agentId) {
857
+ if (!sessionExistsSync(agentId)) throw new Error(`Agent ${agentId} is not running`);
858
+ killSessionSync(agentId);
859
+ saveAgentRuntimeState(agentId, {
860
+ state: "idle",
861
+ lastActivity: (/* @__PURE__ */ new Date()).toISOString()
862
+ });
863
+ const state = getAgentStateSync(agentId);
864
+ if (state) {
865
+ state.status = "stopped";
866
+ saveAgentStateSync(state);
867
+ }
868
+ }
869
+ /**
870
+ * Spawn a new agent
871
+ */
872
+ async spawnAgent(config) {
873
+ const state = await spawnAgent({
874
+ issueId: config.agentId.replace(/^agent-/, ""),
875
+ workspace: config.workspace,
876
+ harness: "claude-code",
877
+ model: determineModel({
878
+ model: config.model,
879
+ role: "work",
880
+ spawnKey: `work:${config.agentId.replace(/^agent-/, "")}`
881
+ }),
882
+ role: "work",
883
+ prompt: config.prompt
884
+ });
885
+ const projectDir = this.getProjectDirForWorkspace(config.workspace);
886
+ const sessionId = projectDir ? this.getActiveSessionId(projectDir) : void 0;
887
+ return {
888
+ id: state.id,
889
+ sessionId: sessionId || "unknown",
890
+ runtime: "claude-code",
891
+ model: state.model,
892
+ workspace: state.workspace,
893
+ startedAt: new Date(state.startedAt)
894
+ };
895
+ }
896
+ /**
897
+ * List all sessions for this runtime
898
+ */
899
+ listSessions(workspace) {
900
+ const sessions = [];
901
+ if (workspace) {
902
+ const projectDir = this.getProjectDirForWorkspace(workspace);
903
+ if (projectDir) {
904
+ const files = getSessionFilesSync(projectDir);
905
+ for (const file of files) {
906
+ const session = this.parseSessionFile(file, workspace);
907
+ if (session) sessions.push(session);
908
+ }
909
+ }
910
+ } else {
911
+ const projectDirs = getProjectDirsSync();
912
+ for (const projectDir of projectDirs) {
913
+ const files = getSessionFilesSync(projectDir);
914
+ for (const file of files) {
915
+ const session = this.parseSessionFile(file);
916
+ if (session) sessions.push(session);
917
+ }
918
+ }
919
+ }
920
+ return sessions;
921
+ }
922
+ /**
923
+ * Parse a session file into a Session object
924
+ */
925
+ parseSessionFile(file, workspace) {
926
+ const sessionUsage = parseClaudeSessionSync(file);
927
+ if (!sessionUsage) return null;
928
+ const stat = statSync(file);
929
+ return {
930
+ id: sessionUsage.sessionId,
931
+ agentId: "unknown",
932
+ workspace: workspace || "unknown",
933
+ model: sessionUsage.model,
934
+ startedAt: new Date(sessionUsage.startTime),
935
+ lastActivity: stat.mtime,
936
+ tokenUsage: sessionUsage.usage
937
+ };
938
+ }
939
+ /**
940
+ * Check if an agent is running
941
+ */
942
+ isRunning(agentId) {
943
+ return sessionExistsSync(agentId);
944
+ }
945
+ };
946
+ /**
947
+ * Create a Claude Code runtime instance
948
+ */
949
+ function createClaudeCodeRuntimeSync() {
950
+ return new ClaudeCodeRuntimeSync();
951
+ }
952
+ //#endregion
953
+ //#region ../../lib/cost-parsers/pi-parser.ts
954
+ init_errors();
955
+ //#endregion
956
+ //#region ../../lib/runtimes/pi.ts
957
+ init_behavior();
958
+ init_tmux();
959
+ init_pi_fifo();
960
+ init_errors();
961
+ init_paths();
962
+ promisify(exec);
963
+ //#endregion
964
+ //#region ../../lib/runtimes/index.ts
965
+ init_behavior();
966
+ init_ohmypi();
967
+ init_agents();
968
+ /**
969
+ * Runtime registry implementation
970
+ *
971
+ * Manages multiple runtime adapters and provides lookup by agent ID.
972
+ */
973
+ var RuntimeRegistry = class {
974
+ runtimes = /* @__PURE__ */ new Map();
975
+ /**
976
+ * Register a runtime adapter
977
+ */
978
+ register(runtime) {
979
+ this.runtimes.set(runtime.name, runtime);
980
+ }
981
+ /**
982
+ * Get a runtime by name
983
+ */
984
+ get(name) {
985
+ return this.runtimes.get(name);
986
+ }
987
+ /**
988
+ * Get all registered runtimes
989
+ */
990
+ getAll() {
991
+ return Array.from(this.runtimes.values());
992
+ }
993
+ /**
994
+ * Get the runtime for a specific agent.
995
+ *
996
+ * Reads the agent's state file and dispatches by `state.harness`. When
997
+ * the harness field is missing or carries a legacy value (e.g. 'claude'
998
+ * from pre-PAN-636 wire format), we fall back to the claude-code runtime
999
+ * to preserve back-compat (PAN-636 ac2).
1000
+ */
1001
+ getRuntimeForAgent(agentId) {
1002
+ const state = getAgentStateSync(agentId);
1003
+ if (!state) return null;
1004
+ const harness = state.harness;
1005
+ if (harness === "ohmypi" || harness === "pi") return this.get("ohmypi") ?? null;
1006
+ if (harness === "codex") return this.get("codex") ?? null;
1007
+ return this.get("claude-code") ?? null;
1008
+ }
1009
+ };
1010
+ /**
1011
+ * Global runtime registry instance
1012
+ */
1013
+ let globalRegistry = null;
1014
+ /**
1015
+ * Get the global runtime registry
1016
+ *
1017
+ * Creates a new registry if one doesn't exist.
1018
+ * Registers Claude Code runtime by default.
1019
+ */
1020
+ function getGlobalRegistry() {
1021
+ if (!globalRegistry) {
1022
+ globalRegistry = new RuntimeRegistry();
1023
+ globalRegistry.register(createClaudeCodeRuntimeSync());
1024
+ globalRegistry.register(createOhmypiRuntimeSync());
1025
+ globalRegistry.register(createCodexRuntimeSync());
1026
+ }
1027
+ return globalRegistry;
1028
+ }
1029
+ /**
1030
+ * Helper to get the runtime for an agent from the global registry
1031
+ */
1032
+ function getRuntimeForAgent(agentId) {
1033
+ return getGlobalRegistry().getRuntimeForAgent(agentId);
1034
+ }
1035
+ //#endregion
1036
+ //#region ../../lib/cloister/agent-idle.ts
1037
+ init_agents();
1038
+ init_tmux();
1039
+ function getAgentEffectiveLastActivityMs(agentId) {
1040
+ const candidates = [];
1041
+ const runtimeState = getAgentRuntimeStateSync(agentId);
1042
+ const runtimeMs = runtimeState?.lastActivity ? new Date(runtimeState.lastActivity).getTime() : NaN;
1043
+ if (Number.isFinite(runtimeMs)) candidates.push(runtimeMs);
1044
+ try {
1045
+ const tmuxActivity = listPaneValuesSync(agentId, "#{window_activity}").map((value) => Number.parseInt(value.trim(), 10) * 1e3).filter(Number.isFinite);
1046
+ candidates.push(...tmuxActivity);
1047
+ } catch {}
1048
+ try {
1049
+ const heartbeat = getRuntimeForAgent(agentId)?.getHeartbeat(agentId);
1050
+ if (heartbeat?.timestamp) {
1051
+ const heartbeatMs = heartbeat.timestamp.getTime();
1052
+ if (Number.isFinite(heartbeatMs)) candidates.push(heartbeatMs);
1053
+ }
1054
+ } catch {}
1055
+ return candidates.length > 0 ? Math.max(...candidates) : null;
1056
+ }
1057
+ function isAgentIdleForNudge(agentId, staleActiveThresholdMs = 300 * 1e3, now = Date.now()) {
1058
+ const runtimeState = getAgentRuntimeStateSync(agentId);
1059
+ const effectiveLastActivityMs = getAgentEffectiveLastActivityMs(agentId);
1060
+ if (!runtimeState) {
1061
+ if (effectiveLastActivityMs === null) {
1062
+ console.log(`[deacon] ${agentId}: no runtime.json — skipping (hook not yet fired)`);
1063
+ return false;
1064
+ }
1065
+ return now - effectiveLastActivityMs > staleActiveThresholdMs;
1066
+ }
1067
+ if (runtimeState.state === "suspended" || runtimeState.state === "stopped") return false;
1068
+ if (runtimeState.state === "waiting-on-human") return false;
1069
+ if (runtimeState.state === "idle") return true;
1070
+ return now - (effectiveLastActivityMs ?? new Date(runtimeState.lastActivity).getTime()) > staleActiveThresholdMs;
1071
+ }
1072
+ //#endregion
1073
+ //#region ../../lib/cloister/agent-death.ts
1074
+ /**
1075
+ * Agent death diagnostics (PAN-2108).
1076
+ *
1077
+ * When an ohmypi/pi agent process dies, the launcher records its exit code +
1078
+ * timestamp to `<agentDir>/exit-status` (see buildOhmypiCommand in
1079
+ * launcher-generator.ts), and omp's stdout/stderr is captured to
1080
+ * `<agentDir>/output.log`. This module turns those into a one-line death reason
1081
+ * the deacon can log, replacing the opaque "session is dead" with an actual
1082
+ * cause — the gap that made the flywheel orchestrator's silent death
1083
+ * undiagnosable in RUN-30.
1084
+ */
1085
+ init_paths();
1086
+ init_tmux();
1087
+ function agentDir(agentId) {
1088
+ return join$1(getOverdeckHome(), "agents", agentId);
1089
+ }
1090
+ /** Read the launcher-recorded exit code + UTC timestamp, or null if absent. */
1091
+ function readAgentExitStatus(agentId) {
1092
+ try {
1093
+ const p = join$1(agentDir(agentId), "exit-status");
1094
+ if (!existsSync(p)) return null;
1095
+ const raw = readFileSync(p, "utf-8").trim();
1096
+ if (!raw) return null;
1097
+ const [code, at = ""] = raw.split(/\s+/);
1098
+ return {
1099
+ code: code ?? "?",
1100
+ at
1101
+ };
1102
+ } catch {
1103
+ return null;
1104
+ }
1105
+ }
1106
+ /**
1107
+ * Best-effort one-line description of why an agent process died: the
1108
+ * launcher-recorded exit status (preferred), the tmux pane exit status (fallback
1109
+ * when the dead pane corpse still exists), and the tail of output.log.
1110
+ */
1111
+ function describeAgentDeath(agentId) {
1112
+ const parts = [];
1113
+ const exit = readAgentExitStatus(agentId);
1114
+ if (exit) parts.push(`exit=${exit.code}${exit.at ? ` at ${exit.at}` : ""}`);
1115
+ else if (sessionExistsSync(agentId)) {
1116
+ const paneExit = listPaneValuesSync(agentId, "#{pane_exit_status}").find((v) => v !== "");
1117
+ if (paneExit) parts.push(`pane_exit=${paneExit}`);
1118
+ }
1119
+ try {
1120
+ const logPath = join$1(agentDir(agentId), "output.log");
1121
+ if (existsSync(logPath)) {
1122
+ const tail = readFileSync(logPath, "utf-8").slice(-1500).trim().split("\n").slice(-6).join(" | ").trim();
1123
+ if (tail) parts.push(`output.log tail: ${tail}`);
1124
+ }
1125
+ } catch {}
1126
+ return parts.length ? parts.join("; ") : "no exit trace (exit-status + output.log empty)";
1127
+ }
1128
+ //#endregion
1129
+ //#region ../../lib/cloister/stuck-remediation-state.ts
1130
+ init_control_settings();
1131
+ init_paths();
1132
+ function agentStateDir(agentId) {
1133
+ return join$1(getOverdeckHome(), "agents", agentId);
1134
+ }
1135
+ function statePath(agentId) {
1136
+ return join$1(agentStateDir(agentId), "stuck-remediation.json");
1137
+ }
1138
+ function readStuckRemediationState(agentId) {
1139
+ const filePath = statePath(agentId);
1140
+ if (!existsSync(filePath)) return null;
1141
+ try {
1142
+ return JSON.parse(readFileSync(filePath, "utf-8"));
1143
+ } catch (error) {
1144
+ console.warn(`Failed to read stuck-remediation state for ${agentId}:`, error);
1145
+ return null;
1146
+ }
1147
+ }
1148
+ function writeStuckRemediationState(agentId, state) {
1149
+ mkdirSync(agentStateDir(agentId), { recursive: true });
1150
+ writeFileSync(statePath(agentId), `${JSON.stringify(state, null, 2)}\n`, "utf-8");
1151
+ }
1152
+ function clearStuckRemediationState(agentId) {
1153
+ const filePath = statePath(agentId);
1154
+ if (!existsSync(filePath)) return;
1155
+ unlinkSync(filePath);
1156
+ }
1157
+ //#endregion
1158
+ //#region ../../lib/cloister/stuck-remediation.ts
1159
+ init_agents();
1160
+ init_tmux();
1161
+ function issueIdForAgent(agent) {
1162
+ return agent.issueId || agent.id.replace(/^agent-/, "").toUpperCase();
1163
+ }
1164
+ function shouldSkipReviewStatus(status) {
1165
+ if (!status) return false;
1166
+ if (status.stuck || status.deaconIgnored || status.mergeStatus === "merged" || status.readyForMerge) return true;
1167
+ if (status.reviewStatus === "blocked" || status.reviewStatus === "failed") return true;
1168
+ if (status.verificationStatus === "failed" || status.testStatus === "failed") return true;
1169
+ if (status.reviewStatus === "reviewing" || status.reviewStatus === "passed") return true;
1170
+ return status.reviewStatus === "pending" && !!status.reviewRequestedAt;
1171
+ }
1172
+ /**
1173
+ * PAN-2581 (FR-2, residual): phase gate for the health-check poke loop
1174
+ * (service.ts pokeAgent → pokeAgentWithEscalation → idle-alive pause), the
1175
+ * SECOND independent idleness consumer besides stuck-remediation. A warm-idle
1176
+ * work agent on a pipeline-owned issue — and a warm-idle review/test agent
1177
+ * after its verdict — must never be poked ("are you stuck?") or idle-alive
1178
+ * paused: the poke spends tokens re-explaining the wait, and the pause
1179
+ * manufactures the paused-delivery-target deadlock PAN-2461 exists to undo.
1180
+ * A genuinely stalled mid-review parent is covered by the PAN-2584 liveness
1181
+ * deadline, not pokes. Owed-rework agents (review blocked/failed, tests
1182
+ * failed) are ALSO skipped here by design: shouldSkipReviewStatus returns
1183
+ * true for those because the PAN-2519 wedged-rework path owns their
1184
+ * escalation — the health-check poke loop must not double-drive them.
1185
+ * Roles outside work/review/test (plan, strike, flywheel, sequencer) keep
1186
+ * their existing idleness semantics.
1187
+ */
1188
+ function shouldSkipIdlePokeForAgent(agent, readStatus = getReviewStatusSync) {
1189
+ if (!agent) return false;
1190
+ if (agent.role !== "work" && agent.role !== "review" && agent.role !== "test") return false;
1191
+ return shouldSkipReviewStatus(readStatus((agent.issueId || agent.id.replace(/^agent-/, "").replace(/-(review|test|ship)(-.*)?$/, "").replace(/-slot-\d+$/, "")).toUpperCase()));
1192
+ }
1193
+ function hasPendingRework(status) {
1194
+ if (!status) return false;
1195
+ if (status.stuck || status.deaconIgnored || status.mergeStatus === "merged" || status.readyForMerge) return false;
1196
+ return status.reviewStatus === "blocked" || status.reviewStatus === "failed" || status.verificationStatus === "failed" || status.testStatus === "failed";
1197
+ }
1198
+ const STUCK_KILL_REQUEUE_CEILING = 25;
1199
+ async function evaluateWedgedReworkAgent(agent, config, now, actions) {
1200
+ const agentId = agent.id;
1201
+ if (agent.role !== "work" || !agent.workspace) return false;
1202
+ const issueId = issueIdForAgent(agent);
1203
+ const status = getReviewStatusSync(issueId);
1204
+ if (!hasPendingRework(status)) return false;
1205
+ const lastActivityMs = getAgentEffectiveLastActivityMs(agentId);
1206
+ if (lastActivityMs === null || !Number.isFinite(lastActivityMs)) return false;
1207
+ const stuckState = readStuckRemediationState(agentId);
1208
+ if (stuckState) {
1209
+ const firstStuckMs = new Date(stuckState.firstStuckAt).getTime();
1210
+ if (Number.isFinite(firstStuckMs) && lastActivityMs > firstStuckMs) {
1211
+ clearStuckRemediationState(agentId);
1212
+ return false;
1213
+ }
1214
+ }
1215
+ const idleMinutes = Math.floor((now - lastActivityMs) / 6e4);
1216
+ const lastStage = stuckState?.lastStage ?? 0;
1217
+ if (idleMinutes < config.stage3_minutes || lastStage >= 3) return false;
1218
+ const firstStuck = firstStuckAt(new Date(lastActivityMs).toISOString(), stuckState);
1219
+ if ((status?.autoRequeueCount ?? 0) >= STUCK_KILL_REQUEUE_CEILING) {
1220
+ markAgentTroubled(agentId);
1221
+ writeStuckRemediationState(agentId, stageState(3, now, firstStuck));
1222
+ logAction(actions, transitionAction(3, issueId, idleMinutes, "rework-wedge-troubled"));
1223
+ surfaceStuckNeedsYou(agent, issueId, firstStuck, actions);
1224
+ return true;
1225
+ }
1226
+ killSessionSync(agentId);
1227
+ writeStuckRemediationState(agentId, stageState(3, now, firstStuck));
1228
+ logAction(actions, transitionAction(3, issueId, idleMinutes, "killed-for-respawn"));
1229
+ return true;
1230
+ }
1231
+ function hasReadyBeads(readyByQueryRoot, agent, issueLabel) {
1232
+ return (readyByQueryRoot.get(resolveBeadsQueryRoot(agent.workspace))?.[issueLabel] ?? []).length > 0;
1233
+ }
1234
+ function shouldCheckReadyBeadsForAgent(agent, now) {
1235
+ const agentId = agent.id;
1236
+ if (!agentId) return false;
1237
+ if (agent.status !== "running") return false;
1238
+ if (agent.role !== "work") return false;
1239
+ if (!agent.workspace) return false;
1240
+ const completedAt = agent.completedAt;
1241
+ if (agent.paused || agent.troubled || completedAt) return false;
1242
+ if (!sessionExistsSync(agentId)) return false;
1243
+ if (shouldSkipReviewStatus(getReviewStatusSync(issueIdForAgent(agent)))) return false;
1244
+ return isAgentIdleForNudge(agentId, 300 * 1e3, now);
1245
+ }
1246
+ function firstStuckAt(runtimeLastActivity, stuckState) {
1247
+ return stuckState?.firstStuckAt ?? runtimeLastActivity;
1248
+ }
1249
+ function stageState(stage, now, firstStuck, prev) {
1250
+ return {
1251
+ lastStage: stage,
1252
+ lastStageAt: new Date(now).toISOString(),
1253
+ firstStuckAt: firstStuck,
1254
+ ...prev?.respawnCount !== void 0 ? { respawnCount: prev.respawnCount } : {},
1255
+ ...prev?.lastRespawnAt !== void 0 ? { lastRespawnAt: prev.lastRespawnAt } : {}
1256
+ };
1257
+ }
1258
+ function transitionAction(stage, issueId, idleMinutes, action) {
1259
+ return `[deacon] stuck-remediation stage=${stage} issue=${issueId} idleMin=${idleMinutes} action=${action}`;
1260
+ }
1261
+ function logAction(actions, action) {
1262
+ actions.push(action);
1263
+ console.log(action);
1264
+ logDeaconEventSync(action);
1265
+ }
1266
+ function surfaceStuckNeedsYou(agent, issueId, generation, actions) {
1267
+ if (!agent.workspace) return;
1268
+ if (recordRecoveryFailure(agent.workspace, issueId, "stuck-remediation", generation, 1).emitNeedsYou) logAction(actions, `[deacon] needs-you ${issueId}: stuck remediation exhausted`);
1269
+ }
1270
+ async function evaluateAgent(agent, config, now, actions, readyByQueryRoot) {
1271
+ const agentId = agent.id;
1272
+ if (!agentId) return;
1273
+ if (agent.status !== "running") return;
1274
+ const completedAt = agent.completedAt;
1275
+ if (agent.paused || agent.troubled || completedAt) return;
1276
+ if (agent.role === "flywheel") {
1277
+ await evaluateFlywheelOrchestrator(agent, config, now, actions);
1278
+ return;
1279
+ }
1280
+ if (!sessionExistsSync(agentId)) return;
1281
+ if (agent.role === "plan" && agent.auto === true) {
1282
+ await evaluateAutoPlanningAgent(agent, config, now, actions);
1283
+ return;
1284
+ }
1285
+ if (await evaluateWedgedReworkAgent(agent, config, now, actions)) return;
1286
+ if (!shouldCheckReadyBeadsForAgent(agent, now)) return;
1287
+ if (!agent.workspace) return;
1288
+ const issueId = issueIdForAgent(agent);
1289
+ if (hasReadyBeads(readyByQueryRoot, agent, issueId.toLowerCase())) return;
1290
+ const lastActivityMs = getAgentEffectiveLastActivityMs(agentId);
1291
+ if (lastActivityMs === null) return;
1292
+ if (!Number.isFinite(lastActivityMs)) return;
1293
+ const lastActivity = new Date(lastActivityMs).toISOString();
1294
+ const stuckState = readStuckRemediationState(agentId);
1295
+ if (stuckState) {
1296
+ const firstStuckMs = new Date(stuckState.firstStuckAt).getTime();
1297
+ if (Number.isFinite(firstStuckMs) && lastActivityMs > firstStuckMs) {
1298
+ clearStuckRemediationState(agentId);
1299
+ return;
1300
+ }
1301
+ }
1302
+ const idleMinutes = Math.floor((now - lastActivityMs) / 6e4);
1303
+ const lastStage = stuckState?.lastStage ?? 0;
1304
+ const firstStuck = firstStuckAt(lastActivity, stuckState);
1305
+ if (idleMinutes >= config.stage3_minutes && lastStage < 3) {
1306
+ markAgentTroubled(agentId);
1307
+ writeStuckRemediationState(agentId, stageState(3, now, firstStuck));
1308
+ logAction(actions, transitionAction(3, issueId, idleMinutes, "marked-troubled"));
1309
+ surfaceStuckNeedsYou(agent, issueId, firstStuck, actions);
1310
+ return;
1311
+ }
1312
+ if (idleMinutes >= config.stage2_minutes && lastStage < 2) {
1313
+ if ((await resumeAgent(agentId, `Resuming after auto-detected stall (${idleMinutes} min idle). Review your last work and decide whether to continue or signal done with \`pan done ${issueId}\`.`)).success) {
1314
+ writeStuckRemediationState(agentId, stageState(2, now, firstStuck));
1315
+ logAction(actions, transitionAction(2, issueId, idleMinutes, "resumed"));
1316
+ } else {
1317
+ const action = `${transitionAction(2, issueId, idleMinutes, "resume-failed")} — death: ${describeAgentDeath(agentId)}`;
1318
+ console.warn(action);
1319
+ logDeaconEventSync(action);
1320
+ }
1321
+ return;
1322
+ }
1323
+ if (idleMinutes >= config.stage1_minutes && lastStage < 1) {
1324
+ await messageAgent(agentId, `You appear stuck — no tool calls for ${idleMinutes} min. If your implementation is complete, run \`pan done ${issueId}\`. Otherwise reply with a one-line summary of what you're waiting on, then continue.`);
1325
+ writeStuckRemediationState(agentId, stageState(1, now, firstStuck));
1326
+ logAction(actions, transitionAction(1, issueId, idleMinutes, "poked"));
1327
+ }
1328
+ }
1329
+ async function evaluateAutoPlanningAgent(agent, config, now, actions) {
1330
+ const agentId = agent.id;
1331
+ if (!isAgentIdleForNudge(agentId, 300 * 1e3, now)) return;
1332
+ if (await Effect.runPromise(countPendingAskUserQuestionsForAgent(agentId)) === 0) return;
1333
+ const lastActivityMs = getAgentEffectiveLastActivityMs(agentId);
1334
+ if (lastActivityMs === null || !Number.isFinite(lastActivityMs)) return;
1335
+ const lastActivity = new Date(lastActivityMs).toISOString();
1336
+ const stuckState = readStuckRemediationState(agentId);
1337
+ if (stuckState) {
1338
+ const firstStuckMs = new Date(stuckState.firstStuckAt).getTime();
1339
+ if (Number.isFinite(firstStuckMs) && lastActivityMs > firstStuckMs) {
1340
+ clearStuckRemediationState(agentId);
1341
+ return;
1342
+ }
1343
+ }
1344
+ const idleMinutes = Math.floor((now - lastActivityMs) / 6e4);
1345
+ const lastStage = stuckState?.lastStage ?? 0;
1346
+ if (idleMinutes < config.stage1_minutes || lastStage >= 1) return;
1347
+ const issueId = issueIdForAgent(agent);
1348
+ await messageAgent(agentId, `This planning session was launched with \`pan plan ${issueId} --auto\`, so do not wait for operator input. Proceed with the most defensible default from the issue/PRD/comments, record the choice in \`plan.autoDecisions[]\` with rationale, and continue to \`pan plan finalize\`. Only halt for a genuine contradiction between authoritative inputs.`);
1349
+ writeStuckRemediationState(agentId, stageState(1, now, firstStuckAt(lastActivity, stuckState)));
1350
+ logAction(actions, transitionAction(1, issueId, idleMinutes, "auto-planning-default"));
1351
+ }
1352
+ const FLYWHEEL_RESPAWN_WINDOW_MS = 1800 * 1e3;
1353
+ const FLYWHEEL_MAX_RESPAWNS = 3;
1354
+ const FLYWHEEL_ORCHESTRATOR_AGENT_ID = "flywheel-orchestrator";
1355
+ /**
1356
+ * Pure decision for recovering a dead or wedged flywheel orchestrator (no I/O —
1357
+ * side effects live in remediateFlywheelOrchestrator). The respawn cap
1358
+ * (FLYWHEEL_MAX_RESPAWNS within FLYWHEEL_RESPAWN_WINDOW_MS) stops an infinite
1359
+ * relaunch loop: past the cap, escalate to paused+troubled. `hasActiveRun` false
1360
+ * ⇒ the operator stopped the flywheel deliberately ⇒ do not resurrect.
1361
+ */
1362
+ function decideFlywheelRemediation(opts) {
1363
+ if (!opts.hasActiveRun) return { kind: "noop" };
1364
+ const lastRespawnMs = opts.prev?.lastRespawnAt ? new Date(opts.prev.lastRespawnAt).getTime() : 0;
1365
+ const respawnCount = Number.isFinite(lastRespawnMs) && opts.now - lastRespawnMs < FLYWHEEL_RESPAWN_WINDOW_MS ? opts.prev?.respawnCount ?? 0 : 0;
1366
+ if (respawnCount >= FLYWHEEL_MAX_RESPAWNS) return {
1367
+ kind: "escalate",
1368
+ respawnCount
1369
+ };
1370
+ return {
1371
+ kind: "relaunch",
1372
+ respawnCount: respawnCount + 1
1373
+ };
1374
+ }
1375
+ /** True when the orchestrator's process is actually gone (session missing or dead pane). */
1376
+ function isFlywheelOrchestratorDead(agentId) {
1377
+ if (!sessionExistsSync(agentId)) return true;
1378
+ return listPaneValuesSync(agentId, "#{pane_dead}").some((v) => v === "1");
1379
+ }
1380
+ /**
1381
+ * Recover a dead or wedged flywheel orchestrator: relaunch (capped) or, past the
1382
+ * cap, pause+trouble. `reason` describes why recovery fired (death vs wedge) for
1383
+ * the deacon log. NO_RESUME is intentionally NOT consulted (see header comment) —
1384
+ * the operator gate is the active run (`pan flywheel stop`) / patrol freeze.
1385
+ */
1386
+ async function remediateFlywheelOrchestrator(agentId, now, actions, reason) {
1387
+ const decision = decideFlywheelRemediation({
1388
+ hasActiveRun: Boolean(getFlywheelActiveRunId()),
1389
+ prev: readStuckRemediationState(agentId),
1390
+ now
1391
+ });
1392
+ if (decision.kind === "noop") return;
1393
+ const { resumeFlywheel, pauseFlywheel } = await import("./flywheel-RCnHAgc4.js");
1394
+ const prev = readStuckRemediationState(agentId);
1395
+ const nowIso = new Date(now).toISOString();
1396
+ if (decision.kind === "escalate") {
1397
+ await pauseFlywheel();
1398
+ markAgentTroubled(agentId);
1399
+ writeStuckRemediationState(agentId, {
1400
+ lastStage: 3,
1401
+ lastStageAt: nowIso,
1402
+ firstStuckAt: prev?.firstStuckAt ?? nowIso,
1403
+ respawnCount: decision.respawnCount,
1404
+ lastRespawnAt: prev?.lastRespawnAt
1405
+ });
1406
+ logAction(actions, `[deacon] FLYWHEEL orchestrator ${reason} and exceeded ${FLYWHEEL_MAX_RESPAWNS} relaunches in ${FLYWHEEL_RESPAWN_WINDOW_MS / 6e4}min — paused + troubled; operator needed`);
1407
+ return;
1408
+ }
1409
+ try {
1410
+ killSessionSync(agentId);
1411
+ } catch {}
1412
+ try {
1413
+ await resumeFlywheel();
1414
+ writeStuckRemediationState(agentId, {
1415
+ lastStage: 0,
1416
+ lastStageAt: nowIso,
1417
+ firstStuckAt: nowIso,
1418
+ respawnCount: decision.respawnCount,
1419
+ lastRespawnAt: nowIso
1420
+ });
1421
+ logAction(actions, `[deacon] FLYWHEEL orchestrator ${reason} — fresh-launched (relaunch ${decision.respawnCount}/${FLYWHEEL_MAX_RESPAWNS})`);
1422
+ } catch (error) {
1423
+ logAction(actions, `[deacon] FLYWHEEL orchestrator ${reason} — relaunch FAILED: ${error instanceof Error ? error.message : String(error)}`);
1424
+ }
1425
+ }
1426
+ async function evaluateFlywheelOrchestrator(agent, config, now, actions) {
1427
+ const agentId = agent.id;
1428
+ if (isFlywheelOrchestratorDead(agentId)) {
1429
+ await remediateFlywheelOrchestrator(agentId, now, actions, `DIED (${describeAgentDeath(agentId)})`);
1430
+ return;
1431
+ }
1432
+ if (!isAgentIdleForNudge(agentId, 300 * 1e3, now)) return;
1433
+ const runtime = getAgentRuntimeStateSync(agentId);
1434
+ if (!runtime?.lastActivity) return;
1435
+ const lastActivityMs = new Date(runtime.lastActivity).getTime();
1436
+ if (!Number.isFinite(lastActivityMs)) return;
1437
+ const stuckState = readStuckRemediationState(agentId);
1438
+ if (stuckState) {
1439
+ const firstStuckMs = new Date(stuckState.firstStuckAt).getTime();
1440
+ if (Number.isFinite(firstStuckMs) && lastActivityMs > firstStuckMs) {
1441
+ clearStuckRemediationState(agentId);
1442
+ return;
1443
+ }
1444
+ }
1445
+ const idleMinutes = Math.floor((now - lastActivityMs) / 6e4);
1446
+ const lastStage = stuckState?.lastStage ?? 0;
1447
+ const firstStuck = firstStuckAt(runtime.lastActivity, stuckState);
1448
+ if (idleMinutes >= config.flywheel_stage3_minutes && lastStage < 3) {
1449
+ await remediateFlywheelOrchestrator(agentId, now, actions, `wedged (idle ${idleMinutes}min)`);
1450
+ return;
1451
+ }
1452
+ if (idleMinutes >= config.flywheel_stage2_minutes && lastStage < 2) {
1453
+ await messageAgent(agentId, `Stage 2: idle ${idleMinutes} min — run a FULL flywheel tick NOW: inventory -> diagnose -> suggest -> launch ready work -> \`pan flywheel emit-status\`. Then call ScheduleWakeup(delaySeconds:1000) to arm the next tick. Do NOT ask the operator a question, do NOT wait, and do NOT just emit a stale status or pause.`);
1454
+ writeStuckRemediationState(agentId, stageState(2, now, firstStuck, stuckState));
1455
+ logAction(actions, transitionAction(2, "FLYWHEEL", idleMinutes, "escalated-nudge"));
1456
+ return;
1457
+ }
1458
+ if (idleMinutes >= config.flywheel_stage1_minutes && lastStage < 1) {
1459
+ await messageAgent(agentId, `You appear stuck — ${idleMinutes} min since your last tick. Run a FULL flywheel tick NOW: inventory -> diagnose -> suggest -> launch ready work -> \`pan flywheel emit-status\`. Then call ScheduleWakeup(delaySeconds:1000) to arm the next tick. Do NOT ask the operator a question, do NOT wait, and do NOT just emit a stale status or pause.`);
1460
+ writeStuckRemediationState(agentId, stageState(1, now, firstStuck, stuckState));
1461
+ logAction(actions, transitionAction(1, "FLYWHEEL", idleMinutes, "poked"));
1462
+ }
1463
+ }
1464
+ async function reconcileActiveFlywheelWithoutRunningAgent(now, actions) {
1465
+ if (!getFlywheelActiveRunId()) return;
1466
+ if (isFlywheelGloballyPaused()) return;
1467
+ if (sessionExistsSync(FLYWHEEL_ORCHESTRATOR_AGENT_ID)) return;
1468
+ await remediateFlywheelOrchestrator(FLYWHEEL_ORCHESTRATOR_AGENT_ID, now, actions, `DIED (${describeAgentDeath(FLYWHEEL_ORCHESTRATOR_AGENT_ID)})`);
1469
+ }
1470
+ async function checkStuckAgentRemediation(opts = {}) {
1471
+ const config = loadCloisterConfigSync().stuck_remediation ?? DEFAULT_CLOISTER_CONFIG.stuck_remediation;
1472
+ if (!config.enabled) return [];
1473
+ const actions = [];
1474
+ const now = opts.now ?? Date.now();
1475
+ const runningAgents = listRunningAgentsSync();
1476
+ const readyByQueryRoot = /* @__PURE__ */ new Map();
1477
+ const workAgentsByQueryRoot = /* @__PURE__ */ new Map();
1478
+ let sawFlywheelOrchestrator = false;
1479
+ for (const agent of runningAgents) {
1480
+ if (!shouldCheckReadyBeadsForAgent(agent, now)) continue;
1481
+ const queryRoot = resolveBeadsQueryRoot(agent.workspace);
1482
+ const workspaceAgents = workAgentsByQueryRoot.get(queryRoot) ?? [];
1483
+ workspaceAgents.push(agent);
1484
+ workAgentsByQueryRoot.set(queryRoot, workspaceAgents);
1485
+ }
1486
+ for (const [queryRoot, workspaceAgents] of workAgentsByQueryRoot) {
1487
+ const issueIds = workspaceAgents.map(issueIdForAgent);
1488
+ const ready = await Effect.runPromise(queryReadyBeadsByIssueLabels(queryRoot, issueIds, { acquisitionTimeoutMs: 500 }));
1489
+ readyByQueryRoot.set(queryRoot, ready.byIssue);
1490
+ }
1491
+ for (const agent of runningAgents) {
1492
+ if (agent.id === FLYWHEEL_ORCHESTRATOR_AGENT_ID || agent.role === "flywheel") sawFlywheelOrchestrator = true;
1493
+ try {
1494
+ await evaluateAgent(agent, config, now, actions, readyByQueryRoot);
1495
+ } catch (error) {
1496
+ const message = `[deacon] stuck-remediation agent=${agent.id || "(unknown)"} error=${error instanceof Error ? error.message : String(error)}`;
1497
+ console.error(message, error);
1498
+ logDeaconEventSync(message);
1499
+ }
1500
+ }
1501
+ if (!sawFlywheelOrchestrator) try {
1502
+ await reconcileActiveFlywheelWithoutRunningAgent(now, actions);
1503
+ } catch (error) {
1504
+ const message = `[deacon] stuck-remediation agent=${FLYWHEEL_ORCHESTRATOR_AGENT_ID} error=${error instanceof Error ? error.message : String(error)}`;
1505
+ console.error(message, error);
1506
+ logDeaconEventSync(message);
1507
+ }
1508
+ return actions;
1509
+ }
1510
+ //#endregion
1511
+ export { parseCodexApprovalPrompt as _, isAgentIdleForNudge as a, countPendingAskUserQuestionsForAgent as c, getAgentPendingQuestions as d, getAgentWorkspace as f, normalizeAwaitingInputPrompt as g, detectAwaitingInputFromPaneSync as h, shouldSkipReviewStatus as i, getAgentJsonlMtime as l, detectAwaitingInputForAgent as m, decideFlywheelRemediation as n, getRuntimeForAgent as o, scanPendingInputsPromise as p, shouldSkipIdlePokeForAgent as r, computeAgentEnrichment as s, checkStuckAgentRemediation as t, getAgentJsonlPath as u };
1512
+
1513
+ //# sourceMappingURL=stuck-remediation-CxsyxwFO.js.map