@saluzi/saluzi-edu 0.7.36 → 0.8.0

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 (187) hide show
  1. package/dist/cli.js +1014 -54
  2. package/dist/rcs-web/assets/{AdminPanel-DNBSru_G.js → AdminPanel-CCkH7iJv.js} +1 -1
  3. package/dist/rcs-web/assets/ArtifactView-v2hQNqJZ.js +1 -0
  4. package/dist/rcs-web/assets/{ArtifactsGallery-CpLh8gO6.js → ArtifactsGallery-BSdlASB3.js} +5 -5
  5. package/{packages/remote-control-server/web/dist/assets/Claim-C7E3WT4f.js → dist/rcs-web/assets/Claim-BK0aslcx.js} +1 -1
  6. package/dist/rcs-web/assets/Dashboard-Cr-2Grcq.js +12 -0
  7. package/dist/rcs-web/assets/Join-CSQz-8kg.js +1 -0
  8. package/dist/rcs-web/assets/Login-CIblWx47.js +1 -0
  9. package/dist/rcs-web/assets/MemoriesPage-D2Qadc7N.js +1 -0
  10. package/{packages/remote-control-server/web/dist/assets/MemoryTypeChips-DL1Uf2db.js → dist/rcs-web/assets/MemoryTypeChips-BFl2a9Tv.js} +2 -2
  11. package/dist/rcs-web/assets/Register-nFyACJRk.js +1 -0
  12. package/dist/rcs-web/assets/{RegisterEmpty-CdLm4eR8.js → RegisterEmpty-FxupE-t-.js} +1 -1
  13. package/dist/rcs-web/assets/{SessionDetail-Bkz6dL9v.js → SessionDetail-BpmjKpR1.js} +19 -24
  14. package/dist/rcs-web/assets/SessionVisibilityBadge-D6XUIJa4.js +21 -0
  15. package/dist/rcs-web/assets/Setup-DGBcwRTD.js +1 -0
  16. package/dist/rcs-web/assets/{ShareLanding-CJQURPqs.js → ShareLanding-CyNQfq4N.js} +1 -1
  17. package/dist/rcs-web/assets/{TeamDetail-BTbWxeki.js → TeamDetail-4aZd9y8I.js} +3 -3
  18. package/dist/rcs-web/assets/TeamList-Cs6JQa7m.js +1 -0
  19. package/dist/rcs-web/assets/{TeamSettings-CmUq3hLc.js → TeamSettings-DX0MfIJy.js} +1 -1
  20. package/{packages/remote-control-server/web/dist/assets/UserSearchInput-C8H64lVR.js → dist/rcs-web/assets/UserSearchInput-CyhqVZCc.js} +2 -2
  21. package/dist/rcs-web/assets/{UserSettings-BEIlh9kd.js → UserSettings-CsFYao6k.js} +1 -1
  22. package/dist/rcs-web/assets/{arc-BtitZIgo.js → arc-BbFYStVr.js} +1 -1
  23. package/{packages/remote-control-server/web/dist/assets/architectureDiagram-3BPJPVTR-B5sR9G2-.js → dist/rcs-web/assets/architectureDiagram-3BPJPVTR-BrraS5HV.js} +1 -1
  24. package/dist/rcs-web/assets/{blockDiagram-GPEHLZMM-5cF13FZT.js → blockDiagram-GPEHLZMM-BSrrZzGd.js} +1 -1
  25. package/dist/rcs-web/assets/{c4Diagram-AAUBKEIU-Blp83HZs.js → c4Diagram-AAUBKEIU-BwIi-MY-.js} +1 -1
  26. package/dist/rcs-web/assets/channel-D9MN_Xoy.js +1 -0
  27. package/dist/rcs-web/assets/{chunk-2J33WTMH-nAF6ry-x.js → chunk-2J33WTMH-RF5WXSdc.js} +1 -1
  28. package/dist/rcs-web/assets/{chunk-4BX2VUAB-B_YEQwMM.js → chunk-4BX2VUAB-HD-9lc81.js} +1 -1
  29. package/dist/rcs-web/assets/{chunk-55IACEB6-DWgWeTMt.js → chunk-55IACEB6-DORDCTWG.js} +1 -1
  30. package/{packages/remote-control-server/web/dist/assets/chunk-727SXJPM-lfm6jXAu.js → dist/rcs-web/assets/chunk-727SXJPM-BgEvck_h.js} +1 -1
  31. package/{packages/remote-control-server/web/dist/assets/chunk-AQP2D5EJ-CWnhAZ9O.js → dist/rcs-web/assets/chunk-AQP2D5EJ-CYDKpO5q.js} +1 -1
  32. package/dist/rcs-web/assets/{chunk-FMBD7UC4-QBtdnQIp.js → chunk-FMBD7UC4-HTfaOp-P.js} +1 -1
  33. package/dist/rcs-web/assets/{chunk-ND2GUHAM-YUuihu7V.js → chunk-ND2GUHAM-C7j1dy_M.js} +1 -1
  34. package/dist/rcs-web/assets/{chunk-QZHKN3VN-CegaWivs.js → chunk-QZHKN3VN-DrNt3GZ4.js} +1 -1
  35. package/dist/rcs-web/assets/classDiagram-4FO5ZUOK-C7FZfsl-.js +1 -0
  36. package/dist/rcs-web/assets/classDiagram-v2-Q7XG4LA2-C7FZfsl-.js +1 -0
  37. package/dist/rcs-web/assets/{code-block-IT6T5CEO-D2n4Ga2v.js → code-block-IT6T5CEO-qOs_ie5D.js} +1 -1
  38. package/dist/rcs-web/assets/{copy-Dt0a6XCD.js → copy-LeFUX09K.js} +1 -1
  39. package/{packages/remote-control-server/web/dist/assets/cose-bilkent-S5V4N54A-D3tF664q.js → dist/rcs-web/assets/cose-bilkent-S5V4N54A-CNYjbdwx.js} +1 -1
  40. package/dist/rcs-web/assets/{dagre-BM42HDAG-Ba9POJgR.js → dagre-BM42HDAG-CzF1zU8o.js} +1 -1
  41. package/dist/rcs-web/assets/{diagram-2AECGRRQ-CZAcdfXD.js → diagram-2AECGRRQ-BOYW474q.js} +1 -1
  42. package/dist/rcs-web/assets/{diagram-5GNKFQAL-DO4nXgzG.js → diagram-5GNKFQAL-CP-yWCBy.js} +1 -1
  43. package/{packages/remote-control-server/web/dist/assets/diagram-KO2AKTUF-BDK3PG7v.js → dist/rcs-web/assets/diagram-KO2AKTUF-DdqQ4pAJ.js} +1 -1
  44. package/dist/rcs-web/assets/{diagram-LMA3HP47-DYXmhnhQ.js → diagram-LMA3HP47-CE2gGIRy.js} +1 -1
  45. package/dist/rcs-web/assets/{diagram-OG6HWLK6-CLarvguU.js → diagram-OG6HWLK6-BNA49_sd.js} +1 -1
  46. package/dist/rcs-web/assets/dialog-DnbWz68R.js +1 -0
  47. package/dist/rcs-web/assets/{erDiagram-TEJ5UH35-D4zryVmf.js → erDiagram-TEJ5UH35-DVflh1jg.js} +1 -1
  48. package/{packages/remote-control-server/web/dist/assets/flowDiagram-I6XJVG4X-C55CpRnZ.js → dist/rcs-web/assets/flowDiagram-I6XJVG4X-B8b91Tm9.js} +1 -1
  49. package/{packages/remote-control-server/web/dist/assets/ganttDiagram-6RSMTGT7-a33rVx18.js → dist/rcs-web/assets/ganttDiagram-6RSMTGT7-7fEdykwc.js} +1 -1
  50. package/{packages/remote-control-server/web/dist/assets/gitGraphDiagram-PVQCEYII-CdeFuha2.js → dist/rcs-web/assets/gitGraphDiagram-PVQCEYII-B_17h1CU.js} +1 -1
  51. package/dist/rcs-web/assets/{infoDiagram-5YYISTIA-CkgCIBPN.js → infoDiagram-5YYISTIA-DWa7j6Zg.js} +1 -1
  52. package/dist/rcs-web/assets/{ishikawaDiagram-YF4QCWOH-IMWeHd6c.js → ishikawaDiagram-YF4QCWOH-b11b1c8I.js} +1 -1
  53. package/{packages/remote-control-server/web/dist/assets/journeyDiagram-JHISSGLW-BW_NwQ4x.js → dist/rcs-web/assets/journeyDiagram-JHISSGLW-CsvW9Ud9.js} +1 -1
  54. package/{packages/remote-control-server/web/dist/assets/kanban-definition-UN3LZRKU-BEYl8Usi.js → dist/rcs-web/assets/kanban-definition-UN3LZRKU-B97kXWdO.js} +1 -1
  55. package/dist/rcs-web/assets/{linear-Di8Hsx3R.js → linear-CrAR73-K.js} +1 -1
  56. package/dist/rcs-web/assets/main-BOI1Ucfk.css +1 -0
  57. package/dist/rcs-web/assets/{main-BkfSO2Rz.js → main-CDaRKeiT.js} +24 -24
  58. package/{packages/remote-control-server/web/dist/assets/mermaid-VLURNSYL-Alki8AJh.js → dist/rcs-web/assets/mermaid-VLURNSYL-gQdmHkjr.js} +4 -4
  59. package/dist/rcs-web/assets/{mermaid.core-CPLRyRun.js → mermaid.core-DTuGObIu.js} +5 -5
  60. package/{packages/remote-control-server/web/dist/assets/mindmap-definition-RKZ34NQL-DzkpJBE2.js → dist/rcs-web/assets/mindmap-definition-RKZ34NQL-wGG267Yb.js} +1 -1
  61. package/dist/rcs-web/assets/{notifications-V4HNWkys.js → notifications-Ms9MI-nO.js} +1 -1
  62. package/dist/rcs-web/assets/{pieDiagram-4H26LBE5-BcvVbbf5.js → pieDiagram-4H26LBE5-DgayJQKV.js} +1 -1
  63. package/dist/rcs-web/assets/{quadrantDiagram-W4KKPZXB-DTIciStr.js → quadrantDiagram-W4KKPZXB-BOtyjbOc.js} +1 -1
  64. package/dist/rcs-web/assets/{refresh-cw-DPCoOD18.js → refresh-cw-Dc5tn8Z_.js} +1 -1
  65. package/{packages/remote-control-server/web/dist/assets/requirementDiagram-4Y6WPE33-Dilpse2A.js → dist/rcs-web/assets/requirementDiagram-4Y6WPE33-Ck-a8POo.js} +1 -1
  66. package/{packages/remote-control-server/web/dist/assets/sankeyDiagram-5OEKKPKP-DsBacA7d.js → dist/rcs-web/assets/sankeyDiagram-5OEKKPKP-DR0OBykc.js} +1 -1
  67. package/{packages/remote-control-server/web/dist/assets/sequenceDiagram-3UESZ5HK-C_USxpgF.js → dist/rcs-web/assets/sequenceDiagram-3UESZ5HK-DFOP0Bxr.js} +1 -1
  68. package/dist/rcs-web/assets/{stateDiagram-AJRCARHV-ClUhzFvq.js → stateDiagram-AJRCARHV-DF9rQs3c.js} +1 -1
  69. package/dist/rcs-web/assets/{stateDiagram-v2-BHNVJYJU-dRIOwebj.js → stateDiagram-v2-BHNVJYJU-Zl4Zj4zN.js} +1 -1
  70. package/dist/rcs-web/assets/{timeline-definition-PNZ67QCA-BH8TVQ46.js → timeline-definition-PNZ67QCA-C3MtsV-F.js} +1 -1
  71. package/dist/rcs-web/assets/{vennDiagram-CIIHVFJN-BtRNizK-.js → vennDiagram-CIIHVFJN-DP7wVqlq.js} +1 -1
  72. package/dist/rcs-web/assets/{wardleyDiagram-YWT4CUSO-BW1rj4A0.js → wardleyDiagram-YWT4CUSO-DxAqIThI.js} +1 -1
  73. package/{packages/remote-control-server/web/dist/assets/workerType-CS6pd4nT.js → dist/rcs-web/assets/workerType-CR0nPOQn.js} +1 -1
  74. package/dist/rcs-web/assets/{xychartDiagram-2RQKCTM6-JsSvd6FU.js → xychartDiagram-2RQKCTM6-n7XBFulh.js} +1 -1
  75. package/dist/rcs-web/index.html +2 -2
  76. package/dist/rcs-web/saluzi-icon.png +0 -0
  77. package/package.json +1 -1
  78. package/packages/remote-control-server/src/__tests__/environment-rpc.test.ts +142 -0
  79. package/packages/remote-control-server/src/routes/v1/environments.work.ts +13 -0
  80. package/packages/remote-control-server/src/routes/web/environments.ts +65 -0
  81. package/packages/remote-control-server/src/services/environment-rpc.ts +188 -0
  82. package/packages/remote-control-server/src/services/work-dispatch.ts +53 -4
  83. package/packages/remote-control-server/src/store.ts +12 -0
  84. package/packages/remote-control-server/src/types/api.ts +15 -4
  85. package/packages/remote-control-server/web/dist/assets/{AdminPanel-DNBSru_G.js → AdminPanel-CCkH7iJv.js} +1 -1
  86. package/packages/remote-control-server/web/dist/assets/ArtifactView-v2hQNqJZ.js +1 -0
  87. package/packages/remote-control-server/web/dist/assets/{ArtifactsGallery-CpLh8gO6.js → ArtifactsGallery-BSdlASB3.js} +5 -5
  88. package/{dist/rcs-web/assets/Claim-C7E3WT4f.js → packages/remote-control-server/web/dist/assets/Claim-BK0aslcx.js} +1 -1
  89. package/packages/remote-control-server/web/dist/assets/Dashboard-Cr-2Grcq.js +12 -0
  90. package/packages/remote-control-server/web/dist/assets/Join-CSQz-8kg.js +1 -0
  91. package/packages/remote-control-server/web/dist/assets/Login-CIblWx47.js +1 -0
  92. package/packages/remote-control-server/web/dist/assets/MemoriesPage-D2Qadc7N.js +1 -0
  93. package/{dist/rcs-web/assets/MemoryTypeChips-DL1Uf2db.js → packages/remote-control-server/web/dist/assets/MemoryTypeChips-BFl2a9Tv.js} +2 -2
  94. package/packages/remote-control-server/web/dist/assets/Register-nFyACJRk.js +1 -0
  95. package/packages/remote-control-server/web/dist/assets/{RegisterEmpty-CdLm4eR8.js → RegisterEmpty-FxupE-t-.js} +1 -1
  96. package/packages/remote-control-server/web/dist/assets/{SessionDetail-Bkz6dL9v.js → SessionDetail-BpmjKpR1.js} +19 -24
  97. package/packages/remote-control-server/web/dist/assets/SessionVisibilityBadge-D6XUIJa4.js +21 -0
  98. package/packages/remote-control-server/web/dist/assets/Setup-DGBcwRTD.js +1 -0
  99. package/packages/remote-control-server/web/dist/assets/{ShareLanding-CJQURPqs.js → ShareLanding-CyNQfq4N.js} +1 -1
  100. package/packages/remote-control-server/web/dist/assets/{TeamDetail-BTbWxeki.js → TeamDetail-4aZd9y8I.js} +3 -3
  101. package/packages/remote-control-server/web/dist/assets/TeamList-Cs6JQa7m.js +1 -0
  102. package/packages/remote-control-server/web/dist/assets/{TeamSettings-CmUq3hLc.js → TeamSettings-DX0MfIJy.js} +1 -1
  103. package/{dist/rcs-web/assets/UserSearchInput-C8H64lVR.js → packages/remote-control-server/web/dist/assets/UserSearchInput-CyhqVZCc.js} +2 -2
  104. package/packages/remote-control-server/web/dist/assets/{UserSettings-BEIlh9kd.js → UserSettings-CsFYao6k.js} +1 -1
  105. package/packages/remote-control-server/web/dist/assets/{arc-BtitZIgo.js → arc-BbFYStVr.js} +1 -1
  106. package/{dist/rcs-web/assets/architectureDiagram-3BPJPVTR-B5sR9G2-.js → packages/remote-control-server/web/dist/assets/architectureDiagram-3BPJPVTR-BrraS5HV.js} +1 -1
  107. package/packages/remote-control-server/web/dist/assets/{blockDiagram-GPEHLZMM-5cF13FZT.js → blockDiagram-GPEHLZMM-BSrrZzGd.js} +1 -1
  108. package/packages/remote-control-server/web/dist/assets/{c4Diagram-AAUBKEIU-Blp83HZs.js → c4Diagram-AAUBKEIU-BwIi-MY-.js} +1 -1
  109. package/packages/remote-control-server/web/dist/assets/channel-D9MN_Xoy.js +1 -0
  110. package/packages/remote-control-server/web/dist/assets/{chunk-2J33WTMH-nAF6ry-x.js → chunk-2J33WTMH-RF5WXSdc.js} +1 -1
  111. package/packages/remote-control-server/web/dist/assets/{chunk-4BX2VUAB-B_YEQwMM.js → chunk-4BX2VUAB-HD-9lc81.js} +1 -1
  112. package/packages/remote-control-server/web/dist/assets/{chunk-55IACEB6-DWgWeTMt.js → chunk-55IACEB6-DORDCTWG.js} +1 -1
  113. package/{dist/rcs-web/assets/chunk-727SXJPM-lfm6jXAu.js → packages/remote-control-server/web/dist/assets/chunk-727SXJPM-BgEvck_h.js} +1 -1
  114. package/{dist/rcs-web/assets/chunk-AQP2D5EJ-CWnhAZ9O.js → packages/remote-control-server/web/dist/assets/chunk-AQP2D5EJ-CYDKpO5q.js} +1 -1
  115. package/packages/remote-control-server/web/dist/assets/{chunk-FMBD7UC4-QBtdnQIp.js → chunk-FMBD7UC4-HTfaOp-P.js} +1 -1
  116. package/packages/remote-control-server/web/dist/assets/{chunk-ND2GUHAM-YUuihu7V.js → chunk-ND2GUHAM-C7j1dy_M.js} +1 -1
  117. package/packages/remote-control-server/web/dist/assets/{chunk-QZHKN3VN-CegaWivs.js → chunk-QZHKN3VN-DrNt3GZ4.js} +1 -1
  118. package/packages/remote-control-server/web/dist/assets/classDiagram-4FO5ZUOK-C7FZfsl-.js +1 -0
  119. package/packages/remote-control-server/web/dist/assets/classDiagram-v2-Q7XG4LA2-C7FZfsl-.js +1 -0
  120. package/packages/remote-control-server/web/dist/assets/{code-block-IT6T5CEO-D2n4Ga2v.js → code-block-IT6T5CEO-qOs_ie5D.js} +1 -1
  121. package/packages/remote-control-server/web/dist/assets/{copy-Dt0a6XCD.js → copy-LeFUX09K.js} +1 -1
  122. package/{dist/rcs-web/assets/cose-bilkent-S5V4N54A-D3tF664q.js → packages/remote-control-server/web/dist/assets/cose-bilkent-S5V4N54A-CNYjbdwx.js} +1 -1
  123. package/packages/remote-control-server/web/dist/assets/{dagre-BM42HDAG-Ba9POJgR.js → dagre-BM42HDAG-CzF1zU8o.js} +1 -1
  124. package/packages/remote-control-server/web/dist/assets/{diagram-2AECGRRQ-CZAcdfXD.js → diagram-2AECGRRQ-BOYW474q.js} +1 -1
  125. package/packages/remote-control-server/web/dist/assets/{diagram-5GNKFQAL-DO4nXgzG.js → diagram-5GNKFQAL-CP-yWCBy.js} +1 -1
  126. package/{dist/rcs-web/assets/diagram-KO2AKTUF-BDK3PG7v.js → packages/remote-control-server/web/dist/assets/diagram-KO2AKTUF-DdqQ4pAJ.js} +1 -1
  127. package/packages/remote-control-server/web/dist/assets/{diagram-LMA3HP47-DYXmhnhQ.js → diagram-LMA3HP47-CE2gGIRy.js} +1 -1
  128. package/packages/remote-control-server/web/dist/assets/{diagram-OG6HWLK6-CLarvguU.js → diagram-OG6HWLK6-BNA49_sd.js} +1 -1
  129. package/packages/remote-control-server/web/dist/assets/dialog-DnbWz68R.js +1 -0
  130. package/packages/remote-control-server/web/dist/assets/{erDiagram-TEJ5UH35-D4zryVmf.js → erDiagram-TEJ5UH35-DVflh1jg.js} +1 -1
  131. package/{dist/rcs-web/assets/flowDiagram-I6XJVG4X-C55CpRnZ.js → packages/remote-control-server/web/dist/assets/flowDiagram-I6XJVG4X-B8b91Tm9.js} +1 -1
  132. package/{dist/rcs-web/assets/ganttDiagram-6RSMTGT7-a33rVx18.js → packages/remote-control-server/web/dist/assets/ganttDiagram-6RSMTGT7-7fEdykwc.js} +1 -1
  133. package/{dist/rcs-web/assets/gitGraphDiagram-PVQCEYII-CdeFuha2.js → packages/remote-control-server/web/dist/assets/gitGraphDiagram-PVQCEYII-B_17h1CU.js} +1 -1
  134. package/packages/remote-control-server/web/dist/assets/{infoDiagram-5YYISTIA-CkgCIBPN.js → infoDiagram-5YYISTIA-DWa7j6Zg.js} +1 -1
  135. package/packages/remote-control-server/web/dist/assets/{ishikawaDiagram-YF4QCWOH-IMWeHd6c.js → ishikawaDiagram-YF4QCWOH-b11b1c8I.js} +1 -1
  136. package/{dist/rcs-web/assets/journeyDiagram-JHISSGLW-BW_NwQ4x.js → packages/remote-control-server/web/dist/assets/journeyDiagram-JHISSGLW-CsvW9Ud9.js} +1 -1
  137. package/{dist/rcs-web/assets/kanban-definition-UN3LZRKU-BEYl8Usi.js → packages/remote-control-server/web/dist/assets/kanban-definition-UN3LZRKU-B97kXWdO.js} +1 -1
  138. package/packages/remote-control-server/web/dist/assets/{linear-Di8Hsx3R.js → linear-CrAR73-K.js} +1 -1
  139. package/packages/remote-control-server/web/dist/assets/main-BOI1Ucfk.css +1 -0
  140. package/packages/remote-control-server/web/dist/assets/{main-BkfSO2Rz.js → main-CDaRKeiT.js} +24 -24
  141. package/{dist/rcs-web/assets/mermaid-VLURNSYL-Alki8AJh.js → packages/remote-control-server/web/dist/assets/mermaid-VLURNSYL-gQdmHkjr.js} +4 -4
  142. package/packages/remote-control-server/web/dist/assets/{mermaid.core-CPLRyRun.js → mermaid.core-DTuGObIu.js} +5 -5
  143. package/{dist/rcs-web/assets/mindmap-definition-RKZ34NQL-DzkpJBE2.js → packages/remote-control-server/web/dist/assets/mindmap-definition-RKZ34NQL-wGG267Yb.js} +1 -1
  144. package/packages/remote-control-server/web/dist/assets/{notifications-V4HNWkys.js → notifications-Ms9MI-nO.js} +1 -1
  145. package/packages/remote-control-server/web/dist/assets/{pieDiagram-4H26LBE5-BcvVbbf5.js → pieDiagram-4H26LBE5-DgayJQKV.js} +1 -1
  146. package/packages/remote-control-server/web/dist/assets/{quadrantDiagram-W4KKPZXB-DTIciStr.js → quadrantDiagram-W4KKPZXB-BOtyjbOc.js} +1 -1
  147. package/packages/remote-control-server/web/dist/assets/{refresh-cw-DPCoOD18.js → refresh-cw-Dc5tn8Z_.js} +1 -1
  148. package/{dist/rcs-web/assets/requirementDiagram-4Y6WPE33-Dilpse2A.js → packages/remote-control-server/web/dist/assets/requirementDiagram-4Y6WPE33-Ck-a8POo.js} +1 -1
  149. package/{dist/rcs-web/assets/sankeyDiagram-5OEKKPKP-DsBacA7d.js → packages/remote-control-server/web/dist/assets/sankeyDiagram-5OEKKPKP-DR0OBykc.js} +1 -1
  150. package/{dist/rcs-web/assets/sequenceDiagram-3UESZ5HK-C_USxpgF.js → packages/remote-control-server/web/dist/assets/sequenceDiagram-3UESZ5HK-DFOP0Bxr.js} +1 -1
  151. package/packages/remote-control-server/web/dist/assets/{stateDiagram-AJRCARHV-ClUhzFvq.js → stateDiagram-AJRCARHV-DF9rQs3c.js} +1 -1
  152. package/packages/remote-control-server/web/dist/assets/{stateDiagram-v2-BHNVJYJU-dRIOwebj.js → stateDiagram-v2-BHNVJYJU-Zl4Zj4zN.js} +1 -1
  153. package/packages/remote-control-server/web/dist/assets/{timeline-definition-PNZ67QCA-BH8TVQ46.js → timeline-definition-PNZ67QCA-C3MtsV-F.js} +1 -1
  154. package/packages/remote-control-server/web/dist/assets/{vennDiagram-CIIHVFJN-BtRNizK-.js → vennDiagram-CIIHVFJN-DP7wVqlq.js} +1 -1
  155. package/packages/remote-control-server/web/dist/assets/{wardleyDiagram-YWT4CUSO-BW1rj4A0.js → wardleyDiagram-YWT4CUSO-DxAqIThI.js} +1 -1
  156. package/{dist/rcs-web/assets/workerType-CS6pd4nT.js → packages/remote-control-server/web/dist/assets/workerType-CR0nPOQn.js} +1 -1
  157. package/packages/remote-control-server/web/dist/assets/{xychartDiagram-2RQKCTM6-JsSvd6FU.js → xychartDiagram-2RQKCTM6-n7XBFulh.js} +1 -1
  158. package/packages/remote-control-server/web/dist/index.html +2 -2
  159. package/packages/remote-control-server/web/dist/saluzi-icon.png +0 -0
  160. package/dist/rcs-web/assets/ArtifactView-gUzyHJ7q.js +0 -1
  161. package/dist/rcs-web/assets/Dashboard-B6D1a9t5.js +0 -2
  162. package/dist/rcs-web/assets/Join-CEirdone.js +0 -1
  163. package/dist/rcs-web/assets/Login-Ddl_jJu7.js +0 -1
  164. package/dist/rcs-web/assets/MemoriesPage-Dh0nr4m_.js +0 -1
  165. package/dist/rcs-web/assets/Register-Dk25q6g8.js +0 -1
  166. package/dist/rcs-web/assets/SessionVisibilityBadge-CtjTB48N.js +0 -16
  167. package/dist/rcs-web/assets/Setup-Ce4opwTt.js +0 -1
  168. package/dist/rcs-web/assets/TeamList-DRzBptgs.js +0 -1
  169. package/dist/rcs-web/assets/channel-QeSvbFDN.js +0 -1
  170. package/dist/rcs-web/assets/classDiagram-4FO5ZUOK-BrYok7tm.js +0 -1
  171. package/dist/rcs-web/assets/classDiagram-v2-Q7XG4LA2-BrYok7tm.js +0 -1
  172. package/dist/rcs-web/assets/dialog-8nXjsFEb.js +0 -1
  173. package/dist/rcs-web/assets/main-C8p_H8IX.css +0 -1
  174. package/packages/remote-control-server/web/dist/assets/ArtifactView-gUzyHJ7q.js +0 -1
  175. package/packages/remote-control-server/web/dist/assets/Dashboard-B6D1a9t5.js +0 -2
  176. package/packages/remote-control-server/web/dist/assets/Join-CEirdone.js +0 -1
  177. package/packages/remote-control-server/web/dist/assets/Login-Ddl_jJu7.js +0 -1
  178. package/packages/remote-control-server/web/dist/assets/MemoriesPage-Dh0nr4m_.js +0 -1
  179. package/packages/remote-control-server/web/dist/assets/Register-Dk25q6g8.js +0 -1
  180. package/packages/remote-control-server/web/dist/assets/SessionVisibilityBadge-CtjTB48N.js +0 -16
  181. package/packages/remote-control-server/web/dist/assets/Setup-Ce4opwTt.js +0 -1
  182. package/packages/remote-control-server/web/dist/assets/TeamList-DRzBptgs.js +0 -1
  183. package/packages/remote-control-server/web/dist/assets/channel-QeSvbFDN.js +0 -1
  184. package/packages/remote-control-server/web/dist/assets/classDiagram-4FO5ZUOK-BrYok7tm.js +0 -1
  185. package/packages/remote-control-server/web/dist/assets/classDiagram-v2-Q7XG4LA2-BrYok7tm.js +0 -1
  186. package/packages/remote-control-server/web/dist/assets/dialog-8nXjsFEb.js +0 -1
  187. package/packages/remote-control-server/web/dist/assets/main-C8p_H8IX.css +0 -1
@@ -1,83 +1,78 @@
1
- var nr=Object.defineProperty;var rr=(r,t,s)=>t in r?nr(r,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[t]=s;var F=(r,t,s)=>rr(r,typeof t!="symbol"?t+"":t,s);import{j as e,e as o}from"./vendor-DE_-CLIE.js";import{aH as ae,am as ar,aP as Es,aO as Ts,aX as i,aR as ir,aQ as kt,aJ as hn,aK as or,aY as K,aM as Me,aA as lr,az as le,ap as cr,aw as dr,a_ as ur,b1 as me,T as mr,Y as xr,$ as Ze,L as st,N as pr,Q as hr,i as Ms,aL as fr,J as fn,W as yr,aI as St,e as Wt,S as et,M as gr,G as br,aF as yn,aS as gn,u as jr,c as wr,v as vr,t as kr,aq as Nr,a6 as Sr,av as _r,b2 as Cr,ai as bn,ag as Er,ae as Tr,ax as Mr,as as Rr,P as Ar,w as Ir,B as Lt,a4 as Pr,A as Dr,aN as qr,aT as $r,aV as Fr,aj as Or,a2 as Rs,a5 as Ur,aZ as Lr,b as Kr,a9 as As,aU as Br,at as Hr,V as jn,F as Is,m as Ps,r as Ds,n as qs,o as ue,d as Qr,K as Wr,C as zr,al as $s,l as Gr,a as Yr,x as zt,z as Gt,I as Vr,g as Yt,f as Vt,y as Jt,s as Jr}from"./main-BkfSO2Rz.js";import{A as Xr,g as wn,C as $t}from"./workerType-CS6pd4nT.js";import{D as ke,a as Ne,d as Re,e as Se,b as Fs,c as Zr}from"./dialog-8nXjsFEb.js";import{F as ea,S as ta}from"./SessionVisibilityBadge-CtjTB48N.js";import{R as sa}from"./refresh-cw-DPCoOD18.js";import{A as na,U as ra}from"./UserSearchInput-C8H64lVR.js";import{C as aa}from"./copy-Dt0a6XCD.js";import{S as ia,A as oa}from"./ArtifactsGallery-CpLh8gO6.js";import{D as Ft,u as la,d as ca,e as da,i as ua,F as Os,c as ma,b as xa,T as pa,h as Us,a as ha,M as fa}from"./MemoryTypeChips-DL1Uf2db.js";import{S as ya,b as ga}from"./notifications-V4HNWkys.js";import"./preload-helper-BiaRt2Oj.js";import"./motion-BILbV7YQ.js";/**
1
+ var nr=Object.defineProperty;var rr=(r,t,s)=>t in r?nr(r,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[t]=s;var F=(r,t,s)=>rr(r,typeof t!="symbol"?t+"":t,s);import{j as e,e as o}from"./vendor-DE_-CLIE.js";import{aQ as ie,av as ar,aY as Es,aX as Ts,b4 as i,a_ as ir,aZ as kt,aS as hn,aT as or,b5 as K,aV as Me,aJ as lr,aI as le,ay as cr,aF as dr,b7 as ur,ba as me,Z as mr,a3 as xr,a7 as Ze,L as st,X as pr,Y as hr,i as Ms,aU as fr,V as fn,a0 as yr,aR as St,e as Wt,S as et,M as gr,Q as br,aO as yn,a$ as gn,x as jr,c as wr,y as vr,w as kr,az as Nr,af as Sr,aE as _r,bb as Cr,ar as bn,ap as Er,an as Tr,aG as Mr,aB as Rr,P as Ar,z as Ir,B as Lt,ad as Pr,A as Dr,aW as qr,b0 as $r,b2 as Fr,as as Or,ab as Rs,ae as Ur,b6 as Lr,b as Kr,ai as As,b1 as Br,aC as Hr,$ as jn,F as Is,n as Ps,s as Ds,o as qs,p as ue,d as Qr,W as Wr,C as Gr,au as $s,m as zr,a as Yr,E as Gt,H as zt,U as Vr,g as Yt,f as Vt,G as Jt,v as Jr}from"./main-CDaRKeiT.js";import{A as Xr,g as wn,C as $t}from"./workerType-CR0nPOQn.js";import{D as ke,a as Ne,d as Re,e as Se,b as Fs,c as Zr}from"./dialog-DnbWz68R.js";import{F as ea,C as ta,S as sa}from"./SessionVisibilityBadge-D6XUIJa4.js";import{R as na}from"./refresh-cw-Dc5tn8Z_.js";import{A as ra,U as aa}from"./UserSearchInput-CyhqVZCc.js";import{C as ia}from"./copy-LeFUX09K.js";import{S as oa,A as la}from"./ArtifactsGallery-BSdlASB3.js";import{D as Ft,u as ca,d as da,e as ua,i as ma,F as Os,c as xa,b as pa,T as ha,h as Us,a as fa,M as ya}from"./MemoryTypeChips-BFl2a9Tv.js";import{S as ga,b as ba}from"./notifications-Ms9MI-nO.js";import"./preload-helper-BiaRt2Oj.js";import"./motion-BILbV7YQ.js";/**
2
2
  * @license lucide-react v0.555.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
5
5
  * See the LICENSE file in the root directory of this source tree.
6
- */const ba=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ja=ae("chevron-right",ba);/**
6
+ */const ja=[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]],wa=ie("coins",ja);/**
7
7
  * @license lucide-react v0.555.0 - ISC
8
8
  *
9
9
  * This source code is licensed under the ISC license.
10
10
  * See the LICENSE file in the root directory of this source tree.
11
- */const wa=[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]],va=ae("coins",wa);/**
11
+ */const va=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],vn=ie("cpu",va);/**
12
12
  * @license lucide-react v0.555.0 - ISC
13
13
  *
14
14
  * This source code is licensed under the ISC license.
15
15
  * See the LICENSE file in the root directory of this source tree.
16
- */const ka=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],vn=ae("cpu",ka);/**
16
+ */const ka=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Ls=ie("ellipsis",ka);/**
17
17
  * @license lucide-react v0.555.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const Na=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Ls=ae("ellipsis",Na);/**
21
+ */const Na=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Ks=ie("gauge",Na);/**
22
22
  * @license lucide-react v0.555.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */const Sa=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Ks=ae("gauge",Sa);/**
26
+ */const Sa=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],_a=ie("hash",Sa);/**
27
27
  * @license lucide-react v0.555.0 - ISC
28
28
  *
29
29
  * This source code is licensed under the ISC license.
30
30
  * See the LICENSE file in the root directory of this source tree.
31
- */const _a=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],Ca=ae("hash",_a);/**
31
+ */const Ca=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Ea=ie("layers",Ca);/**
32
32
  * @license lucide-react v0.555.0 - ISC
33
33
  *
34
34
  * This source code is licensed under the ISC license.
35
35
  * See the LICENSE file in the root directory of this source tree.
36
- */const Ea=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Ta=ae("layers",Ea);/**
36
+ */const Ta=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],Bs=ie("lightbulb",Ta);/**
37
37
  * @license lucide-react v0.555.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const Ma=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],Bs=ae("lightbulb",Ma);/**
41
+ */const Ma=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["rect",{x:"3",y:"4",width:"6",height:"6",rx:"1",key:"cif1o7"}]],Hs=ie("list-todo",Ma);/**
42
42
  * @license lucide-react v0.555.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const Ra=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["rect",{x:"3",y:"4",width:"6",height:"6",rx:"1",key:"cif1o7"}]],Hs=ae("list-todo",Ra);/**
46
+ */const Ra=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Kt=ie("message-circle-question-mark",Ra);/**
47
47
  * @license lucide-react v0.555.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const Aa=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Kt=ae("message-circle-question-mark",Aa);/**
51
+ */const Aa=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],Ia=ie("play",Aa);/**
52
52
  * @license lucide-react v0.555.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const Ia=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],Pa=ae("play",Ia);/**
56
+ */const Pa=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]],Bt=ie("plug",Pa);/**
57
57
  * @license lucide-react v0.555.0 - ISC
58
58
  *
59
59
  * This source code is licensed under the ISC license.
60
60
  * See the LICENSE file in the root directory of this source tree.
61
- */const Da=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]],Bt=ae("plug",Da);/**
61
+ */const Da=[["path",{d:"m10.852 14.772-.383.923",key:"11vil6"}],["path",{d:"M13.148 14.772a3 3 0 1 0-2.296-5.544l-.383-.923",key:"1v3clb"}],["path",{d:"m13.148 9.228.383-.923",key:"t2zzyc"}],["path",{d:"m13.53 15.696-.382-.924a3 3 0 1 1-2.296-5.544",key:"1bxfiv"}],["path",{d:"m14.772 10.852.923-.383",key:"k9m8cz"}],["path",{d:"m14.772 13.148.923.383",key:"1xvhww"}],["path",{d:"M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5",key:"tn8das"}],["path",{d:"M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5",key:"1g2pve"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"m9.228 10.852-.923-.383",key:"1wtb30"}],["path",{d:"m9.228 13.148-.923.383",key:"1a830x"}]],qa=ie("server-cog",Da);/**
62
62
  * @license lucide-react v0.555.0 - ISC
63
63
  *
64
64
  * This source code is licensed under the ISC license.
65
65
  * See the LICENSE file in the root directory of this source tree.
66
- */const qa=[["path",{d:"m10.852 14.772-.383.923",key:"11vil6"}],["path",{d:"M13.148 14.772a3 3 0 1 0-2.296-5.544l-.383-.923",key:"1v3clb"}],["path",{d:"m13.148 9.228.383-.923",key:"t2zzyc"}],["path",{d:"m13.53 15.696-.382-.924a3 3 0 1 1-2.296-5.544",key:"1bxfiv"}],["path",{d:"m14.772 10.852.923-.383",key:"k9m8cz"}],["path",{d:"m14.772 13.148.923.383",key:"1xvhww"}],["path",{d:"M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5",key:"tn8das"}],["path",{d:"M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5",key:"1g2pve"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"m9.228 10.852-.923-.383",key:"1wtb30"}],["path",{d:"m9.228 13.148-.923.383",key:"1a830x"}]],$a=ae("server-cog",qa);/**
66
+ */const $a=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],Ht=ie("settings-2",$a);/**
67
67
  * @license lucide-react v0.555.0 - ISC
68
68
  *
69
69
  * This source code is licensed under the ISC license.
70
70
  * See the LICENSE file in the root directory of this source tree.
71
- */const Fa=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],Ht=ae("settings-2",Fa);/**
72
- * @license lucide-react v0.555.0 - ISC
73
- *
74
- * This source code is licensed under the ISC license.
75
- * See the LICENSE file in the root directory of this source tree.
76
- */const Oa=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],Qs=ae("share-2",Oa);function Qt(){return{tasks:{}}}const Ws=3e4;function bt(r){const t=r.trim();if(!t)return"agent";const s=t.split(/\s+/).slice(0,2).join(" ");return s.length>40?s.slice(0,40)+"…":s}function zs(r,t){var c,u,y,f,j,_,E,T,A,N,q,P;const s=t.subtype;if(s!=="task_started"&&s!=="task_progress"&&s!=="task_notification")return r;const n=t.task_id;if(!n)return r;const l=Date.now(),d=r.tasks[n];if(s==="task_started"){if(d)return{tasks:{...r.tasks,[n]:{...d,description:t.description??d.description,name:bt(t.description??d.description),taskType:t.task_type??d.taskType,workflowName:t.workflow_name??d.workflowName,prompt:t.prompt??d.prompt,toolUseId:t.tool_use_id??d.toolUseId,status:"running",startTime:l,evictAfter:void 0}}};const I=t.description??"";return{tasks:{...r.tasks,[n]:{taskId:n,name:bt(I),description:I,taskType:t.task_type,workflowName:t.workflow_name,prompt:t.prompt,toolUseId:t.tool_use_id,status:"running",startTime:l}}}}if(s==="task_progress"){if(!d){const I=t.description??"";return{tasks:{...r.tasks,[n]:{taskId:n,name:bt(I),description:I,toolUseId:t.tool_use_id,status:"running",startTime:l,tokenCount:(c=t.usage)==null?void 0:c.total_tokens,toolUseCount:(u=t.usage)==null?void 0:u.tool_uses,durationMs:(y=t.usage)==null?void 0:y.duration_ms,lastToolName:t.last_tool_name,summary:t.summary}}}}return{tasks:{...r.tasks,[n]:{...d,description:t.description??d.description,tokenCount:((f=t.usage)==null?void 0:f.total_tokens)??d.tokenCount,toolUseCount:((j=t.usage)==null?void 0:j.tool_uses)??d.toolUseCount,durationMs:((_=t.usage)==null?void 0:_.duration_ms)??d.durationMs,lastToolName:t.last_tool_name??d.lastToolName,summary:t.summary??d.summary}}}}return d?{tasks:{...r.tasks,[n]:{...d,status:t.status??"completed",endTime:l,finalSummary:t.summary??d.finalSummary,outputFile:t.output_file??d.outputFile,tokenCount:((N=t.usage)==null?void 0:N.total_tokens)??d.tokenCount,toolUseCount:((q=t.usage)==null?void 0:q.tool_uses)??d.toolUseCount,durationMs:((P=t.usage)==null?void 0:P.duration_ms)??d.durationMs,evictAfter:l+Ws}}}:{tasks:{...r.tasks,[n]:{taskId:n,name:bt(t.summary??""),description:t.summary??"",status:t.status??"completed",startTime:l,endTime:l,finalSummary:t.summary,outputFile:t.output_file,tokenCount:(E=t.usage)==null?void 0:E.total_tokens,toolUseCount:(T=t.usage)==null?void 0:T.tool_uses,durationMs:(A=t.usage)==null?void 0:A.duration_ms,evictAfter:l+Ws}}}}function Ua(r,t=Date.now()){return Object.values(r.tasks).filter(s=>s.evictAfter===void 0||s.evictAfter>t).sort((s,n)=>s.startTime-n.startTime)}const Gs={in_process_teammate:0,local_bash:1,monitor_mcp:2,remote_agent:3,local_agent:4,dream:5},Ys=100;function La(r){const t=new Map;for(const s of r){const n=s.taskType??"",l=t.get(n);l?l.push(s):t.set(n,[s])}return[...t.entries()].sort(([s],[n])=>{const l=Gs[s]??Ys,d=Gs[n]??Ys;return l===d?s.localeCompare(n):l-d}).map(([s,n])=>({taskType:s,tasks:[...n].sort((l,d)=>l.startTime-d.startTime)}))}function Vs(r){const t=r.raw,s=t&&typeof t=="object"?t:r,n=typeof s.subtype=="string"?s.subtype:void 0;return n!=="task_started"&&n!=="task_progress"&&n!=="task_notification"?null:{subtype:n,task_id:typeof s.task_id=="string"?s.task_id:void 0,tool_use_id:typeof s.tool_use_id=="string"?s.tool_use_id:void 0,description:typeof s.description=="string"?s.description:void 0,task_type:typeof s.task_type=="string"?s.task_type:void 0,workflow_name:typeof s.workflow_name=="string"?s.workflow_name:void 0,prompt:typeof s.prompt=="string"?s.prompt:void 0,usage:s.usage&&typeof s.usage=="object"?s.usage:void 0,last_tool_name:typeof s.last_tool_name=="string"?s.last_tool_name:void 0,summary:typeof s.summary=="string"?s.summary:void 0,status:s.status==="completed"||s.status==="failed"||s.status==="stopped"?s.status:void 0,output_file:typeof s.output_file=="string"?s.output_file:void 0}}function Ka(r){if(!r||typeof r!="object"||Array.isArray(r))return null;const t=r,s={file_search:t.file_search===!0,clear:t.clear===!0,set_max_thinking_tokens:t.set_max_thinking_tokens===!0,get_context_usage:t.get_context_usage===!0,stop_task:t.stop_task===!0,set_model:t.set_model===!0,set_permission_mode:t.set_permission_mode===!0,interrupt:t.interrupt===!0,end_session:t.end_session===!0,mcp_management:t.mcp_management===!0,remote_settings:t.remote_settings===!0,rewind:t.rewind===!0,resume:t.resume===!0,set_effort:t.set_effort===!0,set_token_mode:t.set_token_mode===!0,side_question:t.side_question===!0};return Object.values(s).some(Boolean)?s:null}function Js(r,t){const s=[];if(Array.isArray(r)){for(const n of r){if(!n||typeof n!="object")continue;const l=n;if(typeof l.name!="string"||!l.name)continue;const d=l.type==="prompt"||l.type==="local"||l.type==="local-jsx"?l.type:void 0;s.push({name:l.name,...typeof l.description=="string"&&l.description?{description:l.description}:{},...typeof l.argumentHint=="string"&&l.argumentHint?{argumentHint:l.argumentHint}:{},...d?{type:d}:{}})}if(s.length>0)return s}if(Array.isArray(t))for(const n of t)typeof n=="string"&&n&&s.push({name:n});return s}function Xs(r){const t=r.raw&&typeof r.raw=="object"&&!Array.isArray(r.raw)?r.raw:r,s=Js(t.slash_command_details??r.slash_command_details,t.slash_commands??r.slash_commands),n=Js(t.skill_details??r.skill_details,t.skills??r.skills),l=Ka(t.remote_capabilities??r.remote_capabilities);return s.length===0&&n.length===0&&!l?null:{commands:s,skills:n,capabilities:l}}class Ba{constructor(t){F(this,"listeners",new Set);F(this,"stateListeners",new Set);F(this,"eventSource",null);F(this,"sessionId",null);F(this,"_lastSeqNum",0);F(this,"lastFrameAt",0);F(this,"firstEventAfterOpen",!1);F(this,"watchdogTimer",null);F(this,"visibilityHandler",null);F(this,"reconnectTimer",null);F(this,"reconnectAttempts",0);F(this,"_state","idle");F(this,"opts");this.opts={stallThresholdMs:45e3,watchdogTickMs:5e3,reconnectBaseDelayMs:1e3,reconnectMaxDelayMs:15e3,maxReconnectAttempts:6,...t}}get state(){return this._state}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}onStateChange(t){return this.stateListeners.add(t),()=>this.stateListeners.delete(t)}connect(t){this.stopReconnectTimer(),this.reconnectAttempts=0,this.sessionId=t,this.openStream()}openStream(){if(this.closeStream(),!this.sessionId)return;this.setState("connecting");const t=this._lastSeqNum>0?`/web/sessions/${this.sessionId}/events?fromSeqNum=${this._lastSeqNum}`:`/web/sessions/${this.sessionId}/events`,s=new EventSource(t,{withCredentials:!0});this.eventSource=s,this.lastFrameAt=Date.now(),this.firstEventAfterOpen=!0,s.addEventListener("open",()=>{this.lastFrameAt=Date.now(),this.reconnectAttempts=0,this.firstEventAfterOpen=!0,this.setState("open")}),s.addEventListener("ping",()=>{this.lastFrameAt=Date.now()}),s.addEventListener("message",n=>{this.lastFrameAt=Date.now();try{const l=JSON.parse(n.data);if(this.firstEventAfterOpen&&(this.firstEventAfterOpen=!1,typeof l.seqNum=="number"&&l.seqNum<this._lastSeqNum&&(this._lastSeqNum=l.seqNum-1,this.notifyResync())),l.seqNum!==void 0&&l.seqNum<=this._lastSeqNum)return;l.seqNum!==void 0&&(this._lastSeqNum=l.seqNum);for(const d of this.listeners)d(l)}catch{}}),s.addEventListener("error",()=>{s.readyState===EventSource.CLOSED&&this.scheduleReconnect()}),this.startWatchdog()}disconnect(){this.sessionId=null,this.stopReconnectTimer(),this.closeStream(),this._lastSeqNum=0,this.reconnectAttempts=0,this.setState("idle")}closeStream(){this.stopWatchdog(),this.eventSource&&(this.eventSource.close(),this.eventSource=null)}startWatchdog(){this.stopWatchdog(),this.watchdogTimer=setInterval(()=>{this.probeStall()},this.opts.watchdogTickMs),typeof document<"u"&&(this.visibilityHandler=()=>{document.visibilityState==="visible"&&this.probeStall()},document.addEventListener("visibilitychange",this.visibilityHandler))}probeStall(){const t=this.eventSource;!t||t.readyState!==EventSource.OPEN||Date.now()-this.lastFrameAt<=this.opts.stallThresholdMs||this.scheduleReconnect()}stopWatchdog(){this.watchdogTimer&&(clearInterval(this.watchdogTimer),this.watchdogTimer=null),this.visibilityHandler&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null)}stopReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}scheduleReconnect(){if(this.reconnectTimer||!this.sessionId)return;if(this.closeStream(),this.reconnectAttempts++,this.reconnectAttempts>this.opts.maxReconnectAttempts){this.setState("failed");return}this.setState("reconnecting");const t=Math.min(this.opts.reconnectBaseDelayMs*2**(this.reconnectAttempts-1),this.opts.reconnectMaxDelayMs),s=Math.max(0,t+t*.25*(2*Math.random()-1));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.reconnect()},s)}async reconnect(){this.sessionId&&(await ur(),this.sessionId&&this.openStream())}setState(t){if(this._state!==t){this._state=t;for(const s of this.stateListeners)s(t,{})}}notifyResync(){for(const t of this.stateListeners)t(this._state,{resync:!0})}}const xe=new Ba;function Ot(r){if(typeof r.content=="string")return r.content;if(r.message&&typeof r.message=="object"){const t=r.message;if(typeof t.content=="string")return t.content;if(Array.isArray(t.content))return t.content.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}return""}function Zs(r,t){for(let s=r.length-1;s>=0;s--){const n=r[s];if(n&&n.type==="tool_call"&&n.toolCall.id===t)return s}return-1}const Ut="streaming-";function en(r){const t=r.message;if(!t||typeof t!="object"||!Array.isArray(t.content))return"";const s=[];for(const n of t.content)if((n==null?void 0:n.type)==="thinking"){const l=typeof n.thinking=="string"&&n.thinking||typeof n.text=="string"&&n.text||"";l&&s.push(l)}return s.join("")}function tn(r){return r.filter(t=>typeof t.subject=="string"&&t.subject).map(t=>({content:t.subject,priority:"medium",status:t.status==="completed"?"completed":t.status==="in_progress"?"in_progress":"pending"}))}function sn(r){if(!r||typeof r!="object")return"";const t=r;if(typeof t.target_event_id=="string"&&t.target_event_id)return t.target_event_id;const s=t.raw;if(s&&typeof s=="object"&&!Array.isArray(s)){const n=s.target_event_id;if(typeof n=="string"&&n)return n}return""}class Ha{constructor(t,s,n){F(this,"sessionId");F(this,"setEntries");F(this,"unsub",null);F(this,"unsubState",null);F(this,"onStatusChange");F(this,"onError");F(this,"onPermissionRequest");F(this,"onPermissionSettled");F(this,"onModelsStateChange");F(this,"onSubagentUpdate");F(this,"onControlResponse");F(this,"onPermissionModeChange");F(this,"onElicitationRequest");F(this,"onWorkerInfoChange");F(this,"onTurnStart");F(this,"subagentState",Qt());F(this,"seenUuids",new Set);F(this,"seenToolCallIds",new Set);F(this,"pendingToolCallIds",new Set);F(this,"pendingPermissionToolIds",new Map);F(this,"pendingPermissionDecisions",new Map);F(this,"settledPermissionIds",new Set);F(this,"postedUserUuids",new Set);F(this,"pendingControlRequests",new Map);F(this,"turnEnded",!1);F(this,"userSinceTurnEnd",!1);F(this,"turnStartedAt",null);F(this,"closed",!1);this.sessionId=t,this.setEntries=s,this.onStatusChange=n==null?void 0:n.onStatusChange,this.onError=n==null?void 0:n.onError,this.onPermissionRequest=n==null?void 0:n.onPermissionRequest,this.onPermissionSettled=n==null?void 0:n.onPermissionSettled,this.onModelsStateChange=n==null?void 0:n.onModelsStateChange,this.onSubagentUpdate=n==null?void 0:n.onSubagentUpdate,this.onControlResponse=n==null?void 0:n.onControlResponse,this.onPermissionModeChange=n==null?void 0:n.onPermissionModeChange,this.onElicitationRequest=n==null?void 0:n.onElicitationRequest,this.onWorkerInfoChange=n==null?void 0:n.onWorkerInfoChange,this.onTurnStart=n==null?void 0:n.onTurnStart}markClosed(){this.closed=!0}setTurnStartedAt(t){var s;this.turnStartedAt!==t&&(this.turnStartedAt=t,(s=this.onTurnStart)==null||s.call(this,t))}async init(){await this.loadHistory(),this.connectSSE()}async loadHistory(){var N,q,P,I,$,p,g;const{events:t}=await ar(this.sessionId);if(!t||t.length===0)return;const s=new Set;for(const v of t){if(v.type!=="user"||v.direction==="inbound")continue;const w=(N=v.payload)==null?void 0:N.uuid;typeof w=="string"&&w&&s.add(w)}const n=[];let l=null;const d=()=>{l&&(n.push(l),l=null)};for(const v of t){const w=v.payload||{},S=w.uuid;if(typeof S=="string"&&S&&this.seenUuids.add(S),v.type==="tool_use"){const h=w.tool_call_id;typeof h=="string"&&h&&this.seenToolCallIds.add(h)}if(v.type==="user"){if(v.direction==="inbound"){const x=w.uuid;if(typeof x!="string"||!x||s.has(x))continue}d();const h=Ot(w);h&&n.push({type:"user_message",id:v.id||`hist-user-${n.length}`,content:h})}else if(v.type==="assistant"){d();const h=Ot(w);if(Es(h))continue;const x=en(w),M=[],U=w.message;if(U&&typeof U=="object"&&Array.isArray(U.content)){for(const X of U.content)if(X.type==="tool_use"){const se=X.id;se&&this.seenToolCallIds.add(se),M.push({type:"tool_call",toolCall:{id:se||`hist-tool-${n.length}`,title:X.name||"tool",status:"complete",rawInput:X.input||{}}})}}if(h||x||M.length>0){l={type:"assistant_message",id:v.id||`hist-asst-${n.length}`,chunks:[...x?[{type:"thought",text:x}]:[],...h?[{type:"message",text:h}]:[]]},n.push(l);for(const X of M)n.push(X);l=null}}else if(v.type==="conversation_rewound"){const h=sn(w);if(h){const x=n.findIndex(M=>Ts(M)===h);x>=0&&(n.length=x)}}else if(v.type==="tool_use"){const h=w,x={type:"tool_call",toolCall:{id:h.tool_call_id||`hist-tool-${n.length}`,title:h.tool_name||"tool",status:"complete",rawInput:h.tool_input||{}}};n.push(x)}else if(v.type==="tool_result"){const h=w,x=Zs(n,h.tool_call_id||"");if(x>=0){const M=n[x];n[x]={type:"tool_call",toolCall:{...M.toolCall,rawOutput:{output:h.content||h.output||""}}}}}}d();let c=null;for(const v of t){if(v.type!=="task_state")continue;const w=v.payload||{};Array.isArray(w.tasks)&&(c=w.tasks)}if(c&&c.length>0){const v=tn(c);v.length>0&&n.push({type:"plan",id:`plan-hist-${Date.now()}`,entries:v})}this.pendingToolCallIds.clear(),this.pendingPermissionToolIds.clear(),this.pendingPermissionDecisions.clear(),this.setEntries(n);let u=null,y=null,f=null,j=null,_=0,E=0;for(const v of t){const w=v.payload||{};if(typeof v.createdAt=="number"&&(v.createdAt>E&&(E=v.createdAt),v.type==="user"&&j!=="user"&&v.createdAt>0&&(_=v.createdAt)),v.type==="user"?j="user":(v.type==="result"||v.type==="result_success"||v.type==="interrupt")&&(j="turn_end"),v.type==="system"&&(w.subtype==="init"||((q=w.raw)==null?void 0:q.subtype)==="init")&&(y=Xs(w)),v.type==="models_state"){const S=w.raw,h=S&&typeof S=="object"?S.models_state:w.models_state;h&&Array.isArray(h.availableModels)&&typeof h.currentModelId=="string"&&(u=h)}if(v.type==="system"){const S=w.raw,h=typeof w.permissionMode=="string"?w.permissionMode:typeof(S==null?void 0:S.permissionMode)=="string"?S.permissionMode:null;h&&(f=h)}}let T=!1,A=Qt();for(const v of t){if(v.type!=="system")continue;const w=Vs(v.payload||{});w&&(A=zs(A,w),T=!0)}T&&(this.subagentState=A,(P=this.onSubagentUpdate)==null||P.call(this,this.subagentState)),u&&((I=this.onModelsStateChange)==null||I.call(this,u)),y&&(($=this.onWorkerInfoChange)==null||$.call(this,y)),f&&((p=this.onPermissionModeChange)==null||p.call(this,f)),this.turnEnded=j==="turn_end",this.userSinceTurnEnd=j==="user",this.setTurnStartedAt(!this.closed&&j==="user"&&_>0&&E>=_?Date.now()-(E-_):null),this.turnEnded&&!this.closed&&((g=this.onStatusChange)==null||g.call(this,"idle"))}connectSSE(){xe.connect(this.sessionId),this.unsub=xe.onEvent(t=>this.handleEvent(t)),this.unsubState=xe.onStateChange((t,s)=>{s.resync&&!this.closed&&this.loadHistory().catch(()=>{})})}disconnect(){this.unsub&&(this.unsub(),this.unsub=null),this.unsubState&&(this.unsubState(),this.unsubState=null),xe.disconnect()}handleEvent(t){var l,d,c,u,y,f,j,_,E,T,A,N,q,P,I,$;const s=t.type,n=t.payload||{};switch(s){case"user":{if(this.applyEmbeddedToolResults(n),this.userSinceTurnEnd=!0,!this.closed&&this.turnStartedAt===null&&this.setTurnStartedAt(Date.now()),t.direction==="inbound"){const p=n.uuid;if(typeof p!="string"||!p||this.postedUserUuids.has(p)||this.seenUuids.has(p))break;this.seenUuids.add(p);const g=Ot(n);g&&this.setEntries(v=>[...v,{type:"user_message",id:t.id||`user-${Date.now()}`,content:g}])}break}case"assistant":{const p=n.uuid;if(typeof p=="string"&&p){if(this.seenUuids.has(p))break;this.seenUuids.add(p)}const g=typeof n.content=="string"?n.content:"";if(Es(g))break;const v=en(n);this.setEntries(S=>{const h=S[S.length-1];if((h==null?void 0:h.type)==="assistant_message"&&h.id.startsWith(Ut))return[...S.slice(0,-1),{...h,id:`assistant-${Date.now()}`,chunks:[...v?[{type:"thought",text:v}]:[],{type:"message",text:g}]}];if((h==null?void 0:h.type)==="assistant_message"){const x=h.chunks[h.chunks.length-1];return(x==null?void 0:x.type)==="message"?[...S.slice(0,-1),{...h,chunks:[...h.chunks.slice(0,-1),{type:"message",text:x.text+g}]}]:[...S.slice(0,-1),{...h,chunks:[...h.chunks,{type:"message",text:g}]}]}if(g&&g.trim()||v){const x={type:"assistant_message",id:`assistant-${Date.now()}`,chunks:[...v?[{type:"thought",text:v}]:[],...g?[{type:"message",text:g}]:[]]};return[...S,x]}return S});const w=n.message;if(w&&typeof w=="object"&&Array.isArray(w.content)){const S=w.content.filter(h=>h.type==="tool_use");for(const h of S){const x=h.id||`call-${Date.now()}-${Math.random().toString(16).slice(2,8)}`;if(this.seenToolCallIds.has(x))continue;this.seenToolCallIds.add(x),this.pendingToolCallIds.add(x);const M={id:x,title:h.name||"tool",status:"running",rawInput:h.input||{}};this.setEntries(U=>[...U,{type:"tool_call",toolCall:M}])}}break}case"tool_use":{const p=n,g=p.tool_call_id||`call-${Date.now()}`;if(this.seenToolCallIds.has(g))break;this.seenToolCallIds.add(g),this.pendingToolCallIds.add(g);const v={id:g,title:p.tool_name||"tool",status:"running",rawInput:p.tool_input||{}};this.setEntries(w=>[...w,{type:"tool_call",toolCall:v}]);break}case"tool_result":{const p=n;this.applyToolResult(p.tool_call_id||"",p.content??p.output);break}case"interrupt":{this.finalizePendingToolCalls("canceled"),this.turnEnded=!0,this.userSinceTurnEnd=!1,this.setTurnStartedAt(null),(l=this.onPermissionSettled)==null||l.call(this,null),this.closed||(d=this.onStatusChange)==null||d.call(this,"idle");break}case"control_request":case"permission_request":{const p=n.request;if(p&&p.subtype==="can_use_tool"){const g=n.request_id||"";if(!g||this.settledPermissionIds.has(g)||this.pendingPermissionDecisions.has(g))break;const v=p.tool_name||"unknown",w=p.input||p.tool_input||{},S=p.description||"",h=Array.isArray(p.permission_suggestions)?p.permission_suggestions:[],x=typeof p.tool_use_id=="string"?p.tool_use_id:void 0,M=v==="AskUserQuestion"||v==="ExitPlanMode",U=hn(h,v)[0],X=U?or(U):void 0,se=M?[]:[{optionId:"allow_once",name:"",kind:"allow_once"},...h.length>0?[{optionId:"allow_always",name:"",kind:"allow_always",description:X}]:[],{optionId:"reject_once",name:"",kind:"reject_once"}];this.setEntries(Q=>{let D=-1;if(x&&(D=Q.findIndex(Z=>Z.type==="tool_call"&&Z.toolCall.id===x)),D<0){const Z=[...Q].reverse().findIndex(ce=>ce.type==="tool_call");Z>=0&&(D=Q.length-1-Z)}if(D<0)return Q;const ne=Q[D];return ne.toolCall.status!=="running"?Q:(this.pendingPermissionToolIds.set(g,ne.toolCall.id),Q.map((Z,ce)=>ce===D?{type:"tool_call",toolCall:{...ne.toolCall,status:"waiting_for_confirmation",permissionRequest:{requestId:g,options:se,...x?{toolUseId:x}:{}}}}:Z))}),(c=this.onPermissionRequest)==null||c.call(this,{requestId:g,toolName:v,toolInput:w,description:S,suggestions:h,...x?{toolUseId:x}:{}})}else p&&p.subtype==="elicitation"&&((u=this.onElicitationRequest)==null||u.call(this,{requestId:n.request_id||"",serverName:p.mcp_server_name||"",message:p.message||"",mode:p.mode==="url"?"url":"form",url:typeof p.url=="string"?p.url:void 0,requestedSchema:p.requested_schema||void 0}));break}case"conversation_rewound":{const p=sn(n);p&&(this.pendingToolCallIds.clear(),this.pendingPermissionToolIds.clear(),this.pendingPermissionDecisions.clear(),this.setEntries(g=>{const v=g.findIndex(w=>Ts(w)===p);return v===-1?g:g.slice(0,v)}));break}case"session_status":{if(ir(n)){this.pendingToolCallIds.clear(),this.pendingPermissionToolIds.clear(),this.pendingPermissionDecisions.clear(),this.setEntries([]);break}if(typeof n.status=="string"){if(kt(n.status))this.closed=!0,this.finalizePendingToolCalls("canceled");else if(this.closed)break;if(n.status==="running"&&this.turnEnded&&!this.userSinceTurnEnd)break;(y=this.onStatusChange)==null||y.call(this,n.status)}break}case"error":{const p=String(n.message||n.content||"Unknown error");(f=this.onError)==null||f.call(this,p);break}case"models_state":{const p=n.raw,g=typeof p=="object"&&p!==null?p.models_state:n.models_state;g&&Array.isArray(g.availableModels)&&typeof g.currentModelId=="string"&&((j=this.onModelsStateChange)==null||j.call(this,g));break}case"system":{const p=n.raw,g=p&&typeof p=="object"?p:n,v=typeof g.subtype=="string"?g.subtype:void 0,w=Vs(n);w&&(this.subagentState=zs(this.subagentState,w),(_=this.onSubagentUpdate)==null||_.call(this,this.subagentState));const S=typeof g.permissionMode=="string"?g.permissionMode:typeof n.permissionMode=="string"?n.permissionMode:null;if(S&&((E=this.onPermissionModeChange)==null||E.call(this,S)),v==="init"){const h=Xs(n);h&&((T=this.onWorkerInfoChange)==null||T.call(this,h))}break}case"control_response":{const p=n.response;if(p&&typeof p=="object"){const g=typeof p.request_id=="string"?p.request_id:"",v=typeof p.subtype=="string"?p.subtype:"";if(g){const w=(A=p.response)==null?void 0:A.behavior,S=this.settlePermission(g,w==="allow"?"allow":w==="deny"?"deny":void 0);S&&((N=this.onPermissionSettled)==null||N.call(this,g,S)),(q=this.onControlResponse)==null||q.call(this,{subtype:v,requestId:g,error:typeof p.error=="string"?p.error:void 0});const h=this.pendingControlRequests.get(g);h&&(this.pendingControlRequests.delete(g),h({data:v==="success"&&p.response&&typeof p.response=="object"?p.response:null,...v==="error"&&typeof p.error=="string"?{error:p.error}:{}}))}}break}case"control_cancel_request":{const p=typeof n.request_id=="string"?n.request_id:"";if(p){const g=this.settlePermission(p,"cancel");g&&((P=this.onPermissionSettled)==null||P.call(this,p,g))}break}case"stream_event":{const p=n.event;if(!p||typeof p.type!="string")break;if(p.type==="content_block_delta"){const g=p.delta;if(!g||typeof g.type!="string")break;const v=g.type==="text_delta"?"message":g.type==="thinking_delta"?"thought":null;if(!v)break;const w=g.text??g.thinking;if(typeof w!="string"||!w)break;this.appendStreamingDelta(v,w)}break}case"partial_assistant":{const p=typeof n.content=="string"?n.content:"";p&&this.appendStreamingDelta("message",p);break}case"result":case"result_success":{this.turnEnded=!0,this.userSinceTurnEnd=!1,this.setTurnStartedAt(null),(I=this.onPermissionSettled)==null||I.call(this,null),this.finalizePendingToolCalls(n.is_error?"canceled":"complete"),this.closed||($=this.onStatusChange)==null||$.call(this,"idle");const p=typeof n.subtype=="string"?n.subtype:"",g=n.raw&&typeof n.raw=="object"?n.raw:void 0,w=(typeof n.result=="string"?n.result:typeof(g==null?void 0:g.result)=="string"?g.result:"").trim();p.startsWith("error_")&&w&&this.setEntries(S=>[...S,{type:"command_output",id:`exit-error-${typeof n.uuid=="string"?n.uuid:Date.now()}`,commandName:"worker",inputText:"",title:i("adapter.workerCrashed"),outputText:w,variant:"error"}]);break}case"task_state":{const p=Array.isArray(n.tasks)?n.tasks:[];if(p.length===0)break;const g=tn(p);if(g.length===0)break;this.setEntries(v=>[...v.filter(S=>S.type!=="plan"),{type:"plan",id:`plan-${n.task_list_id||Date.now()}`,entries:g}]);break}}}applyEmbeddedToolResults(t){const s=t.message;if(!(!s||typeof s!="object"||!Array.isArray(s.content)))for(const n of s.content)!n||n.type!=="tool_result"||this.applyToolResult(n.tool_use_id||"",n.content??n.output)}applyToolResult(t,s){var l;if(!t)return;let n;for(const[d,c]of this.pendingPermissionToolIds)if(c===t){n=d;break}if(n){const d=this.settlePermission(n,"allow");d&&((l=this.onPermissionSettled)==null||l.call(this,n,d))}this.pendingToolCallIds.delete(t),this.setEntries(d=>{const c=Zs(d,t);if(c<0)return d;const u=d[c];return u.toolCall.status!=="running"&&u.toolCall.status!=="waiting_for_confirmation"?d:d.map((y,f)=>f===c?{type:"tool_call",toolCall:{...u.toolCall,status:"complete",permissionRequest:void 0,rawOutput:{output:s||""}}}:y)})}finalizePendingToolCalls(t){if(this.pendingPermissionToolIds.clear(),this.pendingPermissionDecisions.clear(),this.pendingToolCallIds.size===0)return;const s=this.pendingToolCallIds;this.pendingToolCallIds=new Set,this.setEntries(n=>n.map(l=>l.type!=="tool_call"||!s.has(l.toolCall.id)?l:{type:"tool_call",toolCall:{...l.toolCall,status:t,permissionRequest:void 0}}))}appendStreamingDelta(t,s){this.setEntries(n=>{const l=n[n.length-1];if((l==null?void 0:l.type)==="assistant_message"&&l.id.startsWith(Ut)){const c=l.chunks[l.chunks.length-1];return(c==null?void 0:c.type)===t?[...n.slice(0,-1),{...l,chunks:[...l.chunks.slice(0,-1),{type:t,text:c.text+s}]}]:[...n.slice(0,-1),{...l,chunks:[...l.chunks,{type:t,text:s}]}]}const d={type:"assistant_message",id:`${Ut}${Date.now()}`,chunks:[{type:t,text:s}]};return[...n,d]})}async sendMessage(t,s,n){var f;const l=s&&s.length>0,d=n&&n.length>0;if(!t.trim()&&!l&&!d)return;const c={type:"user_message",id:`user-${Date.now()}`,content:t,images:l?s:void 0,attachments:d?n:void 0};this.setEntries(j=>[...j,c]);const u=[];if(t&&u.push({type:"text",text:t}),l)for(const j of s)u.push({type:"image",source:{type:"base64",media_type:j.mimeType,data:j.data}});if(d){for(const j of n)if(j.kind==="text"||j.kind==="table"){const _=`📎 ${j.name}${j.size!=null?` (${Qa(j.size)})`:""}`,E=j.textContent||i("attach.emptyFile");u.push({type:"text",text:`${_}
71
+ */const Fa=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],Qs=ie("share-2",Fa);function Qt(){return{tasks:{}}}const Ws=3e4;function bt(r){const t=r.trim();if(!t)return"agent";const s=t.split(/\s+/).slice(0,2).join(" ");return s.length>40?s.slice(0,40)+"…":s}function Gs(r,t){var c,u,y,f,j,_,E,T,A,N,q,P;const s=t.subtype;if(s!=="task_started"&&s!=="task_progress"&&s!=="task_notification")return r;const n=t.task_id;if(!n)return r;const l=Date.now(),d=r.tasks[n];if(s==="task_started"){if(d)return{tasks:{...r.tasks,[n]:{...d,description:t.description??d.description,name:bt(t.description??d.description),taskType:t.task_type??d.taskType,workflowName:t.workflow_name??d.workflowName,prompt:t.prompt??d.prompt,toolUseId:t.tool_use_id??d.toolUseId,status:"running",startTime:l,evictAfter:void 0}}};const I=t.description??"";return{tasks:{...r.tasks,[n]:{taskId:n,name:bt(I),description:I,taskType:t.task_type,workflowName:t.workflow_name,prompt:t.prompt,toolUseId:t.tool_use_id,status:"running",startTime:l}}}}if(s==="task_progress"){if(!d){const I=t.description??"";return{tasks:{...r.tasks,[n]:{taskId:n,name:bt(I),description:I,toolUseId:t.tool_use_id,status:"running",startTime:l,tokenCount:(c=t.usage)==null?void 0:c.total_tokens,toolUseCount:(u=t.usage)==null?void 0:u.tool_uses,durationMs:(y=t.usage)==null?void 0:y.duration_ms,lastToolName:t.last_tool_name,summary:t.summary}}}}return{tasks:{...r.tasks,[n]:{...d,description:t.description??d.description,tokenCount:((f=t.usage)==null?void 0:f.total_tokens)??d.tokenCount,toolUseCount:((j=t.usage)==null?void 0:j.tool_uses)??d.toolUseCount,durationMs:((_=t.usage)==null?void 0:_.duration_ms)??d.durationMs,lastToolName:t.last_tool_name??d.lastToolName,summary:t.summary??d.summary}}}}return d?{tasks:{...r.tasks,[n]:{...d,status:t.status??"completed",endTime:l,finalSummary:t.summary??d.finalSummary,outputFile:t.output_file??d.outputFile,tokenCount:((N=t.usage)==null?void 0:N.total_tokens)??d.tokenCount,toolUseCount:((q=t.usage)==null?void 0:q.tool_uses)??d.toolUseCount,durationMs:((P=t.usage)==null?void 0:P.duration_ms)??d.durationMs,evictAfter:l+Ws}}}:{tasks:{...r.tasks,[n]:{taskId:n,name:bt(t.summary??""),description:t.summary??"",status:t.status??"completed",startTime:l,endTime:l,finalSummary:t.summary,outputFile:t.output_file,tokenCount:(E=t.usage)==null?void 0:E.total_tokens,toolUseCount:(T=t.usage)==null?void 0:T.tool_uses,durationMs:(A=t.usage)==null?void 0:A.duration_ms,evictAfter:l+Ws}}}}function Oa(r,t=Date.now()){return Object.values(r.tasks).filter(s=>s.evictAfter===void 0||s.evictAfter>t).sort((s,n)=>s.startTime-n.startTime)}const zs={in_process_teammate:0,local_bash:1,monitor_mcp:2,remote_agent:3,local_agent:4,dream:5},Ys=100;function Ua(r){const t=new Map;for(const s of r){const n=s.taskType??"",l=t.get(n);l?l.push(s):t.set(n,[s])}return[...t.entries()].sort(([s],[n])=>{const l=zs[s]??Ys,d=zs[n]??Ys;return l===d?s.localeCompare(n):l-d}).map(([s,n])=>({taskType:s,tasks:[...n].sort((l,d)=>l.startTime-d.startTime)}))}function Vs(r){const t=r.raw,s=t&&typeof t=="object"?t:r,n=typeof s.subtype=="string"?s.subtype:void 0;return n!=="task_started"&&n!=="task_progress"&&n!=="task_notification"?null:{subtype:n,task_id:typeof s.task_id=="string"?s.task_id:void 0,tool_use_id:typeof s.tool_use_id=="string"?s.tool_use_id:void 0,description:typeof s.description=="string"?s.description:void 0,task_type:typeof s.task_type=="string"?s.task_type:void 0,workflow_name:typeof s.workflow_name=="string"?s.workflow_name:void 0,prompt:typeof s.prompt=="string"?s.prompt:void 0,usage:s.usage&&typeof s.usage=="object"?s.usage:void 0,last_tool_name:typeof s.last_tool_name=="string"?s.last_tool_name:void 0,summary:typeof s.summary=="string"?s.summary:void 0,status:s.status==="completed"||s.status==="failed"||s.status==="stopped"?s.status:void 0,output_file:typeof s.output_file=="string"?s.output_file:void 0}}function La(r){if(!r||typeof r!="object"||Array.isArray(r))return null;const t=r,s={file_search:t.file_search===!0,clear:t.clear===!0,set_max_thinking_tokens:t.set_max_thinking_tokens===!0,get_context_usage:t.get_context_usage===!0,stop_task:t.stop_task===!0,set_model:t.set_model===!0,set_permission_mode:t.set_permission_mode===!0,interrupt:t.interrupt===!0,end_session:t.end_session===!0,mcp_management:t.mcp_management===!0,remote_settings:t.remote_settings===!0,rewind:t.rewind===!0,resume:t.resume===!0,set_effort:t.set_effort===!0,set_token_mode:t.set_token_mode===!0,side_question:t.side_question===!0};return Object.values(s).some(Boolean)?s:null}function Js(r,t){const s=[];if(Array.isArray(r)){for(const n of r){if(!n||typeof n!="object")continue;const l=n;if(typeof l.name!="string"||!l.name)continue;const d=l.type==="prompt"||l.type==="local"||l.type==="local-jsx"?l.type:void 0;s.push({name:l.name,...typeof l.description=="string"&&l.description?{description:l.description}:{},...typeof l.argumentHint=="string"&&l.argumentHint?{argumentHint:l.argumentHint}:{},...d?{type:d}:{}})}if(s.length>0)return s}if(Array.isArray(t))for(const n of t)typeof n=="string"&&n&&s.push({name:n});return s}function Xs(r){const t=r.raw&&typeof r.raw=="object"&&!Array.isArray(r.raw)?r.raw:r,s=Js(t.slash_command_details??r.slash_command_details,t.slash_commands??r.slash_commands),n=Js(t.skill_details??r.skill_details,t.skills??r.skills),l=La(t.remote_capabilities??r.remote_capabilities);return s.length===0&&n.length===0&&!l?null:{commands:s,skills:n,capabilities:l}}class Ka{constructor(t){F(this,"listeners",new Set);F(this,"stateListeners",new Set);F(this,"eventSource",null);F(this,"sessionId",null);F(this,"_lastSeqNum",0);F(this,"lastFrameAt",0);F(this,"firstEventAfterOpen",!1);F(this,"watchdogTimer",null);F(this,"visibilityHandler",null);F(this,"reconnectTimer",null);F(this,"reconnectAttempts",0);F(this,"_state","idle");F(this,"opts");this.opts={stallThresholdMs:45e3,watchdogTickMs:5e3,reconnectBaseDelayMs:1e3,reconnectMaxDelayMs:15e3,maxReconnectAttempts:6,...t}}get state(){return this._state}onEvent(t){return this.listeners.add(t),()=>this.listeners.delete(t)}onStateChange(t){return this.stateListeners.add(t),()=>this.stateListeners.delete(t)}connect(t){this.stopReconnectTimer(),this.reconnectAttempts=0,this.sessionId=t,this.openStream()}openStream(){if(this.closeStream(),!this.sessionId)return;this.setState("connecting");const t=this._lastSeqNum>0?`/web/sessions/${this.sessionId}/events?fromSeqNum=${this._lastSeqNum}`:`/web/sessions/${this.sessionId}/events`,s=new EventSource(t,{withCredentials:!0});this.eventSource=s,this.lastFrameAt=Date.now(),this.firstEventAfterOpen=!0,s.addEventListener("open",()=>{this.lastFrameAt=Date.now(),this.reconnectAttempts=0,this.firstEventAfterOpen=!0,this.setState("open")}),s.addEventListener("ping",()=>{this.lastFrameAt=Date.now()}),s.addEventListener("message",n=>{this.lastFrameAt=Date.now();try{const l=JSON.parse(n.data);if(this.firstEventAfterOpen&&(this.firstEventAfterOpen=!1,typeof l.seqNum=="number"&&l.seqNum<this._lastSeqNum&&(this._lastSeqNum=l.seqNum-1,this.notifyResync())),l.seqNum!==void 0&&l.seqNum<=this._lastSeqNum)return;l.seqNum!==void 0&&(this._lastSeqNum=l.seqNum);for(const d of this.listeners)d(l)}catch{}}),s.addEventListener("error",()=>{s.readyState===EventSource.CLOSED&&this.scheduleReconnect()}),this.startWatchdog()}disconnect(){this.sessionId=null,this.stopReconnectTimer(),this.closeStream(),this._lastSeqNum=0,this.reconnectAttempts=0,this.setState("idle")}closeStream(){this.stopWatchdog(),this.eventSource&&(this.eventSource.close(),this.eventSource=null)}startWatchdog(){this.stopWatchdog(),this.watchdogTimer=setInterval(()=>{this.probeStall()},this.opts.watchdogTickMs),typeof document<"u"&&(this.visibilityHandler=()=>{document.visibilityState==="visible"&&this.probeStall()},document.addEventListener("visibilitychange",this.visibilityHandler))}probeStall(){const t=this.eventSource;!t||t.readyState!==EventSource.OPEN||Date.now()-this.lastFrameAt<=this.opts.stallThresholdMs||this.scheduleReconnect()}stopWatchdog(){this.watchdogTimer&&(clearInterval(this.watchdogTimer),this.watchdogTimer=null),this.visibilityHandler&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null)}stopReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}scheduleReconnect(){if(this.reconnectTimer||!this.sessionId)return;if(this.closeStream(),this.reconnectAttempts++,this.reconnectAttempts>this.opts.maxReconnectAttempts){this.setState("failed");return}this.setState("reconnecting");const t=Math.min(this.opts.reconnectBaseDelayMs*2**(this.reconnectAttempts-1),this.opts.reconnectMaxDelayMs),s=Math.max(0,t+t*.25*(2*Math.random()-1));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.reconnect()},s)}async reconnect(){this.sessionId&&(await ur(),this.sessionId&&this.openStream())}setState(t){if(this._state!==t){this._state=t;for(const s of this.stateListeners)s(t,{})}}notifyResync(){for(const t of this.stateListeners)t(this._state,{resync:!0})}}const xe=new Ka;function Ot(r){if(typeof r.content=="string")return r.content;if(r.message&&typeof r.message=="object"){const t=r.message;if(typeof t.content=="string")return t.content;if(Array.isArray(t.content))return t.content.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}return""}function Zs(r,t){for(let s=r.length-1;s>=0;s--){const n=r[s];if(n&&n.type==="tool_call"&&n.toolCall.id===t)return s}return-1}const Ut="streaming-";function en(r){const t=r.message;if(!t||typeof t!="object"||!Array.isArray(t.content))return"";const s=[];for(const n of t.content)if((n==null?void 0:n.type)==="thinking"){const l=typeof n.thinking=="string"&&n.thinking||typeof n.text=="string"&&n.text||"";l&&s.push(l)}return s.join("")}function tn(r){return r.filter(t=>typeof t.subject=="string"&&t.subject).map(t=>({content:t.subject,priority:"medium",status:t.status==="completed"?"completed":t.status==="in_progress"?"in_progress":"pending"}))}function sn(r){if(!r||typeof r!="object")return"";const t=r;if(typeof t.target_event_id=="string"&&t.target_event_id)return t.target_event_id;const s=t.raw;if(s&&typeof s=="object"&&!Array.isArray(s)){const n=s.target_event_id;if(typeof n=="string"&&n)return n}return""}class Ba{constructor(t,s,n){F(this,"sessionId");F(this,"setEntries");F(this,"unsub",null);F(this,"unsubState",null);F(this,"onStatusChange");F(this,"onError");F(this,"onPermissionRequest");F(this,"onPermissionSettled");F(this,"onModelsStateChange");F(this,"onSubagentUpdate");F(this,"onControlResponse");F(this,"onPermissionModeChange");F(this,"onElicitationRequest");F(this,"onWorkerInfoChange");F(this,"onTurnStart");F(this,"subagentState",Qt());F(this,"seenUuids",new Set);F(this,"seenToolCallIds",new Set);F(this,"pendingToolCallIds",new Set);F(this,"pendingPermissionToolIds",new Map);F(this,"pendingPermissionDecisions",new Map);F(this,"settledPermissionIds",new Set);F(this,"postedUserUuids",new Set);F(this,"pendingControlRequests",new Map);F(this,"turnEnded",!1);F(this,"userSinceTurnEnd",!1);F(this,"turnStartedAt",null);F(this,"closed",!1);this.sessionId=t,this.setEntries=s,this.onStatusChange=n==null?void 0:n.onStatusChange,this.onError=n==null?void 0:n.onError,this.onPermissionRequest=n==null?void 0:n.onPermissionRequest,this.onPermissionSettled=n==null?void 0:n.onPermissionSettled,this.onModelsStateChange=n==null?void 0:n.onModelsStateChange,this.onSubagentUpdate=n==null?void 0:n.onSubagentUpdate,this.onControlResponse=n==null?void 0:n.onControlResponse,this.onPermissionModeChange=n==null?void 0:n.onPermissionModeChange,this.onElicitationRequest=n==null?void 0:n.onElicitationRequest,this.onWorkerInfoChange=n==null?void 0:n.onWorkerInfoChange,this.onTurnStart=n==null?void 0:n.onTurnStart}markClosed(){this.closed=!0}setTurnStartedAt(t){var s;this.turnStartedAt!==t&&(this.turnStartedAt=t,(s=this.onTurnStart)==null||s.call(this,t))}async init(){await this.loadHistory(),this.connectSSE()}async loadHistory(){var N,q,P,I,$,p,g;const{events:t}=await ar(this.sessionId);if(!t||t.length===0)return;const s=new Set;for(const v of t){if(v.type!=="user"||v.direction==="inbound")continue;const w=(N=v.payload)==null?void 0:N.uuid;typeof w=="string"&&w&&s.add(w)}const n=[];let l=null;const d=()=>{l&&(n.push(l),l=null)};for(const v of t){const w=v.payload||{},S=w.uuid;if(typeof S=="string"&&S&&this.seenUuids.add(S),v.type==="tool_use"){const h=w.tool_call_id;typeof h=="string"&&h&&this.seenToolCallIds.add(h)}if(v.type==="user"){if(v.direction==="inbound"){const x=w.uuid;if(typeof x!="string"||!x||s.has(x))continue}d();const h=Ot(w);h&&n.push({type:"user_message",id:v.id||`hist-user-${n.length}`,content:h})}else if(v.type==="assistant"){d();const h=Ot(w);if(Es(h))continue;const x=en(w),M=[],U=w.message;if(U&&typeof U=="object"&&Array.isArray(U.content)){for(const X of U.content)if(X.type==="tool_use"){const se=X.id;se&&this.seenToolCallIds.add(se),M.push({type:"tool_call",toolCall:{id:se||`hist-tool-${n.length}`,title:X.name||"tool",status:"complete",rawInput:X.input||{}}})}}if(h||x||M.length>0){l={type:"assistant_message",id:v.id||`hist-asst-${n.length}`,chunks:[...x?[{type:"thought",text:x}]:[],...h?[{type:"message",text:h}]:[]]},n.push(l);for(const X of M)n.push(X);l=null}}else if(v.type==="conversation_rewound"){const h=sn(w);if(h){const x=n.findIndex(M=>Ts(M)===h);x>=0&&(n.length=x)}}else if(v.type==="tool_use"){const h=w,x={type:"tool_call",toolCall:{id:h.tool_call_id||`hist-tool-${n.length}`,title:h.tool_name||"tool",status:"complete",rawInput:h.tool_input||{}}};n.push(x)}else if(v.type==="tool_result"){const h=w,x=Zs(n,h.tool_call_id||"");if(x>=0){const M=n[x];n[x]={type:"tool_call",toolCall:{...M.toolCall,rawOutput:{output:h.content||h.output||""}}}}}}d();let c=null;for(const v of t){if(v.type!=="task_state")continue;const w=v.payload||{};Array.isArray(w.tasks)&&(c=w.tasks)}if(c&&c.length>0){const v=tn(c);v.length>0&&n.push({type:"plan",id:`plan-hist-${Date.now()}`,entries:v})}this.pendingToolCallIds.clear(),this.pendingPermissionToolIds.clear(),this.pendingPermissionDecisions.clear(),this.setEntries(n);let u=null,y=null,f=null,j=null,_=0,E=0;for(const v of t){const w=v.payload||{};if(typeof v.createdAt=="number"&&(v.createdAt>E&&(E=v.createdAt),v.type==="user"&&j!=="user"&&v.createdAt>0&&(_=v.createdAt)),v.type==="user"?j="user":(v.type==="result"||v.type==="result_success"||v.type==="interrupt")&&(j="turn_end"),v.type==="system"&&(w.subtype==="init"||((q=w.raw)==null?void 0:q.subtype)==="init")&&(y=Xs(w)),v.type==="models_state"){const S=w.raw,h=S&&typeof S=="object"?S.models_state:w.models_state;h&&Array.isArray(h.availableModels)&&typeof h.currentModelId=="string"&&(u=h)}if(v.type==="system"){const S=w.raw,h=typeof w.permissionMode=="string"?w.permissionMode:typeof(S==null?void 0:S.permissionMode)=="string"?S.permissionMode:null;h&&(f=h)}}let T=!1,A=Qt();for(const v of t){if(v.type!=="system")continue;const w=Vs(v.payload||{});w&&(A=Gs(A,w),T=!0)}T&&(this.subagentState=A,(P=this.onSubagentUpdate)==null||P.call(this,this.subagentState)),u&&((I=this.onModelsStateChange)==null||I.call(this,u)),y&&(($=this.onWorkerInfoChange)==null||$.call(this,y)),f&&((p=this.onPermissionModeChange)==null||p.call(this,f)),this.turnEnded=j==="turn_end",this.userSinceTurnEnd=j==="user",this.setTurnStartedAt(!this.closed&&j==="user"&&_>0&&E>=_?Date.now()-(E-_):null),this.turnEnded&&!this.closed&&((g=this.onStatusChange)==null||g.call(this,"idle"))}connectSSE(){xe.connect(this.sessionId),this.unsub=xe.onEvent(t=>this.handleEvent(t)),this.unsubState=xe.onStateChange((t,s)=>{s.resync&&!this.closed&&this.loadHistory().catch(()=>{})})}disconnect(){this.unsub&&(this.unsub(),this.unsub=null),this.unsubState&&(this.unsubState(),this.unsubState=null),xe.disconnect()}handleEvent(t){var l,d,c,u,y,f,j,_,E,T,A,N,q,P,I,$;const s=t.type,n=t.payload||{};switch(s){case"user":{if(this.applyEmbeddedToolResults(n),this.userSinceTurnEnd=!0,!this.closed&&this.turnStartedAt===null&&this.setTurnStartedAt(Date.now()),t.direction==="inbound"){const p=n.uuid;if(typeof p!="string"||!p||this.postedUserUuids.has(p)||this.seenUuids.has(p))break;this.seenUuids.add(p);const g=Ot(n);g&&this.setEntries(v=>[...v,{type:"user_message",id:t.id||`user-${Date.now()}`,content:g}])}break}case"assistant":{const p=n.uuid;if(typeof p=="string"&&p){if(this.seenUuids.has(p))break;this.seenUuids.add(p)}const g=typeof n.content=="string"?n.content:"";if(Es(g))break;const v=en(n);this.setEntries(S=>{const h=S[S.length-1];if((h==null?void 0:h.type)==="assistant_message"&&h.id.startsWith(Ut))return[...S.slice(0,-1),{...h,id:`assistant-${Date.now()}`,chunks:[...v?[{type:"thought",text:v}]:[],{type:"message",text:g}]}];if((h==null?void 0:h.type)==="assistant_message"){const x=h.chunks[h.chunks.length-1];return(x==null?void 0:x.type)==="message"?[...S.slice(0,-1),{...h,chunks:[...h.chunks.slice(0,-1),{type:"message",text:x.text+g}]}]:[...S.slice(0,-1),{...h,chunks:[...h.chunks,{type:"message",text:g}]}]}if(g&&g.trim()||v){const x={type:"assistant_message",id:`assistant-${Date.now()}`,chunks:[...v?[{type:"thought",text:v}]:[],...g?[{type:"message",text:g}]:[]]};return[...S,x]}return S});const w=n.message;if(w&&typeof w=="object"&&Array.isArray(w.content)){const S=w.content.filter(h=>h.type==="tool_use");for(const h of S){const x=h.id||`call-${Date.now()}-${Math.random().toString(16).slice(2,8)}`;if(this.seenToolCallIds.has(x))continue;this.seenToolCallIds.add(x),this.pendingToolCallIds.add(x);const M={id:x,title:h.name||"tool",status:"running",rawInput:h.input||{}};this.setEntries(U=>[...U,{type:"tool_call",toolCall:M}])}}break}case"tool_use":{const p=n,g=p.tool_call_id||`call-${Date.now()}`;if(this.seenToolCallIds.has(g))break;this.seenToolCallIds.add(g),this.pendingToolCallIds.add(g);const v={id:g,title:p.tool_name||"tool",status:"running",rawInput:p.tool_input||{}};this.setEntries(w=>[...w,{type:"tool_call",toolCall:v}]);break}case"tool_result":{const p=n;this.applyToolResult(p.tool_call_id||"",p.content??p.output);break}case"interrupt":{this.finalizePendingToolCalls("canceled"),this.turnEnded=!0,this.userSinceTurnEnd=!1,this.setTurnStartedAt(null),(l=this.onPermissionSettled)==null||l.call(this,null),this.closed||(d=this.onStatusChange)==null||d.call(this,"idle");break}case"control_request":case"permission_request":{const p=n.request;if(p&&p.subtype==="can_use_tool"){const g=n.request_id||"";if(!g||this.settledPermissionIds.has(g)||this.pendingPermissionDecisions.has(g))break;const v=p.tool_name||"unknown",w=p.input||p.tool_input||{},S=p.description||"",h=Array.isArray(p.permission_suggestions)?p.permission_suggestions:[],x=typeof p.tool_use_id=="string"?p.tool_use_id:void 0,M=v==="AskUserQuestion"||v==="ExitPlanMode",U=hn(h,v)[0],X=U?or(U):void 0,se=M?[]:[{optionId:"allow_once",name:"",kind:"allow_once"},...h.length>0?[{optionId:"allow_always",name:"",kind:"allow_always",description:X}]:[],{optionId:"reject_once",name:"",kind:"reject_once"}];this.setEntries(Q=>{let D=-1;if(x&&(D=Q.findIndex(Z=>Z.type==="tool_call"&&Z.toolCall.id===x)),D<0){const Z=[...Q].reverse().findIndex(ce=>ce.type==="tool_call");Z>=0&&(D=Q.length-1-Z)}if(D<0)return Q;const ne=Q[D];return ne.toolCall.status!=="running"?Q:(this.pendingPermissionToolIds.set(g,ne.toolCall.id),Q.map((Z,ce)=>ce===D?{type:"tool_call",toolCall:{...ne.toolCall,status:"waiting_for_confirmation",permissionRequest:{requestId:g,options:se,...x?{toolUseId:x}:{}}}}:Z))}),(c=this.onPermissionRequest)==null||c.call(this,{requestId:g,toolName:v,toolInput:w,description:S,suggestions:h,...x?{toolUseId:x}:{}})}else p&&p.subtype==="elicitation"&&((u=this.onElicitationRequest)==null||u.call(this,{requestId:n.request_id||"",serverName:p.mcp_server_name||"",message:p.message||"",mode:p.mode==="url"?"url":"form",url:typeof p.url=="string"?p.url:void 0,requestedSchema:p.requested_schema||void 0}));break}case"conversation_rewound":{const p=sn(n);p&&(this.pendingToolCallIds.clear(),this.pendingPermissionToolIds.clear(),this.pendingPermissionDecisions.clear(),this.setEntries(g=>{const v=g.findIndex(w=>Ts(w)===p);return v===-1?g:g.slice(0,v)}));break}case"session_status":{if(ir(n)){this.pendingToolCallIds.clear(),this.pendingPermissionToolIds.clear(),this.pendingPermissionDecisions.clear(),this.setEntries([]);break}if(typeof n.status=="string"){if(kt(n.status))this.closed=!0,this.finalizePendingToolCalls("canceled");else if(this.closed)break;if(n.status==="running"&&this.turnEnded&&!this.userSinceTurnEnd)break;(y=this.onStatusChange)==null||y.call(this,n.status)}break}case"error":{const p=String(n.message||n.content||"Unknown error");(f=this.onError)==null||f.call(this,p);break}case"models_state":{const p=n.raw,g=typeof p=="object"&&p!==null?p.models_state:n.models_state;g&&Array.isArray(g.availableModels)&&typeof g.currentModelId=="string"&&((j=this.onModelsStateChange)==null||j.call(this,g));break}case"system":{const p=n.raw,g=p&&typeof p=="object"?p:n,v=typeof g.subtype=="string"?g.subtype:void 0,w=Vs(n);w&&(this.subagentState=Gs(this.subagentState,w),(_=this.onSubagentUpdate)==null||_.call(this,this.subagentState));const S=typeof g.permissionMode=="string"?g.permissionMode:typeof n.permissionMode=="string"?n.permissionMode:null;if(S&&((E=this.onPermissionModeChange)==null||E.call(this,S)),v==="init"){const h=Xs(n);h&&((T=this.onWorkerInfoChange)==null||T.call(this,h))}break}case"control_response":{const p=n.response;if(p&&typeof p=="object"){const g=typeof p.request_id=="string"?p.request_id:"",v=typeof p.subtype=="string"?p.subtype:"";if(g){const w=(A=p.response)==null?void 0:A.behavior,S=this.settlePermission(g,w==="allow"?"allow":w==="deny"?"deny":void 0);S&&((N=this.onPermissionSettled)==null||N.call(this,g,S)),(q=this.onControlResponse)==null||q.call(this,{subtype:v,requestId:g,error:typeof p.error=="string"?p.error:void 0});const h=this.pendingControlRequests.get(g);h&&(this.pendingControlRequests.delete(g),h({data:v==="success"&&p.response&&typeof p.response=="object"?p.response:null,...v==="error"&&typeof p.error=="string"?{error:p.error}:{}}))}}break}case"control_cancel_request":{const p=typeof n.request_id=="string"?n.request_id:"";if(p){const g=this.settlePermission(p,"cancel");g&&((P=this.onPermissionSettled)==null||P.call(this,p,g))}break}case"stream_event":{const p=n.event;if(!p||typeof p.type!="string")break;if(p.type==="content_block_delta"){const g=p.delta;if(!g||typeof g.type!="string")break;const v=g.type==="text_delta"?"message":g.type==="thinking_delta"?"thought":null;if(!v)break;const w=g.text??g.thinking;if(typeof w!="string"||!w)break;this.appendStreamingDelta(v,w)}break}case"partial_assistant":{const p=typeof n.content=="string"?n.content:"";p&&this.appendStreamingDelta("message",p);break}case"result":case"result_success":{this.turnEnded=!0,this.userSinceTurnEnd=!1,this.setTurnStartedAt(null),(I=this.onPermissionSettled)==null||I.call(this,null),this.finalizePendingToolCalls(n.is_error?"canceled":"complete"),this.closed||($=this.onStatusChange)==null||$.call(this,"idle");const p=typeof n.subtype=="string"?n.subtype:"",g=n.raw&&typeof n.raw=="object"?n.raw:void 0,w=(typeof n.result=="string"?n.result:typeof(g==null?void 0:g.result)=="string"?g.result:"").trim();p.startsWith("error_")&&w&&this.setEntries(S=>[...S,{type:"command_output",id:`exit-error-${typeof n.uuid=="string"?n.uuid:Date.now()}`,commandName:"worker",inputText:"",title:i("adapter.workerCrashed"),outputText:w,variant:"error"}]);break}case"task_state":{const p=Array.isArray(n.tasks)?n.tasks:[];if(p.length===0)break;const g=tn(p);if(g.length===0)break;this.setEntries(v=>[...v.filter(S=>S.type!=="plan"),{type:"plan",id:`plan-${n.task_list_id||Date.now()}`,entries:g}]);break}}}applyEmbeddedToolResults(t){const s=t.message;if(!(!s||typeof s!="object"||!Array.isArray(s.content)))for(const n of s.content)!n||n.type!=="tool_result"||this.applyToolResult(n.tool_use_id||"",n.content??n.output)}applyToolResult(t,s){var l;if(!t)return;let n;for(const[d,c]of this.pendingPermissionToolIds)if(c===t){n=d;break}if(n){const d=this.settlePermission(n,"allow");d&&((l=this.onPermissionSettled)==null||l.call(this,n,d))}this.pendingToolCallIds.delete(t),this.setEntries(d=>{const c=Zs(d,t);if(c<0)return d;const u=d[c];return u.toolCall.status!=="running"&&u.toolCall.status!=="waiting_for_confirmation"?d:d.map((y,f)=>f===c?{type:"tool_call",toolCall:{...u.toolCall,status:"complete",permissionRequest:void 0,rawOutput:{output:s||""}}}:y)})}finalizePendingToolCalls(t){if(this.pendingPermissionToolIds.clear(),this.pendingPermissionDecisions.clear(),this.pendingToolCallIds.size===0)return;const s=this.pendingToolCallIds;this.pendingToolCallIds=new Set,this.setEntries(n=>n.map(l=>l.type!=="tool_call"||!s.has(l.toolCall.id)?l:{type:"tool_call",toolCall:{...l.toolCall,status:t,permissionRequest:void 0}}))}appendStreamingDelta(t,s){this.setEntries(n=>{const l=n[n.length-1];if((l==null?void 0:l.type)==="assistant_message"&&l.id.startsWith(Ut)){const c=l.chunks[l.chunks.length-1];return(c==null?void 0:c.type)===t?[...n.slice(0,-1),{...l,chunks:[...l.chunks.slice(0,-1),{type:t,text:c.text+s}]}]:[...n.slice(0,-1),{...l,chunks:[...l.chunks,{type:t,text:s}]}]}const d={type:"assistant_message",id:`${Ut}${Date.now()}`,chunks:[{type:t,text:s}]};return[...n,d]})}async sendMessage(t,s,n){var f;const l=s&&s.length>0,d=n&&n.length>0;if(!t.trim()&&!l&&!d)return;const c={type:"user_message",id:`user-${Date.now()}`,content:t,images:l?s:void 0,attachments:d?n:void 0};this.setEntries(j=>[...j,c]);const u=[];if(t&&u.push({type:"text",text:t}),l)for(const j of s)u.push({type:"image",source:{type:"base64",media_type:j.mimeType,data:j.data}});if(d){for(const j of n)if(j.kind==="text"||j.kind==="table"){const _=`📎 ${j.name}${j.size!=null?` (${Ha(j.size)})`:""}`,E=j.textContent||i("attach.emptyFile");u.push({type:"text",text:`${_}
77
72
  \`\`\`
78
73
  ${E}
79
74
  \`\`\``})}else if(j.kind==="directory"){const _=j.files!=null?`${K("attach.directoryHeader",{name:j.name})} ${K("attach.fileCount",{n:j.files.length})}`:K("attach.directoryHeader",{name:j.name}),E=j.textContent||i("attach.emptyDirectory");u.push({type:"text",text:`${_}
80
- ${E}`})}}const y=u.length===1&&u[0].type==="text"?u[0].text||t:u.length>0?u:t;try{const j=Me();this.postedUserUuids.add(j);const _=await lr(this.sessionId,{type:"user",uuid:j,content:t,message:{content:y}}),E=(f=_==null?void 0:_.event)==null?void 0:f.id;E&&this.setEntries(T=>T.map(A=>A.type==="user_message"&&A.id===c.id?{...A,id:E}:A))}catch(j){throw this.setEntries(_=>_.filter(E=>!(E.type==="user_message"&&E.id===c.id))),j}}async respondPermission(t,s,n){this.pendingPermissionDecisions.set(t,s);const l=Date.now();this.markPermissionSent(t,s?"allow":"deny",l);try{await le(this.sessionId,{type:"permission_response",approved:s,request_id:t,...n})}catch(d){throw this.pendingPermissionDecisions.delete(t),this.markPermissionSent(t,void 0,void 0),d}}markPermissionSent(t,s,n){this.setEntries(l=>l.map(d=>{if(d.type!=="tool_call")return d;const c=d.toolCall.permissionRequest;if((c==null?void 0:c.requestId)!==t)return d;const u={...c};return s?u.decision=s:delete u.decision,n!==void 0?u.sentAt=n:delete u.sentAt,{type:"tool_call",toolCall:{...d.toolCall,permissionRequest:u}}}))}isPermissionSettled(t){return this.settledPermissionIds.has(t)}rememberSettledPermission(t){if(this.settledPermissionIds.add(t),this.settledPermissionIds.size<=200)return;const s=this.settledPermissionIds.values().next().value;s!==void 0&&this.settledPermissionIds.delete(s)}settlePermission(t,s){if(!t||this.settledPermissionIds.has(t))return null;const n=this.pendingPermissionDecisions.get(t);let l;s==="allow"||s==="deny"?l=s:n!==void 0?l=n?"allow":"deny":s==="cancel"?l="cancel":l="allow",this.rememberSettledPermission(t);const d=this.pendingPermissionToolIds.get(t);this.pendingPermissionToolIds.delete(t),this.pendingPermissionDecisions.delete(t),d&&l!=="allow"&&this.pendingToolCallIds.delete(d);const c=l==="allow"?"running":l==="deny"?"rejected":"canceled";return this.setEntries(u=>u.map(y=>{var f;return y.type!=="tool_call"||((f=y.toolCall.permissionRequest)==null?void 0:f.requestId)!==t?y:{type:"tool_call",toolCall:{...y.toolCall,status:c,permissionRequest:void 0}}})),l}async interrupt(){this.finalizePendingToolCalls("canceled"),await cr(this.sessionId)}async setPermissionMode(t){const s=Me();return await le(this.sessionId,{type:"control_request",request_id:s,request:{subtype:"set_permission_mode",mode:t}}),s}async controlRoundTrip(t,s=8e3){const n=Me(),l=new Promise(c=>{this.pendingControlRequests.set(n,c)}),d=setTimeout(()=>{const c=this.pendingControlRequests.get(n);c&&(this.pendingControlRequests.delete(n),c({data:null,error:"timeout"}))},s);try{return await le(this.sessionId,{type:"control_request",request_id:n,request:t}),await l}catch(c){throw this.pendingControlRequests.delete(n),c}finally{clearTimeout(d)}}async searchFiles(t,s=20){const n=await this.controlRoundTrip({subtype:"file_search",query:t,limit:s});try{if(!n.data||!Array.isArray(n.data.suggestions))return[];const l=[];for(const d of n.data.suggestions)d&&typeof d=="object"&&typeof d.path=="string"&&l.push(d.path);return l}catch{return[]}}async respondElicitation(t,s,n){await le(this.sessionId,{type:"permission_response",approved:s==="accept",request_id:t,response:{subtype:"success",request_id:t,response:{action:s,...n?{content:n}:{}}}})}async askSideQuestion(t){const s=await this.controlRoundTrip({subtype:"side_question",question:t},12e4);if(s.error||!s.data)return null;const n=s.data.response;return typeof n=="string"?n:null}async listResumableSessions(){const t=await this.controlRoundTrip({subtype:"list_sessions"});if(!t.data||!Array.isArray(t.data.sessions))throw new Error(t.error??"list_sessions failed");const s=[];for(const n of t.data.sessions){if(!n||typeof n!="object")continue;const l=n;typeof l.session_id!="string"||!l.session_id||s.push({sessionId:l.session_id,title:typeof l.title=="string"&&l.title?l.title:l.session_id.slice(0,8),modified:typeof l.modified=="number"?l.modified:0,...typeof l.created_at=="number"?{createdAt:l.created_at}:{},...typeof l.git_branch=="string"&&l.git_branch?{gitBranch:l.git_branch}:{}})}return s}async resumeSession(t){const s=await this.controlRoundTrip({subtype:"resume_session",session_id:t},3e4);if(!s.data)throw new Error(s.error??"resume_session failed");return{title:typeof s.data.title=="string"?s.data.title:null,messageCount:typeof s.data.message_count=="number"?s.data.message_count:0}}async setEffort(t){const s=Me();return await le(this.sessionId,{type:"control_request",request_id:s,request:{subtype:"set_effort",...t?{effort:t}:{effort:null}}}),s}async setTokenMode(t){const s=Me();return await le(this.sessionId,{type:"control_request",request_id:s,request:{subtype:"set_token_mode",mode:t}}),s}async setThinkingBudget(t){const s=Me();return await le(this.sessionId,{type:"control_request",request_id:s,request:{subtype:"set_max_thinking_tokens",max_thinking_tokens:t}}),s}async getContextUsage(){const t=await this.controlRoundTrip({subtype:"get_context_usage"});try{if(!t.data)return null;const s=t.data.totalTokens,n=t.data.rawMaxTokens,l=t.data.percentage;if(typeof s!="number"||typeof n!="number")return null;const d=t.data.categories,c=Array.isArray(d)?d.filter(u=>!!u&&typeof u=="object"&&typeof u.name=="string").map(u=>({name:u.name,tokens:typeof u.tokens=="number"?u.tokens:0,...u.isDeferred===!0?{isDeferred:!0}:{}})):void 0;return{totalTokens:s,rawMaxTokens:n,percentage:typeof l=="number"?l:0,...typeof t.data.model=="string"&&t.data.model?{model:t.data.model}:{},...c&&c.length>0?{categories:c}:{}}}catch{return null}}async stopSubagent(t){const s=await this.controlRoundTrip({subtype:"stop_task",task_id:t});try{return s.error?{ok:!1,error:s.error==="timeout"?i("adapter.stopTimeout"):s.error}:{ok:!0}}catch{return{ok:!1,error:i("adapter.stopFailed")}}}async getMcpServers(){var l;const s=(l=(await this.controlRoundTrip({subtype:"mcp_status"})).data)==null?void 0:l.mcpServers;if(!Array.isArray(s))return[];const n=[];for(const d of s){if(!d||typeof d!="object")continue;const c=d;if(typeof c.name!="string"||!c.name)continue;const u=c.status;if(u!=="connected"&&u!=="failed"&&u!=="needs-auth"&&u!=="pending"&&u!=="disabled")continue;const y=c.serverInfo,f=c.config;n.push({name:c.name,status:u,...y&&typeof y.name=="string"&&typeof y.version=="string"?{serverInfo:{name:y.name,version:y.version}}:{},...typeof c.error=="string"&&c.error?{error:c.error}:{},...typeof(f==null?void 0:f.url)=="string"&&f.url?{url:f.url}:{},...Array.isArray(c.tools)?{toolCount:c.tools.length}:{}})}return n}async toggleMcpServer(t,s){const n=await this.controlRoundTrip({subtype:"mcp_toggle",serverName:t,enabled:s},15e3);return n.error?{ok:!1,error:n.error==="timeout"?i("adapter.requestTimeout"):n.error}:{ok:!0}}async reconnectMcpServer(t){const s=await this.controlRoundTrip({subtype:"mcp_reconnect",serverName:t},2e4);return s.error?{ok:!1,error:s.error==="timeout"?i("adapter.requestTimeout"):s.error}:{ok:!0}}async getRemoteSettings(){const s=(await this.controlRoundTrip({subtype:"get_settings"})).data;if(!s)return null;const n=s.applied,l=s.effective&&typeof s.effective=="object"&&!Array.isArray(s.effective)?s.effective:{},d=s.sources,c=[];if(Array.isArray(d))for(const u of d){if(!u||typeof u!="object")continue;const y=u;typeof y.source=="string"&&c.push({source:y.source,settings:y.settings&&typeof y.settings=="object"&&!Array.isArray(y.settings)?y.settings:{}})}return{applied:{model:typeof(n==null?void 0:n.model)=="string"?n.model:null,effort:typeof(n==null?void 0:n.effort)=="string"?n.effort:null,tokenMode:typeof(n==null?void 0:n.tokenMode)=="string"?n.tokenMode:null},effective:l,sources:c}}async applyFlagSettings(t){const s=await this.controlRoundTrip({subtype:"apply_flag_settings",settings:t},15e3);return s.error?{ok:!1,error:s.error==="timeout"?i("adapter.requestTimeout"):s.error}:{ok:!0}}async rewindToMessage(t){await dr(this.sessionId,t)}async endSession(t){await le(this.sessionId,{type:"control_request",request_id:Me(),request:{subtype:"end_session",...t?{reason:t}:{}}})}}function Qa(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}function jt({onBack:r,title:t,meta:s,actions:n}){return me(),e.jsx("div",{className:"flex-shrink-0 border-b border-nav-rule bg-surface-1/80 backdrop-blur-md",children:e.jsxs("div",{className:"mx-auto flex h-16 w-full page-measure items-center gap-2 px-4 sm:h-12 sm:px-8",children:[e.jsx("button",{type:"button",onClick:r,"aria-label":i("nav.dashboard"),title:i("nav.dashboard"),className:"-mx-2 flex min-h-11 flex-shrink-0 items-center rounded-md px-2 py-1 text-xs text-text-muted transition hover:-translate-x-0.5 hover:bg-surface-2 hover:text-text-primary sm:min-h-0",children:i("nav.dashboard")}),e.jsx("span",{className:"mx-1 h-4 w-px flex-shrink-0 bg-border","aria-hidden":"true"}),e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[t,s&&e.jsx("div",{className:"flex flex-shrink-0 items-center gap-2",children:s})]}),n&&e.jsx("div",{className:"flex flex-shrink-0 items-center gap-1 sm:gap-0.5",children:n}),e.jsx("span",{className:"mx-0.5 h-4 w-px flex-shrink-0 bg-border","aria-hidden":"true"}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-0.5",children:[e.jsx(mr,{className:"h-11 w-11 sm:h-7 sm:w-7"}),e.jsx(xr,{compact:!0,onSettingsClick:()=>{window.history.pushState(null,"","/settings"),window.dispatchEvent(new PopStateEvent("popstate"))}})]})]})})}function Wa(r){if(r<1e3)return"0s";const t=Math.floor(r/1e3);if(t<60)return`${t}s`;const s=Math.floor(t/60),n=t%60;if(s<60)return n?`${s}m${n}s`:`${s}m`;const l=Math.floor(s/60),d=s%60;return d?`${l}h${d}m`:`${l}h`}function za(r){return r===void 0||r<=0?"":r<1e3?`${r}`:r<1e6?`${(r/1e3).toFixed(r<1e4?1:0)}k`:`${(r/1e6).toFixed(1)}M`}function Ga({status:r}){return r==="running"?e.jsx(st,{className:"h-3 w-3 animate-spin text-brand-text"}):r==="completed"?e.jsx(Pa,{className:"h-3 w-3 text-status-success"}):r==="failed"||r==="stopped"?e.jsx(pr,{className:"h-3 w-3 text-status-error"}):null}function Ya({task:r,onStopTask:t,fullText:s}){const n=r.status==="running",l=n?r.durationMs??Date.now()-r.startTime:(r.endTime??Date.now())-r.startTime,d=za(r.tokenCount),c=r.toolUseCount!==void 0&&r.toolUseCount>0?`${r.toolUseCount} tool${r.toolUseCount>1?"s":""}`:"",u=r.summary||r.description||"(no description)";return e.jsxs("div",{className:"group/task flex items-start gap-2 rounded-md bg-surface-2 px-2.5 py-1.5 text-xs",children:[e.jsx("div",{className:"mt-0.5 flex-shrink-0",children:e.jsx(Ga,{status:r.status})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"truncate font-medium text-text-primary",children:r.name}),e.jsx("span",{className:"flex-shrink-0 font-mono text-text-muted",children:Wa(l)})]}),e.jsx("div",{className:`mt-0.5 text-text-secondary ${s?"line-clamp-2 break-words":"truncate"}`,children:u}),(d||c||r.lastToolName)&&e.jsxs("div",{className:"mt-0.5 flex items-center gap-x-2 overflow-hidden whitespace-nowrap font-mono text-[10px] text-text-muted",children:[d&&e.jsxs("span",{className:"flex-shrink-0",children:["↕ ",d," tok"]}),c&&e.jsxs("span",{className:"flex-shrink-0",children:["· ",c]}),r.lastToolName&&e.jsxs("span",{className:"min-w-0 truncate",children:["· last: ",r.lastToolName]})]}),!n&&r.finalSummary&&e.jsx("div",{className:"mt-1 line-clamp-2 rounded bg-status-success/10 px-1.5 py-0.5 text-[10px] text-status-success",children:r.finalSummary})]}),n&&t&&e.jsx("button",{type:"button",onClick:()=>t(r.taskId),title:i("subagent.stop"),className:"mt-0.5 flex-shrink-0 rounded p-0.5 text-text-muted opacity-0 transition-opacity hover:bg-status-error/10 hover:text-status-error focus:opacity-100 group-hover/task:opacity-100",children:e.jsx(Ze,{className:"h-3.5 w-3.5"})})]})}function Va(r){if(!r)return"never";const t=Math.max(0,Date.now()-r);return t<5e3?"just now":t<6e4?`${Math.floor(t/1e3)}s ago`:t<36e5?`${Math.floor(t/6e4)}m ago`:`${Math.floor(t/36e5)}h ago`}function Ja(r){return r?Date.now()-r<6e4:!1}function Xa({onClose:r,session:t,liveStatus:s,pendingPermissions:n,onInterrupt:l,onDelete:d,onOpenQueue:c,subagentState:u,onStopTask:y,onEndSession:f}){const[j,_]=o.useState(!1),E=async()=>{await navigator.clipboard.writeText(t.id),_(!0),setTimeout(()=>_(!1),1500)},[T,A]=o.useState(!1),N=async()=>{if(!(!f||T)&&window.confirm(i("task.endConfirm"))){A(!0);try{await f(),r()}catch{A(!1)}}},q=n.length,P=t.worker,I=t.work_item,$=t.environment;return e.jsx(ke,{open:!0,onOpenChange:p=>{p||r()},children:e.jsxs(Ne,{showCloseButton:!1,className:"fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-96 h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-md overflow-y-auto",children:[e.jsx(Re,{children:e.jsx(Se,{className:"font-display font-semibold text-text-primary",children:"Session Ops"})}),e.jsxs("div",{className:"mt-3 space-y-5 text-sm",children:[e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Status"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hr,{status:s||t.status||"unknown"}),e.jsx("span",{className:"text-xs text-text-muted",children:P&&(Ja(P.last_heartbeat_at)?"· worker online":"· worker offline")})]}),e.jsxs("dl",{className:"space-y-1 text-xs text-text-muted",children:[P&&e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("dt",{className:"flex items-center gap-1",children:[e.jsx(Ms,{className:"h-3 w-3"}),"Heartbeat"]}),e.jsx("dd",{className:"font-mono text-text-secondary",children:Va(P.last_heartbeat_at)})]}),(t.environment_id||$)&&e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("dt",{className:"flex items-center gap-1",children:[e.jsx(vn,{className:"h-3 w-3"}),"Machine"]}),e.jsx("dd",{className:"truncate text-text-secondary",children:($==null?void 0:$.machine_name)||t.environment_id||($==null?void 0:$.id)})]}),(t.cwd||(I==null?void 0:I.cwd))&&e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsxs("dt",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(ea,{className:"h-3 w-3"}),"Directory"]}),e.jsx("dd",{className:"min-w-0 truncate font-mono text-text-secondary",title:t.cwd||(I==null?void 0:I.cwd)||void 0,children:t.cwd||(I==null?void 0:I.cwd)})]}),t.created_at&&e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("dt",{className:"flex items-center gap-1",children:[e.jsx(Ms,{className:"h-3 w-3"}),"Created"]}),e.jsx("dd",{className:"font-mono text-text-secondary",children:fr(t.created_at)})]})]})]}),e.jsx(ti,{state:u,onStopTask:y}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(fn,{className:"h-3.5 w-3.5"}),i("task.pendingActions")]}),q>0?e.jsxs("button",{type:"button",onClick:c,disabled:!c,className:"permit-mini",title:c?i("permission.reviewShort"):void 0,"aria-label":K("permission.pendingAria",{n:q}),children:[e.jsx("span",{className:"permit-mini__count",children:q}),e.jsxs("span",{className:"permit-mini__body",children:[e.jsx("span",{className:"permit-mini__lead",children:i("task.pendingLead")}),e.jsxs("span",{className:"permit-mini__meta",children:[n.slice(0,2).map(p=>p.toolName).join(" · "),q>2?` +${q-2}`:""]})]}),c&&e.jsxs("span",{className:"permit-mini__action",children:[i("permission.reviewShort")," →"]})]}):e.jsx("p",{className:"text-xs text-text-muted",children:i("task.noPendingActions")})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx($a,{className:"h-3.5 w-3.5"}),"Quick Actions"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:l,className:"flex-1 rounded-md border border-border px-3 py-1.5 text-xs text-text-secondary hover:bg-surface-2 transition-colors",children:"Interrupt"}),f&&e.jsx("button",{onClick:N,disabled:T,className:"flex-1 rounded-md border border-status-error/30 px-3 py-1.5 text-xs text-status-error hover:bg-status-error/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:i("task.endHint"),children:T?"Ending…":"End session"}),e.jsxs("button",{onClick:d,className:"flex-1 rounded-md border border-status-error/30 px-3 py-1.5 text-xs text-status-error hover:bg-status-error/10 transition-colors",children:[e.jsx(yr,{className:"mr-1 inline h-3 w-3"}),"Delete"]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),"Session Info"]}),e.jsxs("dl",{className:"space-y-1 text-xs text-text-muted",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("dt",{children:"Session ID"}),e.jsxs("dd",{className:"flex items-center gap-1 min-w-0",children:[e.jsx("code",{className:"break-all font-mono text-text-secondary text-right",children:t.id}),e.jsx("button",{onClick:E,className:"text-text-muted hover:text-text-primary transition-colors flex-shrink-0",title:"Copy session id",children:j?"✓":"⧉"})]})]}),I&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{children:"Spawn mode"}),e.jsx("dd",{className:"font-mono text-text-secondary",children:I.spawn_mode??"default"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{children:"Work state"}),e.jsx("dd",{className:"font-mono text-text-secondary",children:I.state})]})]}),t.source&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{children:"Source"}),e.jsx("dd",{className:"font-mono text-text-secondary",children:t.source})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{children:"Worker"}),e.jsx("dd",{className:"font-mono text-text-secondary",children:wn(t.source==="acp"?"acp":$==null?void 0:$.worker_type).fullLabel})]})]})]})]})]})})}const Za={in_process_teammate:"task.type.teammates",local_bash:"task.type.shells",monitor_mcp:"task.type.monitors",remote_agent:"task.type.remoteAgents",local_agent:"task.type.localAgents"},ei=new Set(["dream"]);function ti({state:r,onStopTask:t}){const s=Object.values(r.tasks).some(y=>y.status==="running"),n=Object.values(r.tasks).some(y=>y.status!=="running"&&y.evictAfter!==void 0),[,l]=o.useState(0);o.useEffect(()=>{if(!s&&!n)return;const y=setInterval(()=>{l(f=>f+1)},1e3);return()=>clearInterval(y)},[s,n]);const d=Ua(r),c=d.filter(y=>y.status==="running").length,u=d.length-c;return e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(Ta,{className:"h-3.5 w-3.5"}),i("task.backgroundTasks")]}),d.length>0&&e.jsx("span",{className:"font-mono text-[10px] text-text-muted",children:c>0&&u>0?K("task.mixedCount",{running:c,recent:u}):c>0?K("task.runningCount",{count:c}):K("task.recentCount",{count:d.length})})]}),d.length===0?e.jsx("p",{className:"text-xs text-text-muted",children:i("task.noBackgroundTasks")}):e.jsx("div",{className:"max-h-[38vh] space-y-2 overflow-y-auto overscroll-contain pr-1",children:La(d).map(y=>{const f=!ei.has(y.taskType),j=Za[y.taskType]??"task.type.tasks";return e.jsxs("div",{className:"space-y-1",children:[f&&e.jsxs("div",{className:"pl-1 text-[10px] font-medium uppercase tracking-wide text-text-muted/80",children:[i(j)," (",y.tasks.length,")"]}),y.tasks.map(_=>e.jsx(Ya,{task:_,onStopTask:t,fullText:!0},_.taskId))]},y.taskType)})})]})}const si={connected:"bg-status-success/15 text-status-success",failed:"bg-status-error/15 text-status-error","needs-auth":"bg-status-warning/15 text-status-warning",pending:"bg-status-active/15 text-status-active",disabled:"bg-surface-3 text-text-muted"},ni={connected:"mcp.status.connected",failed:"mcp.status.failed","needs-auth":"mcp.status.needsAuth",pending:"mcp.status.pending",disabled:"mcp.status.disabled"};function ri({onClose:r,fetchServers:t,onToggle:s,onReconnect:n}){me();const[l,d]=o.useState(null),[c,u]=o.useState(null),[y,f]=o.useState(null),[j,_]=o.useState(null),E=o.useCallback(async()=>{f(null),_(null);try{const N=await t();d(N),u(null)}catch(N){St("[McpPanel] fetch failed",N),u(i("mcp.loadFailed"))}},[t]);o.useEffect(()=>{E()},[E]);const T=async N=>{const q=N.status==="disabled";f(`toggle:${N.name}`),_(null);try{const P=await s(N.name,q);P.ok||_(P.error||i("mcp.toggleFailed"))}finally{await E()}},A=async N=>{f(`reconnect:${N.name}`),_(null);try{const q=await n(N.name);q.ok||_(q.error||i("mcp.reconnectFailed"))}finally{await E()}};return e.jsx(ke,{open:!0,onOpenChange:N=>{N||r()},children:e.jsxs(Ne,{showCloseButton:!1,className:"fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-96 h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-md overflow-y-auto",children:[e.jsx(Re,{children:e.jsxs(Se,{className:"flex items-center gap-2 font-display font-semibold text-text-primary",children:[e.jsx(Bt,{className:"h-4 w-4"}),i("session.mcp.title")]})}),e.jsxs("div",{className:"mt-3 space-y-3 text-sm",children:[j&&e.jsx("div",{className:"rounded-md bg-status-error/10 px-3 py-2 text-xs text-status-error",children:j}),l===null&&!c&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[e.jsx(st,{className:"h-3.5 w-3.5 animate-spin"}),i("mcp.loading")]}),c&&e.jsx("p",{className:"text-xs text-status-error",children:c}),l!==null&&l.length===0&&e.jsx("p",{className:"text-xs text-text-muted",children:i("mcp.empty")}),l==null?void 0:l.map(N=>{const q=y===`toggle:${N.name}`,P=y===`reconnect:${N.name}`,I=N.status==="disabled";return e.jsx("div",{className:"rounded-lg border border-border bg-surface-2 px-3 py-2.5",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium text-text-primary",children:N.name}),e.jsx("span",{className:`flex-shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium ${si[N.status]}`,children:i(ni[N.status])})]}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-text-muted",children:[N.serverInfo?`${N.serverInfo.name} v${N.serverInfo.version}`:N.url||"stdio",N.toolCount!==void 0&&` · ${K("mcp.toolCount",{n:N.toolCount})}`]}),N.error&&e.jsx("div",{className:"mt-1 truncate text-xs text-status-error",title:N.error,children:N.error})]}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1",children:[e.jsx("button",{type:"button",onClick:()=>void A(N),disabled:P||I,className:"rounded-md p-1.5 text-text-muted hover:bg-surface-3 hover:text-text-primary transition-colors disabled:opacity-40 disabled:cursor-not-allowed",title:i("mcp.reconnect"),children:e.jsx(sa,{className:`h-3.5 w-3.5 ${P?"animate-spin":""}`})}),e.jsx("button",{type:"button",role:"switch","aria-checked":!I,onClick:()=>void T(N),disabled:q,className:`relative h-5 w-9 rounded-full transition-colors disabled:opacity-50 ${I?"bg-surface-3":"bg-brand"}`,title:I?i("mcp.enable"):i("mcp.disable"),children:e.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${I?"left-0.5":"left-4.5"}`})})]})]})},N.name)})]})]})})}const kn=[{key:"autoMemoryEnabled",labelKey:"settings.autoMemory",defaultValue:!0},{key:"teamMemoryEnabled",labelKey:"settings.teamMemory",defaultValue:!1}],ai=new Set(kn.map(r=>r.key));function ii(r){if(r==null)return i("settings.unset");if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}}function nn(r){if(r==null)return i("settings.unset");if(typeof r=="object")try{return JSON.stringify(r,null,2)}catch{return String(r)}return String(r)}function oi({onClose:r,fetchSettings:t,onApply:s}){me();const[n,l]=o.useState(null),[d,c]=o.useState(null),[u,y]=o.useState(""),[f,j]=o.useState(null),[_,E]=o.useState(null),[T,A]=o.useState(null),[N,q]=o.useState(!1),P=o.useCallback(async()=>{j(null),E(null),A(null),q(!1);try{const x=await t();l(x),c(x?null:i("settings.loadFailed"))}catch(x){St("[SettingsDrawer] fetch failed",x),c(i("settings.loadFailed"))}},[t]);o.useEffect(()=>{P()},[P]);const I=o.useMemo(()=>n?Object.entries(n.effective).filter(([,x])=>x!==void 0).filter(([x])=>!x.startsWith("memoryV2")).sort(([x],[M])=>x.localeCompare(M)):[],[n]),$=o.useMemo(()=>{const x=u.trim().toLowerCase();return x?I.filter(([M,U])=>`${M} ${ii(U)}`.toLowerCase().includes(x)):I},[I,u]),p=x=>typeof x[1]=="boolean",g=o.useMemo(()=>$.filter(p).filter(([x])=>!ai.has(x)),[$]),v=o.useMemo(()=>$.filter(x=>!p(x)),[$]),w=o.useMemo(()=>T===null?null:I.find(([x])=>x===T)??null,[I,T]),S=async()=>{if(w)try{await navigator.clipboard.writeText(nn(w[1])),q(!0),window.setTimeout(()=>q(!1),1500)}catch(x){St("[SettingsDrawer] copy failed",x)}},h=async(x,M)=>{j(x),E(null);try{const U=await s({[x]:!M});U.ok||E(U.error||i("settings.writeFailed"))}finally{await P()}};return e.jsx(ke,{open:!0,onOpenChange:x=>{x||r()},children:e.jsxs(Ne,{showCloseButton:!1,className:"fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-96 h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-md overflow-y-auto",children:[e.jsx(Re,{children:e.jsxs(Se,{className:"flex items-center gap-2 font-display font-semibold text-text-primary",children:[e.jsx(Ht,{className:"h-4 w-4"}),i("session.settings.title")]})}),e.jsxs("div",{className:"mt-3 space-y-4 text-sm",children:[_&&e.jsx("div",{className:"rounded-md bg-status-error/10 px-3 py-2 text-xs text-status-error",children:_}),n===null&&!d&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[e.jsx(st,{className:"h-3.5 w-3.5 animate-spin"}),i("settings.loading")]}),d&&e.jsx("p",{className:"text-xs text-status-error",children:d}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"rounded-lg border border-border bg-surface-2 px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-text-muted",children:i("settings.model")}),e.jsx("code",{className:"font-mono text-text-secondary",children:n.applied.model||i("settings.defaultModel")})]}),n.applied.effort&&e.jsxs("div",{className:"mt-1 flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-text-muted",children:"Effort"}),e.jsx("code",{className:"font-mono text-text-secondary",children:n.applied.effort})]}),e.jsx("p",{className:"mt-2 text-[10px] leading-relaxed text-text-muted",children:i("settings.hint")})]}),w?e.jsxs("section",{className:"space-y-2",children:[e.jsxs("button",{type:"button",onClick:()=>{A(null),q(!1)},className:"flex items-center gap-1.5 text-xs text-text-muted transition-colors hover:text-text-primary",children:[e.jsx(na,{className:"h-3.5 w-3.5"}),i("settings.back")]}),e.jsx("div",{className:"break-all font-mono text-xs font-medium text-text-primary",children:w[0]}),e.jsx("pre",{className:"max-h-[60vh] overflow-y-auto whitespace-pre-wrap break-all rounded-md border border-border bg-surface-2 p-3 font-mono text-[10px] leading-relaxed text-text-secondary",children:nn(w[1])}),e.jsxs("button",{type:"button",onClick:()=>void S(),className:"flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary",children:[N?e.jsx(Wt,{className:"h-3.5 w-3.5 text-status-success"}):e.jsx(aa,{className:"h-3.5 w-3.5"}),N?i("settings.copied"):i("settings.copyValue")]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-surface-2 px-2.5 py-1.5",children:[e.jsx(et,{className:"h-3.5 w-3.5 flex-shrink-0 text-text-muted"}),e.jsx("input",{value:u,onChange:x=>y(x.target.value),placeholder:i("settings.searchPlaceholder"),className:"w-full bg-transparent text-sm text-text-primary placeholder:text-text-muted focus:outline-none"})]}),$.length===0&&e.jsx("p",{className:"text-xs text-text-muted",children:i("settings.noMatch")}),e.jsxs("section",{className:"space-y-1.5",children:[e.jsx("h3",{className:"text-[10px] font-medium uppercase tracking-wide text-text-muted",children:i("settings.memorySection")}),kn.map(x=>{const M=n.effective[x.key],U=typeof M=="boolean"?M:x.defaultValue,X=f===x.key;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-border bg-surface-2 px-3 py-2",children:[e.jsx("div",{className:"truncate text-xs text-text-primary",children:i(x.labelKey)}),e.jsx("button",{type:"button",role:"switch","aria-checked":U,disabled:X,onClick:()=>void h(x.key,U),className:`relative h-5 w-9 flex-shrink-0 rounded-full transition-colors disabled:opacity-50 ${U?"bg-brand":"bg-surface-3"}`,title:U?i("settings.turnOff"):i("settings.turnOn"),children:e.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${U?"left-4.5":"left-0.5"}`})})]},x.key)}),e.jsx("p",{className:"text-[10px] leading-relaxed text-text-muted",children:i("settings.memoryHint")})]}),g.length>0&&e.jsxs("section",{className:"space-y-1.5",children:[e.jsx("h3",{className:"text-[10px] font-medium uppercase tracking-wide text-text-muted",children:K("settings.togglable",{n:g.length})}),g.map(([x,M])=>{const U=f===x;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-border bg-surface-2 px-3 py-2",children:[e.jsx("div",{className:"truncate font-mono text-xs text-text-primary",children:x}),e.jsx("button",{type:"button",role:"switch","aria-checked":M,disabled:U,onClick:()=>void h(x,M),className:`relative h-5 w-9 flex-shrink-0 rounded-full transition-colors disabled:opacity-50 ${M?"bg-brand":"bg-surface-3"}`,title:M?i("settings.turnOff"):i("settings.turnOn"),children:e.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${M?"left-4.5":"left-0.5"}`})})]},x)})]}),v.length>0&&e.jsxs("section",{className:"space-y-1.5",children:[e.jsx("h3",{className:"text-[10px] font-medium uppercase tracking-wide text-text-muted",children:K("settings.readOnly",{n:v.length})}),v.map(([x])=>e.jsxs("button",{type:"button",onClick:()=>A(x),className:"flex w-full items-center justify-between gap-3 rounded-md border border-border bg-surface-2 px-3 py-2 text-left transition-colors hover:bg-surface-3",title:i("settings.viewDetail"),children:[e.jsx("span",{className:"truncate font-mono text-xs text-text-primary",children:x}),e.jsx(ja,{className:"h-3.5 w-3.5 flex-shrink-0 text-text-muted"})]},x))]})]})]})]})]})})}function li({onClose:r,onAsk:t}){me();const[s,n]=o.useState([]),[l,d]=o.useState(""),[c,u]=o.useState(!1),y=async()=>{const f=l.trim();if(!f||c)return;const j=Date.now();n(_=>[..._,{id:j,question:f,answer:null}]),d(""),u(!0);try{const _=await t(f);n(E=>E.map(T=>T.id===j?{...T,answer:_??i("sideQuestion.noAnswer"),error:_===null}:T))}finally{u(!1)}};return e.jsx(ke,{open:!0,onOpenChange:f=>{f||r()},children:e.jsxs(Ne,{showCloseButton:!1,className:"fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-[26rem] h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-md flex flex-col",children:[e.jsx(Re,{children:e.jsxs(Se,{className:"flex items-center gap-2 font-display font-semibold text-text-primary",children:[e.jsx(Kt,{className:"h-4 w-4"}),i("sideQuestion.title")]})}),e.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-text-muted",children:i("sideQuestion.desc")}),e.jsxs("div",{className:"mt-3 flex-1 space-y-4 overflow-y-auto",children:[s.length===0&&e.jsx("p",{className:"text-xs text-text-muted",children:i("sideQuestion.empty")}),s.map(f=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-md border border-user-bubble-border bg-user-bubble px-4 py-2 text-sm text-text-primary",children:f.question})}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-brand/8 flex items-center justify-center flex-shrink-0 overflow-hidden",children:e.jsx("img",{src:"/code/pony.svg",alt:"Saluzi",width:24,height:24,className:"object-contain",draggable:!1})}),e.jsx("div",{className:"min-w-0 flex-1 pt-1 text-sm text-text-primary",children:f.answer===null?e.jsxs("span",{className:"chat-typing-indicator inline-flex items-center gap-1","aria-hidden":"true",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):e.jsx("div",{className:f.error?"text-status-error":"",children:e.jsx(gr,{children:f.answer})})})]})]},f.id))]}),e.jsxs("div",{className:"mt-3 flex items-end gap-2",children:[e.jsx("textarea",{value:l,onChange:f=>d(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&!f.nativeEvent.isComposing&&(f.preventDefault(),y())},rows:Math.min(4,Math.max(1,l.split(`
81
- `).length)),placeholder:i("sideQuestion.placeholder"),disabled:c,className:"flex-1 resize-none rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none disabled:opacity-50"}),e.jsx("button",{type:"button",onClick:()=>void y(),disabled:c||!l.trim(),className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-brand text-white transition-colors hover:bg-brand-light disabled:opacity-40 disabled:cursor-not-allowed",title:i("sideQuestion.send"),children:c?e.jsx(st,{className:"h-4 w-4 animate-spin"}):e.jsx(br,{className:"h-4 w-4"})})]})]})})}function ci({request:r,handlers:t,now:s,onRetry:n,variant:l}){const d=r.toolName,c=r.toolInput,u=r.description||"";if(r.sentAt!==void 0){const y=d!=="AskUserQuestion"&&d!=="ExitPlanMode";return e.jsx(jr,{decision:r.decision??"allow",stale:gn(r.sentAt,s),onRetry:y&&n?()=>n(r.requestId):void 0})}if(d==="AskUserQuestion"){const y=c.questions||[];return e.jsx(wr,{requestId:r.requestId,questions:y,description:u,onSubmit:f=>t.onSubmitAnswers(r.requestId,f,y),onSkip:()=>t.onReject(r.requestId)})}if(d==="ExitPlanMode"){const y=c.plan||"";return e.jsx(vr,{requestId:r.requestId,planContent:y,description:u,onSubmit:(f,j)=>t.onSubmitPlan(r.requestId,f,j)})}return e.jsx(kr,{requestId:r.requestId,toolName:d,toolInput:c,description:u,suggestions:r.suggestions,onApprove:()=>t.onApprove(r.requestId),onApproveAlways:r.suggestions&&r.suggestions.length>0?()=>t.onApproveAlways(r.requestId,r.suggestions):void 0,onReject:()=>t.onReject(r.requestId),variant:l})}function Nn(r){return r==="AskUserQuestion"?i("permission.waitingAnswer"):r==="ExitPlanMode"?i("permission.waitingPlan"):i("permission.waitingApprove")}function di(r){return r==="AskUserQuestion"?i("permission.answerShort"):r==="ExitPlanMode"?i("permission.reviewShort"):i("permission.allowShort")}function ui({requests:r,onView:t,onOpenQueue:s,onApprove:n,context:l}){if(me(),r.length===0)return null;const d=r.filter(f=>f.sentAt===void 0);if(d.length===0)return e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-1 sm:px-8",children:e.jsxs("button",{type:"button",onClick:s,className:"flex w-full items-center gap-2 border-l-2 border-border bg-surface-1/60 px-3 py-2 text-text-muted transition-colors hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",children:[e.jsx(st,{className:"h-3.5 w-3.5 flex-shrink-0 animate-spin text-approve-text","aria-hidden":"true"}),e.jsx("span",{role:"status","aria-live":"polite",className:"min-w-0 flex-1 text-left text-xs",children:i("permission.syncing")}),e.jsx("span",{className:"permit-mini__action flex-shrink-0",children:i("permission.view")})]})});const c=d[0],u=Nn(c.toolName),y=c.toolName==="AskUserQuestion"||c.toolName==="ExitPlanMode";return e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-1 sm:px-8",children:e.jsxs("div",{className:"permit-bar",children:[e.jsxs("div",{className:"permit-bar__main",children:[e.jsx(fn,{className:"h-4 w-4 flex-shrink-0 text-approve-text","aria-hidden":"true"}),e.jsx("span",{className:"permit-bar__label",children:u}),e.jsxs("span",{className:"permit-bar__detail",children:[c.toolName,c.description?` · ${c.description}`:"",l?` · ${l}`:""]})]}),e.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:K("permission.pendingAnnounce",{n:d.length,label:u,tool:c.toolName})}),e.jsx("button",{type:"button",onClick:()=>y?t(c):n(c.requestId),className:yn("permit-btn",y?"permit-btn--brand":"permit-btn--primary"),children:di(c.toolName)}),e.jsx("button",{type:"button",onClick:()=>t(c),title:i("permission.evidenceHint"),"aria-label":K("permission.revealAria",{tool:c.toolName}),className:"permit-btn permit-btn--secondary",children:i("permission.view")}),d.length>1&&e.jsx("button",{type:"button",onClick:s,className:"permit-btn permit-btn--quiet",children:K("permission.viewAll",{n:d.length})})]})})}function mi({open:r,onClose:t,requests:s,initialRequestId:n,now:l,errorMessage:d,errorRequestId:c,onRetry:u,context:y,...f}){me();const[j,_]=o.useState(null),E=o.useRef(!1),T=o.useRef(new Map),A=s.filter(S=>S.sentAt===void 0),N=s.find(S=>S.requestId===j)??A[0]??s[0];if(o.useEffect(()=>{var S,h;if(r&&!E.current){const x=n&&s.some(M=>M.requestId===n)?n:((S=A[0])==null?void 0:S.requestId)??((h=s[0])==null?void 0:h.requestId)??null;_(x),requestAnimationFrame(()=>{var M;x&&((M=T.current.get(x))==null||M.focus())})}E.current=r},[r,n,s,A]),o.useEffect(()=>{r&&s.length===0&&t()},[r,s.length,t]),o.useEffect(()=>{var h,x;if(!r||!j||s.some(M=>M.requestId===j))return;const S=((h=A[0])==null?void 0:h.requestId)??((x=s[0])==null?void 0:x.requestId)??null;_(S),requestAnimationFrame(()=>{var M;S&&((M=T.current.get(S))==null||M.focus())})},[r,j,s,A]),s.length===0)return null;const q=N&&c===N.requestId?d:void 0,P=S=>{if(!N)return;const h=s.findIndex(M=>M.requestId===N.requestId);if(h<0)return;const x=s[Math.min(Math.max(h+S,0),s.length-1)];_(x.requestId),requestAnimationFrame(()=>{var M;return(M=T.current.get(x.requestId))==null?void 0:M.focus()})};if(!N)return null;const I=S=>S.sentAt===void 0?Nn(S.toolName):gn(S.sentAt,l)?i("permission.ackStale"):i("permission.syncing"),$=N.toolName!=="AskUserQuestion"&&N.toolName!=="ExitPlanMode",p=s.findIndex(S=>S.requestId===N.requestId),g=String(Math.max(p,0)+1).padStart(2,"0"),v=hn(N.suggestions,N.toolName)[0],w=I(N);return e.jsx(ke,{open:r,onOpenChange:S=>{S||t()},children:e.jsxs(Ne,{showCloseButton:!1,onKeyDown:S=>{const h=S.target;h.tagName==="INPUT"||h.tagName==="TEXTAREA"||h.tagName==="SELECT"||h.isContentEditable||(S.key==="ArrowUp"?(S.preventDefault(),P(-1)):S.key==="ArrowDown"&&(S.preventDefault(),P(1)))},className:"permit-sheet permit-docket translate-x-0 translate-y-0",children:[e.jsxs(Re,{className:"permit-masthead permit-docket__masthead",children:[e.jsxs("div",{className:"permit-docket__top",children:[e.jsxs("span",{className:"permit-docket__runhead",children:[i("permission.docketRunhead")," · ",g]}),e.jsx("button",{type:"button",onClick:t,"aria-label":i("common.close"),title:i("common.close"),className:"permit-close",children:e.jsx(Ze,{className:"h-4 w-4","aria-hidden":"true"})})]}),y&&e.jsx("p",{className:"permit-docket__context",title:y,children:y}),e.jsx(Se,{className:"permit-docket__question",children:$&&N.sentAt===void 0?K("permission.allowQuestion",{tool:N.toolName}):i("permission.queueHeading")}),$?N.description?e.jsx(Fs,{className:"permit-docket__lede",children:N.description}):null:e.jsx(Fs,{className:"permit-docket__lede",children:i("permission.queueListHint")}),e.jsxs("dl",{className:"permit-docket__meta",children:[e.jsx("dt",{children:i("permission.docketTool")}),e.jsx("dd",{children:N.toolName}),e.jsx("dt",{children:i("permission.docketState")}),e.jsx("dd",{children:w}),e.jsx("dt",{children:i("permission.docketScope")}),e.jsx("dd",{children:(v==null?void 0:v.scope)??i("permission.scope.localSettings")})]})]}),s.length>1&&e.jsx("ul",{className:"permit-docket__list",children:s.map((S,h)=>{const x=S.requestId===N.requestId;return e.jsx("li",{children:e.jsxs("button",{ref:M=>{M?T.current.set(S.requestId,M):T.current.delete(S.requestId)},type:"button",onClick:()=>_(S.requestId),"aria-expanded":x,className:yn("permit-docket__row",x&&"permit-docket__row--active"),children:[e.jsx("span",{className:"permit-docket__row-index","aria-hidden":"true",children:String(h+1).padStart(2,"0")}),e.jsx("span",{className:"permit-docket__row-name",children:S.toolName}),e.jsx("span",{className:"permit-docket__row-desc",children:S.description}),e.jsx("span",{className:"permit-docket__row-state",children:I(S)})]})},S.requestId)})}),e.jsxs("div",{className:"permit-docket__body",children:[q&&e.jsxs("div",{role:"alert",className:"permit-error",children:[e.jsx("span",{className:"permit-error__text",children:q}),u&&e.jsx("button",{type:"button",onClick:()=>u(N.requestId),className:"permit-btn permit-btn--secondary permit-btn--tiny",children:i("common.retry")})]}),e.jsx(ci,{request:N,handlers:f,now:l,onRetry:u,variant:"docket"})]})]})})}function xi(r){const[t,s]=o.useState([]),[n,l]=o.useState(!0),[d,c]=o.useState(null),u=o.useCallback(async()=>{l(!0),c(null);try{const j=await Nr(r);s(j)}catch(j){c(j instanceof Error?j.message:"Failed to load shares")}finally{l(!1)}},[r]);o.useEffect(()=>{u()},[u]);const y=o.useCallback(async j=>{c(null);try{const _=await Sr(r,j);return await u(),_}catch(_){throw c(_ instanceof Error?_.message:"Failed to create share"),_}},[r,u]),f=o.useCallback(async j=>{c(null);try{await _r(r,j),await u()}catch(_){throw c(_ instanceof Error?_.message:"Failed to revoke share"),_}},[r,u]);return{shares:t,isLoading:n,error:d,createShare:y,revokeShare:f,refresh:u}}function pi({open:r,onClose:t,sessionId:s,sessionTitle:n}){me();const{shares:l,isLoading:d,error:c,createShare:u,revokeShare:y}=xi(s),[f,j]=o.useState("user"),[_,E]=o.useState(""),[T,A]=o.useState(""),[N,q]=o.useState("read"),[P,I]=o.useState(""),[$,p]=o.useState(!1),[g,v]=o.useState(null),[w,S]=o.useState(""),[h,x]=o.useState(!1),[M,U]=o.useState(!1);o.useEffect(()=>{r&&(j("user"),E(""),A(""),q("read"),I(""),p(!1),v(null),S(""),x(!1),U(!1))},[r]);const X=async()=>{p(!0),S(""),v(null);try{const D={grantedTo:f==="user"?{userId:_.trim()}:{teamId:T.trim()},permission:N};P.trim()&&(D.expiresAt=P.trim());const ne=await u(D);v(`${window.location.origin}/code/s/${ne.shareToken}`)}catch(D){S(D instanceof Error?D.message:"Failed to create share")}finally{p(!1)}},se=async D=>{try{await y(D)}catch{}},Q=async()=>{if(!g)return;U(!1);try{if(navigator.clipboard&&window.isSecureContext){await navigator.clipboard.writeText(g),x(!0),setTimeout(()=>x(!1),2e3);return}}catch{}const D=document.createElement("textarea");D.value=g,D.style.position="fixed",D.style.opacity="0",document.body.appendChild(D),D.select();try{document.execCommand("copy"),x(!0),setTimeout(()=>x(!1),2e3)}catch{U(!0)}document.body.removeChild(D)};return e.jsx(ke,{open:r,onOpenChange:D=>{D||t()},children:e.jsxs(Ne,{className:"max-w-lg rounded-2xl border-border bg-surface-1 p-6 shadow-2xl",children:[e.jsx(Re,{children:e.jsxs(Se,{className:"font-display text-lg font-semibold text-text-primary",children:[i("share.title"),n?`: ${n}`:""]})}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-text-secondary",children:i("share.grantTo")}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsx("button",{onClick:()=>j("user"),className:`rounded-md px-3 py-1 text-sm transition-colors ${f==="user"?"bg-brand text-white":"bg-surface-2 text-text-secondary hover:bg-surface-3"}`,children:i("share.user")}),e.jsx("button",{onClick:()=>j("team"),className:`rounded-md px-3 py-1 text-sm transition-colors ${f==="team"?"bg-brand text-white":"bg-surface-2 text-text-secondary hover:bg-surface-3"}`,children:i("share.team")})]}),f==="user"?e.jsx(ra,{onSelect:E,placeholder:i("share.userIdPlaceholder"),actionLabel:i("share.selectUser")}):e.jsx("input",{type:"text",value:T,onChange:D=>A(D.target.value),placeholder:i("share.teamIdPlaceholder"),className:"w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"}),f==="user"&&_&&e.jsxs("p",{className:"mt-1 text-xs text-text-muted",children:[i("share.selectedUser"),": ",e.jsx("span",{className:"font-mono",children:_})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-text-secondary",children:i("share.permission")}),e.jsxs("select",{value:N,onChange:D=>q(D.target.value),className:"w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-brand focus:outline-none",children:[e.jsx("option",{value:"read",children:i("share.permissionRead")}),e.jsx("option",{value:"write",children:i("share.permissionWrite")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-text-secondary",children:i("share.expiresAt")}),e.jsx("input",{type:"datetime-local",value:P,onChange:D=>I(D.target.value),className:"w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-brand focus:outline-none"})]}),(w||c)&&e.jsx("div",{className:"rounded-md bg-destructive/10 px-3 py-2 text-sm text-status-error",children:w||c}),g&&e.jsxs("div",{className:"rounded-md bg-surface-2 px-3 py-2",children:[e.jsx("p",{className:"text-sm text-text-secondary mb-1",children:i("share.linkCreated")}),e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[e.jsx("code",{className:"min-w-0 flex-1 break-all text-xs text-text-primary",children:g}),e.jsx("button",{onClick:Q,className:"shrink-0 rounded-md bg-brand px-2 py-1 text-xs text-white hover:bg-brand-light transition-colors",children:h?i("share.copied"):i("share.copy")})]}),M&&e.jsx("p",{className:"mt-1 text-xs text-status-error",children:i("share.copyFailed")})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium text-text-secondary",children:i("share.existingShares")}),d?e.jsx("p",{className:"text-sm text-text-muted",children:i("share.loading")}):l.length===0?e.jsx("p",{className:"text-sm text-text-muted",children:i("share.none")}):e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto",children:l.map(D=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md bg-surface-2 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm text-text-primary",children:D.granted_to_user||D.granted_to_team||"Unknown"}),e.jsxs("p",{className:"truncate text-xs text-text-muted",children:[D.permission==="write"?i("share.permissionWrite"):i("share.permissionRead"),D.expires_at?` · expires ${D.expires_at}`:""]})]}),e.jsx("button",{onClick:()=>se(D.id),className:"shrink-0 rounded-md px-2 py-1 text-xs text-status-error hover:bg-surface-3 transition-colors",children:i("share.revoke")})]},D.id))})]})]}),e.jsxs(Zr,{children:[e.jsx("button",{onClick:t,className:"rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors",children:i("common.close")}),e.jsx("button",{onClick:X,disabled:$||(f==="user"?!_.trim():!T.trim()),className:"rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light disabled:opacity-50 transition-colors",children:$?i("common.creating"):i("share.createShare")})]})]})})}function hi(r){const t=new Date,s=new Date(t.getTime()-1440*60*1e3),n=(c,u)=>c.getFullYear()===u.getFullYear()&&c.getMonth()===u.getMonth()&&c.getDate()===u.getDate(),l={today:[],yesterday:[],earlier:[]};for(const c of r){const u=new Date(c.modified||0);n(u,t)?l.today.push(c):n(u,s)?l.yesterday.push(c):l.earlier.push(c)}return[["today",i("resume.today")],["yesterday",i("resume.yesterday")],["earlier",i("resume.earlier")]].map(([c,u])=>({label:u,items:l[c]})).filter(c=>c.items.length>0)}function fi(r){return r?new Date(r).toLocaleString():""}function yi({open:r,onClose:t,adapter:s,onResume:n}){const l=me(),[d,c]=o.useState([]),[u,y]=o.useState(!1),[f,j]=o.useState("");o.useEffect(()=>{if(!r)return;let E=!1;return y(!0),j(""),c([]),s.listResumableSessions().then(T=>{E||c(T)}).catch(T=>{E||j(T instanceof Error?T.message:String(T))}).finally(()=>{E||y(!1)}),()=>{E=!0}},[r,s]);const _=o.useMemo(()=>hi(d),[d,l]);return e.jsx(ke,{open:r,onOpenChange:E=>{E||t()},children:e.jsxs(Ne,{className:"max-w-lg rounded-2xl border-border bg-surface-1 p-6 shadow-2xl",children:[e.jsx(Re,{children:e.jsx(Se,{className:"font-display text-lg font-semibold text-text-primary",children:i("session.resume.title")})}),e.jsxs("div",{className:"max-h-96 min-w-0 space-y-4 overflow-y-auto",children:[u&&e.jsx("p",{className:"py-6 text-center text-sm text-text-muted",children:i("resume.loading")}),!u&&f&&e.jsx("div",{className:"rounded-md bg-destructive/10 px-3 py-2 text-sm text-status-error",children:f}),!u&&!f&&d.length===0&&e.jsx("p",{className:"py-6 text-center text-sm text-text-muted",children:i("resume.empty")}),!u&&!f&&_.map(E=>e.jsxs("div",{children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-text-muted",children:E.label}),e.jsx("div",{className:"space-y-1",children:E.items.map(T=>e.jsxs("button",{type:"button",onClick:()=>n(T),className:"w-full rounded-md px-3 py-2 text-left transition-colors hover:bg-surface-3",children:[e.jsx("p",{className:"truncate text-sm text-text-primary",children:T.title}),e.jsxs("p",{className:"truncate text-xs text-text-muted",children:[fi(T.modified),T.gitBranch?` · ${T.gitBranch}`:""]})]},T.sessionId))})]},E.label))]}),e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx("button",{type:"button",onClick:t,className:"rounded-lg border border-border px-4 py-2 text-sm text-text-secondary transition-colors hover:bg-surface-2",children:i("common.cancel")})})]})})}const rn=["working","episodic","semantic","procedural"],gi=["user","feedback","project","reference"];function bi({refreshTick:r,recall:t,dreaming:s,onDreamTrigger:n}){me();const{myTeams:l}=Cr(),[d,c]=o.useState(null),[u,y]=o.useState("memories"),[f,j]=o.useState("personal"),[_,E]=o.useState([]),[T,A]=o.useState(!1),[N,q]=o.useState(""),[P,I]=o.useState(""),[$,p]=o.useState(null),[g,v]=o.useState(null),[w,S]=o.useState(!1),[h,x]=o.useState(Ft),M=la(),[U,X]=o.useState(""),[se,Q]=o.useState(null),[D,ne]=o.useState(!1),Z=o.useRef(null);o.useEffect(()=>{bn().then(c).catch(()=>c(null))},[]);const ce=o.useCallback(async()=>{A(!0),q("");try{E(await Er(f))}catch{q(i("memorySidebar.loadFailed"))}finally{A(!1)}},[f]);o.useEffect(()=>{ce()},[ce,r]),o.useEffect(()=>{const b=()=>void ce();return window.addEventListener("focus",b),()=>window.removeEventListener("focus",b)},[ce]),o.useEffect(()=>{u==="governance"&&Tr().then(v).catch(()=>v(null))},[u,r]),o.useEffect(()=>{Z.current&&clearTimeout(Z.current);const b=P.trim();if(!b){p(null);return}return Z.current=setTimeout(()=>{Mr(b).then(p).catch(()=>p([]))},300),()=>{Z.current&&clearTimeout(Z.current)}},[P]);const Ue=b=>M.expandedKey===b?e.jsx("pre",{className:"mt-1 max-h-48 overflow-y-auto whitespace-pre-wrap rounded bg-surface-3 p-2 text-[10px] leading-relaxed text-text-secondary",children:M.fileContent[b]??"…"}):null,be=(d==null?void 0:d.mode)==="sqlite",[oe,z]=o.useState(!1),[pe,G]=o.useState(""),[je,we]=o.useState(""),[ie,Ae]=o.useState("project"),[Le,nt]=o.useState(""),[Ke,Ie]=o.useState(""),[re,_e]=o.useState(!1),V=()=>{var b;z(!0),G(""),we(""),Ae("project"),nt(""),Ie(((b=l[0])==null?void 0:b.id)??"")},Ce=be&&f==="team",rt=pe.trim().length>0&&Le.trim().length>0&&!re&&(!Ce||!!Ke),_t=async()=>{if(rt){_e(!0),q("");try{await Pr({scope:f,name:pe.trim(),description:je.trim()||void 0,type:ie,content:Le,...Ce?{teamId:Ke}:{}}),z(!1),await ce()}catch(b){q(b instanceof Error?b.message:i("memorySidebar.createFailed"))}finally{_e(!1)}}},ee=()=>{n==null||n()},at=o.useCallback(async()=>{const b=U.trim();if(!(!b||D)){ne(!0),Q(null);try{Q(await Rr(b,5))}catch{Q([])}finally{ne(!1)}}},[U,D]),he=(d==null?void 0:d.teamEnabled)===!0,Be=d==null?void 0:d.automation,Ct=he&&u==="memories"&&!P,Pe=o.useMemo(()=>ca(_,h),[_,h]),He=o.useMemo(()=>da(_),[_]),Ee=(h.types.size>0?1:0)+(ua(h.layers)?0:1)+(h.days!==null?1:0)+(h.minConfidence>0?1:0)+(h.minAccessCount>0?1:0);return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsxs("div",{className:"flex items-center gap-4 px-3 pt-2 pb-1",children:[["memories","governance"].map(b=>e.jsxs("button",{type:"button",onClick:()=>y(b),"aria-pressed":u===b,className:`relative pb-1 text-xs tracking-wide transition-colors ${u===b?"font-semibold text-text-primary":"text-text-muted hover:text-text-secondary"}`,children:[i(b==="memories"?"memorySidebar.memoriesTab":"memorySidebar.governanceTab"),e.jsx("span",{"aria-hidden":"true",className:`absolute inset-x-0 -bottom-2 h-px bg-brand transition-opacity duration-200 ${u===b?"opacity-100":"opacity-0"}`})]},b)),e.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[u==="memories"&&!P&&e.jsx("button",{type:"button",onClick:oe?()=>z(!1):V,disabled:f==="team"&&!he,className:"rounded p-1 text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-50",title:i("memorySidebar.new"),children:oe?e.jsx(Ar,{className:"h-3 w-3"}):e.jsx(Ir,{className:"h-3 w-3"})}),u==="memories"&&!P&&e.jsxs("button",{type:"button",onClick:()=>S(b=>!b),"data-testid":"memory-filter-toggle",className:`relative rounded p-1 transition-colors ${w||Ee>0?"text-brand-text":"text-text-secondary hover:bg-surface-2 hover:text-text-primary"}`,title:i("memorySidebar.filters"),children:[e.jsx(Os,{className:"h-3 w-3"}),Ee>0&&!w&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-3 min-w-3 items-center justify-center rounded-full bg-brand px-0.5 text-[10px] font-bold text-white",children:Ee})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[e.jsx(et,{className:"h-3 w-3 flex-shrink-0 text-text-muted"}),e.jsx("input",{value:P,onChange:b=>I(b.target.value),placeholder:i("memorySidebar.searchPlaceholder"),title:i("memorySidebar.searchHint"),className:"w-full min-w-0 bg-transparent text-xs text-text-primary placeholder:text-text-muted focus:outline-none"}),e.jsx("span",{className:"flex-shrink-0 font-mono text-[10px] tabular-nums text-text-muted",children:$!==null?$.length:Pe.length})]}),N&&e.jsx("p",{className:"px-3 py-1 text-xs text-status-error",children:N}),w&&u==="memories"&&!P&&e.jsxs("div",{className:"space-y-2.5 px-3 pb-3","data-testid":"memory-filter-panel",children:[e.jsx(ma,{filters:h,onChange:x}),e.jsx(xa,{filters:h,onChange:x,counts:He}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-text-muted",children:i("memories.filter.time")}),e.jsx("div",{className:"flex rounded-md bg-surface-2 p-0.5 text-[10px]",children:pa.map(b=>e.jsx("button",{type:"button",onClick:()=>x(te=>({...te,days:b.value})),className:`rounded px-1.5 py-0.5 ${h.days===b.value?"bg-brand-light text-white":"text-text-muted hover:text-text-secondary"}`,children:i(b.labelKey)},String(b.value)))})]}),e.jsxs("div",{className:"flex items-center gap-1.5",title:i("memories.filter.confidence"),children:[e.jsx("span",{className:"flex-shrink-0 text-[10px] text-text-muted",children:i("memories.filter.confidence")}),e.jsx("input",{type:"range",min:0,max:100,step:10,value:h.minConfidence*100,onChange:b=>x(te=>({...te,minConfidence:Number(b.target.value)/100})),style:{"--mem-pct":`${h.minConfidence*100}%`},className:"mem-slider min-w-16 flex-1"}),e.jsx("span",{className:`flex-shrink-0 font-mono text-[10px] ${h.minConfidence>0?"text-brand-text":"text-text-muted"}`,children:K("memories.filter.minConfidence",{pct:h.minConfidence*100})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",title:i("memories.filter.access"),children:[e.jsx("span",{className:"flex-shrink-0 text-[10px] text-text-muted",children:i("memories.filter.access")}),e.jsx("input",{type:"range",min:0,max:10,step:1,value:h.minAccessCount,onChange:b=>x(te=>({...te,minAccessCount:Number(b.target.value)})),style:{"--mem-pct":`${h.minAccessCount*10}%`},className:"mem-slider min-w-12 flex-1"}),e.jsx("span",{className:`flex-shrink-0 font-mono text-[10px] ${h.minAccessCount>0?"text-brand-text":"text-text-muted"}`,children:K("memories.filter.minAccess",{n:h.minAccessCount})}),e.jsx("button",{type:"button",onClick:()=>x(Ft),disabled:!Us(h),className:"flex-shrink-0 rounded px-1 py-0.5 text-[10px] text-text-muted transition-colors hover:bg-surface-2 hover:text-text-primary disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-text-muted",children:i("memories.filter.clear")})]})]}),Be&&Be.mode!=="normal"&&e.jsx("div",{className:"border-b border-status-warning/30 bg-status-warning/10 px-3 py-1.5 text-xs text-status-warning",children:Be.mode==="sa"?i("memorySidebar.saModeBanner"):i("memorySidebar.poorModeBanner")}),$!==null&&e.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-1.5",children:$.length===0?e.jsx("p",{className:"py-8 text-center text-xs text-text-muted",children:i("memorySidebar.noResults")}):e.jsx("ul",{className:"space-y-1",children:$.map(b=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>void M.toggleExpand({path:b.path}),className:"w-full rounded-md px-2 py-1.5 text-left hover:bg-surface-2",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-xs font-medium text-text-primary",children:b.name}),e.jsx(ha,{layer:b.layer})]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5",children:b.matches.map((te,De)=>e.jsxs("li",{className:"flex gap-1.5 text-[10px] leading-relaxed",children:[e.jsx("span",{className:"flex-shrink-0 font-mono text-text-muted",children:te.line===0?"file":`L${te.line}`}),e.jsx("span",{className:"truncate text-text-secondary",children:te.text})]},De))})]}),Ue(b.path)]},b.path))})}),$===null&&u==="memories"&&e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-1.5",children:[t&&t.hits.length>0&&e.jsxs("div",{className:"mb-3 border-l-2 border-brand/30 pl-2.5",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-brand-text",children:i("memorySidebar.recallTitle")}),e.jsxs("p",{className:"mb-1 truncate text-[10px] text-text-muted",title:t.query,children:[i("memorySidebar.recallQuery"),": ",t.query]}),e.jsx("ul",{className:"space-y-0.5",children:t.hits.slice(0,5).map(b=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>void M.toggleExpand({path:b.path}),className:"flex w-full items-center justify-between gap-2 rounded px-1 py-0.5 text-left text-xs hover:bg-surface-2",title:b.path,children:[e.jsx("span",{className:"truncate text-text-secondary",children:b.path.replace(/^team\//,"").replace(/\.md$/,"")}),b.score!==void 0&&e.jsxs("span",{className:"flex-shrink-0 text-[10px] text-text-muted",children:[(b.score*100).toFixed(0),"%"]})]}),Ue(b.path)]},b.path))})]}),Ct&&e.jsx("div",{className:"mb-2 flex items-center gap-4 px-1 text-xs",children:["personal","team"].map(b=>e.jsx("button",{type:"button",onClick:()=>j(b),className:`pb-1 transition-colors ${f===b?"font-semibold text-text-primary":"text-text-muted hover:text-text-secondary"}`,children:b==="personal"?i("memorySidebar.personal"):i("memorySidebar.team")},b))}),f==="team"&&he&&!oe&&e.jsx("p",{className:"mb-2 px-1 text-[10px] leading-relaxed text-text-muted",children:i("memorySidebar.teamHint")}),oe&&e.jsxs("div",{className:"mb-2 space-y-1.5 rounded-md bg-surface-2 p-2",children:[e.jsx("input",{value:pe,onChange:b=>G(b.target.value),placeholder:i("memorySidebar.create.namePlaceholder"),className:"w-full rounded bg-surface-3 px-2 py-1 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-brand/40"}),e.jsx("input",{value:je,onChange:b=>we(b.target.value),placeholder:i("memorySidebar.create.descriptionPlaceholder"),className:"w-full rounded bg-surface-3 px-2 py-1 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-brand/40"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("select",{value:ie,onChange:b=>Ae(b.target.value),className:"flex-shrink-0 rounded bg-surface-3 px-1.5 py-1 text-xs text-text-primary focus:outline-none",children:gi.map(b=>e.jsx("option",{value:b,children:b},b))}),Ce?e.jsxs("select",{value:Ke,onChange:b=>Ie(b.target.value),"aria-label":i("memories.scope.team"),className:"min-w-0 flex-1 rounded bg-surface-3 px-1.5 py-1 text-xs text-text-primary focus:outline-none",children:[l.length===0&&e.jsx("option",{value:"",children:"—"}),l.map(b=>e.jsx("option",{value:b.id,children:b.name},b.id))]}):e.jsx("span",{className:"truncate text-[10px] text-text-muted",children:f==="team"?i("memorySidebar.team"):i("memorySidebar.personal")})]}),e.jsx("textarea",{value:Le,onChange:b=>nt(b.target.value),placeholder:i("memorySidebar.create.contentPlaceholder"),rows:6,className:"w-full rounded bg-surface-3 p-2 text-[10px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-brand/40"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{type:"button",onClick:()=>void _t(),disabled:!rt,className:"rounded bg-accent px-2 py-0.5 text-[10px] font-medium text-white hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50",children:re?"…":i("memorySidebar.new")}),e.jsx("button",{type:"button",onClick:()=>z(!1),className:"rounded px-2 py-0.5 text-[10px] text-text-muted hover:bg-surface-3",children:i("memorySidebar.cancel")})]})]}),T?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(b=>e.jsx("div",{className:"h-12 animate-pulse rounded-md bg-surface-2"},b))}):_.length===0?e.jsxs("div",{className:"py-10 text-center",children:[e.jsx(Lt,{className:"mx-auto h-6 w-6 text-text-muted/40"}),e.jsx("p",{className:"mt-2 text-xs text-text-muted",children:i("memorySidebar.empty")})]}):Pe.length===0?e.jsxs("div",{className:"py-10 text-center",children:[e.jsx(Os,{className:"mx-auto h-6 w-6 text-text-muted/40"}),e.jsx("p",{className:"mt-2 text-xs text-text-muted",children:i("memories.filter.empty")}),Us(h)?e.jsx("button",{type:"button",onClick:()=>x(Ft),className:"mt-2 rounded-md px-2.5 py-1 text-xs text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary",children:i("memories.filter.clear")}):e.jsx("p",{className:"mt-1 px-4 text-[10px] leading-relaxed text-text-muted",children:i("memories.filter.layersHidden")})]}):e.jsx(fa,{files:Pe,teamEnabled:he,teams:be?l:void 0,onChanged:ce,expandedKey:M.expandedKey,fileContent:M.fileContent,onToggleExpand:M.toggleExpand})]}),$===null&&u==="governance"&&e.jsx("div",{className:"flex-1 overflow-y-auto p-3 text-xs",children:g?e.jsxs("div",{className:"space-y-4",children:[n&&e.jsxs("div",{children:[e.jsxs("button",{type:"button",disabled:s||!g.automation.autoDream,onClick:ee,className:"inline-flex w-full items-center justify-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx(ia,{className:"h-3.5 w-3.5"}),s?i("memorySidebar.dreaming"):i("memorySidebar.dream")]}),!g.automation.autoDream&&e.jsx("p",{className:"mt-1 text-center text-[10px] text-text-muted",children:i("memorySidebar.dreamDisabled")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1 text-[10px] font-semibold uppercase tracking-wide text-text-muted",children:i("memorySidebar.recallTest.title")}),e.jsx("p",{className:"mb-1.5 text-[10px] leading-relaxed text-text-muted",children:i("memorySidebar.recallTest.hint")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("input",{value:U,onChange:b=>X(b.target.value),onKeyDown:b=>{b.key==="Enter"&&!b.nativeEvent.isComposing&&at()},placeholder:i("memorySidebar.recallTest.placeholder"),className:"min-w-0 flex-1 rounded-md bg-surface-2 px-2 py-1 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-brand/40"}),e.jsx("button",{type:"button",onClick:()=>void at(),disabled:D||!U.trim(),className:"flex-shrink-0 rounded-md bg-accent px-2.5 py-1 text-xs font-medium text-white hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50",children:D?i("memorySidebar.recallTest.running"):i("memorySidebar.recallTest.run")})]}),se!==null&&e.jsx("ul",{className:"mt-1.5 space-y-0.5 rounded-md bg-surface-2 p-2",children:se.length===0?e.jsx("li",{className:"text-[10px] text-text-muted",children:i("memorySidebar.recallTest.noResults")}):se.map(b=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>void M.toggleExpand({path:b.path}),className:"flex w-full items-center justify-between gap-2 rounded px-1 py-0.5 text-left text-xs hover:bg-surface-3",title:b.path,children:[e.jsx("span",{className:"truncate text-text-secondary",children:b.path.replace(/^team\//,"").replace(/\.md$/,"")}),e.jsxs("span",{className:"flex-shrink-0 text-[10px] text-text-muted",children:[(b.score*100).toFixed(0),"%",b.confidence!==void 0?` · conf ${b.confidence.toFixed(2)}`:""]})]}),Ue(b.path)]},b.path))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted",children:i("memorySidebar.layers")}),e.jsx("ul",{className:"space-y-1",children:rn.map(b=>{const te=g.layers[b],De=Math.max(...rn.map(it=>g.layers[it]),1);return e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-16 flex-shrink-0 text-text-secondary",children:b}),e.jsx("div",{className:"h-1.5 flex-1 overflow-hidden rounded-full bg-surface-2",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${te/De*100}%`}})}),e.jsx("span",{className:"w-6 text-right text-text-muted",children:te})]},b)})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted",children:i("memorySidebar.health")}),e.jsxs("div",{className:"rounded-md bg-surface-2 p-2 text-[10px] text-text-secondary",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:i("memorySidebar.total")}),e.jsx("span",{children:g.health.totalMemories})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:i("memorySidebar.capacity")}),e.jsxs("span",{className:g.health.capacity.tier==="critical"?"text-status-error":g.health.capacity.tier==="warning"?"text-status-warning":"text-status-active",children:[g.health.capacity.utilizationPct.toFixed(0),"% · ",g.health.capacity.tier]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:i("memorySidebar.avgConfidence")}),e.jsx("span",{children:g.health.avgConfidence.toFixed(2)})]})]})]}),g.alerts.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted",children:[i("memorySidebar.alerts")," (",g.alerts.length,")"]}),e.jsx("ul",{className:"space-y-1 rounded-md bg-status-warning/5 p-2",children:g.alerts.slice(-8).reverse().map((b,te)=>e.jsx("li",{className:"text-[10px] leading-relaxed text-text-secondary",children:b},te))})]}),g.conflicts&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-status-warning",children:i("memorySidebar.conflicts")}),e.jsx("pre",{className:"max-h-40 overflow-y-auto whitespace-pre-wrap rounded-md bg-surface-2 p-2 text-[10px] leading-relaxed text-text-secondary",children:g.conflicts})]})]}):e.jsx("p",{className:"py-10 text-center text-text-muted",children:i("memorySidebar.loadFailed")})})]})}class ji{constructor(t,s,n,l){F(this,"pending",null);this.current=t,this.apply=s,this.send=n,this.onError=l}set(t){if(t===this.current)return;const s=this.current;this.current=t,this.pending={requestId:null,previous:s},this.apply(t);try{Promise.resolve(this.send(t)).then(n=>{this.pending&&(this.pending.requestId=n)}).catch(n=>{this.rollback(s,an(n),"send")})}catch(n){this.rollback(s,an(n),"send")}}handleControlResponse(t){const s=this.pending;if(!s||s.requestId!==t.requestId)return!1;const{previous:n}=s;return this.pending=null,t.subtype==="error"&&this.rollback(n,t.error??"","response"),!0}sync(t){t!==this.current&&(this.current=t,this.apply(t),this.pending=null)}adoptExternal(t){this.pending||t!==this.current&&(this.current=t)}getCurrent(){return this.current}rollback(t,s,n){var l;this.pending=null,this.current=t,this.apply(t),s&&((l=this.onError)==null||l.call(this,s,n))}}function an(r){return r instanceof Error?r.message:String(r)}function wt(r){const t=o.useRef(r);t.current=r;const s=o.useRef(null);s.current||(s.current=new ji(r.value,l=>t.current.apply(l),l=>t.current.send(l),(l,d)=>{var c,u;return(u=(c=t.current).onError)==null?void 0:u.call(c,l,d)}));const n=s.current;return o.useEffect(()=>{n.adoptExternal(r.value)}),o.useMemo(()=>({set:l=>n.set(l),handleControlResponse:l=>n.handleControlResponse(l),sync:l=>n.sync(l)}),[n])}const Sn="rcs_context_usage_";function _n(){try{if(typeof localStorage<"u")return localStorage}catch{}return null}function on(){return{totalTokens:0,rawMaxTokens:0,percentage:0}}function wi(r){if(!r||typeof r!="object"||Array.isArray(r))return null;const t=r,{totalTokens:s,rawMaxTokens:n,percentage:l}=t;if(typeof s!="number"||typeof n!="number"||typeof l!="number")return null;const d=t.categories,c=Array.isArray(d)?d.filter(u=>!!u&&typeof u=="object"&&typeof u.name=="string").map(u=>({name:u.name,tokens:typeof u.tokens=="number"?u.tokens:0,...u.isDeferred===!0?{isDeferred:!0}:{}})):void 0;return{totalTokens:s,rawMaxTokens:n,percentage:l,...typeof t.model=="string"&&t.model?{model:t.model}:{},...c&&c.length>0?{categories:c}:{}}}function vi(r,t=_n()){if(!t||!r)return null;try{const s=t.getItem(Sn+r);return s?wi(JSON.parse(s)):null}catch{return null}}function ki(r,t,s=_n()){if(!(!s||!r))try{s.setItem(Sn+r,JSON.stringify(t))}catch{}}const Ni=[{key:"nav",entries:["artifacts","memories","side","search","mcp","settings","share","tasks"]},{key:"bar",entries:["mode","model","token","context"]}];function Si(){return me(),e.jsx("div",{className:"w-full",children:Ni.map((r,t)=>e.jsxs("section",{className:t>0?"mt-8 min-w-0":"min-w-0",children:[e.jsx("h4",{className:"sr-only",children:i(`session.emptyGuide.${r.key}`)}),e.jsx("dl",{className:"grid grid-cols-1 gap-y-[0.95rem]",children:r.entries.map(s=>e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-y-[0.15rem] sm:grid-cols-[minmax(0,9.5rem)_minmax(0,1fr)] sm:items-baseline sm:gap-x-5 sm:gap-y-0",children:[e.jsx("dt",{className:"font-sans text-[0.8125rem] font-medium leading-[1.45] text-text-primary",children:i(`session.emptyGuide.${r.key}.${s}`)}),e.jsx("dd",{className:"font-sans text-xs leading-[1.5] text-text-muted",children:i(`session.emptyGuide.${r.key}.${s}Desc`)})]},s))})]},r.key))})}function _i(r){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/acp/relay/${r}`}function Ci(r){const t=_i(r),s=qr(),n=s?{proxyUrl:t,token:s}:{proxyUrl:t};return new Dr(n)}const Oe=[{value:"default",labelKey:"session.mode.default",descKey:"session.mode.defaultDesc"},{value:"acceptEdits",labelKey:"session.mode.acceptEdits",descKey:"session.mode.acceptEditsDesc"},{value:"plan",labelKey:"session.mode.plan",descKey:"session.mode.planDesc"},{value:"bypassPermissions",labelKey:"session.mode.bypass",descKey:"session.mode.bypassDesc"}],ln="rcs_permission_mode";function vt(r){return r<1e3?String(r):r<1e6?`${(r/1e3).toFixed(1)}k`:`${(r/1e6).toFixed(1)}M`}function Ei(r){const t=Oe.findIndex(s=>s.value===r);return Oe[(t+1+Oe.length)%Oe.length].value}const tt=[{value:"off",labelKey:"session.thinking.off",descKey:"session.thinking.offDesc",label:void 0,description:void 0,tokens:0},{value:"on",labelKey:"session.thinking.on",descKey:"session.thinking.onDesc",label:void 0,description:void 0,tokens:null},{value:"8192",labelKey:void 0,descKey:void 0,label:"8k",description:"8192 tokens",tokens:8192},{value:"16384",labelKey:void 0,descKey:void 0,label:"16k",description:"16384 tokens",tokens:16384},{value:"32768",labelKey:void 0,descKey:void 0,label:"32k",description:"32768 tokens",tokens:32768}],cn="rcs_thinking_budget",Nt=[{value:"auto",effort:void 0,labelKey:"session.effort.auto",descKey:"session.effort.autoDesc",label:void 0},{value:"low",effort:"low",labelKey:void 0,descKey:"session.effort.lowDesc",label:"low"},{value:"medium",effort:"medium",labelKey:void 0,descKey:"session.effort.mediumDesc",label:"medium"},{value:"high",effort:"high",labelKey:void 0,descKey:"session.effort.highDesc",label:"high"},{value:"xhigh",effort:"xhigh",labelKey:void 0,descKey:"session.effort.xhighDesc",label:"xhigh"},{value:"max",effort:"max",labelKey:void 0,descKey:"session.effort.maxDesc",label:"max"}],Ti=r=>r.labelKey?i(r.labelKey):r.label,Mi=r=>r.labelKey?i(r.labelKey):r.label,dn="rcs_effort",un=[{value:"normal",descKey:"session.tokenMode.normalDesc"},{value:"poor",descKey:"session.tokenMode.poorDesc"},{value:"sa",descKey:"session.tokenMode.saDesc"}],mn="rcs_token_mode";function Ri(r){return r!=null&&r.capabilities?r.capabilities:r?{file_search:!0,clear:!0,set_max_thinking_tokens:!0,get_context_usage:!0,stop_task:!0,set_model:!0,set_permission_mode:!0,interrupt:!0,end_session:!0,mcp_management:!0,remote_settings:!0,rewind:!0,resume:!0,set_effort:!0,set_token_mode:!1,side_question:!0}:{file_search:!1,clear:!0,set_max_thinking_tokens:!0,get_context_usage:!1,stop_task:!0,set_model:!0,set_permission_mode:!0,interrupt:!0,end_session:!1,mcp_management:!1,remote_settings:!1,rewind:!1,resume:!1,set_effort:!1,set_token_mode:!1,side_question:!1}}function xn({icon:r,label:t,levels:s,index:n,onChange:l,disabled:d}){const c=Math.max(s.length-1,0),u=Math.min(Math.max(n,0),c),[y,f]=o.useState(null),j=y??u,_=s[j],E=c>0?j/c*100:0,T=()=>{y!==null&&(y!==u&&l(y),f(null))};return e.jsxs("div",{className:d?"opacity-55":void 0,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-brand/10 text-brand-text",children:e.jsx(r,{className:"h-3 w-3",strokeWidth:2})}),e.jsx("span",{className:"truncate font-display text-xs font-semibold text-text-primary",children:t})]}),e.jsx("span",{className:"shrink-0 rounded-full border border-brand/20 bg-brand/10 px-1.5 py-0.5 font-mono text-[10px] font-medium tabular-nums text-brand-text",children:_.label})]}),e.jsxs("div",{className:"relative mt-2 h-6",children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-[7px] top-1/2 h-[3px] -translate-y-1/2 overflow-hidden rounded-full bg-surface-3",children:e.jsx("div",{className:"h-full rounded-full bg-brand transition-[width] duration-200 ease-out",style:{width:`${E}%`}})}),e.jsx("div",{className:"pointer-events-none absolute inset-x-[7px] top-1/2 h-[7px] -translate-y-1/2",children:s.map((A,N)=>e.jsx("span",{className:`absolute top-0 h-full w-[1.5px] -translate-x-1/2 rounded-full ${N<=j?"bg-primary-foreground/55":"bg-text-muted/25"}`,style:{left:c>0?`${N/c*100}%`:"50%"}},A.value))}),e.jsx("input",{type:"range",min:0,max:c,step:1,value:j,disabled:d,"aria-label":t,"aria-valuetext":_.label,onChange:A=>f(Number(A.target.value)),onPointerUp:T,onKeyUp:T,onBlur:T,className:"rcs-range relative z-10"})]}),e.jsx("div",{className:"mt-1 flex items-start justify-between gap-1",children:s.map((A,N)=>e.jsx("button",{type:"button",disabled:d,onClick:()=>{f(null),l(N)},className:`min-w-0 truncate font-mono text-[10px] leading-4 tabular-nums transition-colors disabled:cursor-not-allowed ${N===j?"font-semibold text-brand-text":"text-text-muted/70 hover:text-text-primary"}`,children:A.label},A.value))}),e.jsx("p",{className:"mt-0.5 min-h-4 text-xs leading-4 text-text-muted",children:_.description})]})}function Ai({mode:r,onModeChange:t,disabled:s}){const[n,l]=o.useState(!1),d=un.find(c=>c.value===r);return e.jsxs(zt,{open:n,onOpenChange:l,children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:s,className:"flex items-center gap-1.5 rounded-lg px-2 h-7 text-xs text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-display",title:i("session.tokenMode.title"),children:[e.jsx(va,{className:"h-3 w-3"}),e.jsx("span",{className:`min-w-0 truncate ${r!=="normal"?"font-medium text-brand-text":""}`,children:d?i(`session.tokenMode.${d.value}`):i("session.tokenMode.fallback")}),n?e.jsx(Yt,{className:"h-3 w-3"}):e.jsx(Vt,{className:"h-3 w-3"})]})}),e.jsx(Jt,{className:"w-64 p-1",align:"start",children:un.map(c=>e.jsxs("button",{type:"button",onClick:()=>{t(c.value),l(!1)},className:"flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left hover:bg-surface-2 transition-colors",children:[e.jsx("span",{className:"mt-0.5 flex h-4 w-4 flex-shrink-0 items-center justify-center",children:r===c.value&&e.jsx(Wt,{className:"h-3.5 w-3.5 text-brand-text"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-text-primary",children:i(`session.tokenMode.${c.value}`)}),e.jsx("div",{className:"text-xs text-text-muted",children:i(c.descKey)})]})]},c.value))})]})}const Ii=new Set(["Free space","Autocompact buffer","Compact buffer"]),pn=["bg-brand","bg-status-active","bg-status-success","bg-violet-500","bg-amber-500","bg-pink-500","bg-teal-500"];function Pi({usage:r}){const t=Math.min(100,Math.max(0,r.percentage)),s=t>=80,n=(r.categories??[]).filter(u=>!u.isDeferred&&!Ii.has(u.name)),l=(r.categories??[]).filter(u=>u.isDeferred),d=n.reduce((u,y)=>u+y.tokens,0),c=[`${K("session.context.tooltip",{used:vt(r.totalTokens),max:vt(r.rawMaxTokens)})}${r.model?` · ${r.model}`:""}`,...n.slice(0,8).map(u=>`${u.name}: ${vt(u.tokens)}`),...l.slice(0,3).map(u=>`${u.name.replace(/\s*\(deferred\)$/i,"")}${i("session.context.deferredSuffix")}: ${vt(u.tokens)}`)];return e.jsxs("span",{className:"flex items-center gap-1.5 text-[10px] text-text-muted font-mono",title:c.join(`
82
- `),children:[e.jsx("span",{className:"relative flex h-1.5 w-16 overflow-hidden rounded-full bg-surface-3",children:n.length>0?n.map((u,y)=>e.jsx("span",{className:s&&y===0?"bg-status-warning":pn[y%pn.length],style:{width:`${Math.min(100,Math.max(0,d>0?u.tokens/d*t:0))}%`}},u.name)):e.jsx("span",{className:`absolute inset-y-0 left-0 rounded-full transition-all ${s?"bg-status-warning":"bg-brand/70"}`,style:{width:`${t}%`}})}),e.jsxs("span",{children:[t,"%"]})]})}function Di({models:r,currentModelId:t,onSelect:s,showThinking:n,thinkingBudget:l,onThinkingChange:d,showEffort:c,effort:u,onEffortChange:y,disabled:f}){const[j,_]=o.useState(!1),E=r.find(w=>w.modelId===t)??null,T=r.length>0,A=n||c,N=T||A,q=tt.findIndex(w=>w.value===l),P=q>=0?q:1,I=Nt.findIndex(w=>w.value===u),$=I>=0?I:0,p=tt.map(w=>({value:w.value,label:Mi(w),description:w.descKey?i(w.descKey):w.description??""})),g=Nt.map(w=>({value:w.value,label:Ti(w),description:i(w.descKey)})),v=[i("session.model.title"),n?p[P].label:null,c?g[$].label:null].filter(Boolean).join(" · ");return e.jsxs(zt,{open:j,onOpenChange:N?_:void 0,children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:f||!N,className:"flex items-center gap-1.5 rounded-lg px-2 h-7 text-xs text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-display",title:v,children:[e.jsx(vn,{className:"h-3 w-3"}),e.jsx("span",{className:"min-w-0 truncate",children:(E==null?void 0:E.name)??t??i("session.model.title")}),A&&e.jsxs("span",{className:"ml-0.5 flex items-center gap-1 border-l border-border/70 pl-1.5",children:[n&&e.jsx(Bs,{className:"h-3 w-3"}),c&&e.jsx(Ks,{className:"h-3 w-3"})]}),j?e.jsx(Yt,{className:"h-3 w-3"}):e.jsx(Vt,{className:"h-3 w-3"})]})}),e.jsxs(Jt,{className:"w-[21rem] max-w-[calc(100vw-2rem)] max-h-[calc(100dvh-2rem)] overflow-y-auto overflow-x-hidden p-0",align:"start",children:[e.jsxs("div",{className:"px-3 pt-3 pb-1.5",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between px-1",children:[e.jsx("span",{className:"font-display text-[10px] font-semibold uppercase tracking-[0.16em] text-text-muted",children:i("session.model.section")}),T&&e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-text-muted",children:r.length})]}),T?e.jsx("div",{className:"[&_[data-slot=command-list]]:max-h-[min(15rem,38vh)]",children:e.jsx(Jr,{models:r,currentModelId:t,onSelect:w=>{s(w.modelId),_(!1)},showSearch:r.length>5})}):e.jsx("p",{className:"px-1 py-2 text-xs text-text-muted",children:i("session.model.unavailable")})]}),A&&e.jsxs("div",{className:"border-t border-border/60 bg-surface-2/35 px-3 pt-2.5 pb-3",children:[e.jsx("div",{className:"mb-2.5 px-1",children:e.jsx("span",{className:"font-display text-[10px] font-semibold uppercase tracking-[0.16em] text-text-muted",children:i("session.model.tuning")})}),e.jsxs("div",{className:"space-y-3.5",children:[n&&e.jsx(xn,{icon:Bs,label:i("session.thinking.title"),levels:p,index:P,onChange:w=>d(tt[w].value),disabled:f}),c&&e.jsx(xn,{icon:Ks,label:i("session.effort.title"),levels:g,index:$,onChange:w=>y(Nt[w].value),disabled:f})]})]})]})]})}function qi({mode:r,onModeChange:t,disabled:s}){const[n,l]=o.useState(!1),d=Oe.find(c=>c.value===r);return e.jsxs(zt,{open:n,onOpenChange:l,children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:s,className:"flex items-center gap-1.5 rounded-lg px-2 h-7 text-xs text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-display",title:i("session.mode.title"),children:[e.jsx(Vr,{className:"h-3 w-3"}),e.jsx("span",{className:"min-w-0 truncate",children:d?i(d.labelKey):r}),n?e.jsx(Yt,{className:"h-3 w-3"}):e.jsx(Vt,{className:"h-3 w-3"})]})}),e.jsx(Jt,{className:"w-64 p-1",align:"start",children:Oe.map(c=>e.jsxs("button",{type:"button",onClick:()=>{t(c.value),l(!1)},className:"flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left hover:bg-surface-2 transition-colors",children:[e.jsx("span",{className:"mt-0.5 flex h-4 w-4 flex-shrink-0 items-center justify-center",children:r===c.value&&e.jsx(Wt,{className:"h-3.5 w-3.5 text-brand-text"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-text-primary",children:i(c.labelKey)}),e.jsx("div",{className:"text-xs text-text-muted",children:i(c.descKey)})]})]},c.value))})]})}function Xi({sessionId:r,onBack:t}){var Cs;me();const[s,n]=o.useState(null),[l,d]=o.useState(null),[c,u]=o.useState(""),[y,f]=o.useState(!1),[j,_]=o.useState(!1),[E,T]=o.useState(!1),[A,N]=o.useState(!1),[q,P]=o.useState(!1),[I,$]=o.useState(!1),[p,g]=o.useState(!1),[v,w]=o.useState(""),[S,h]=o.useState(0),x=o.useRef(null),[M,U]=o.useState({text:"",nonce:0}),[X,se]=o.useState(!1),[Q,D]=o.useState(!1),[ne,Z]=o.useState(0),[ce,Ue]=o.useState(0),[be,oe]=o.useState([]),[z,pe]=o.useState(!1),[G,je]=o.useState([]),we=o.useRef(G);we.current=G;const ie=o.useMemo(()=>G.filter(a=>a.sentAt===void 0),[G]),Ae=o.useRef(!1),[Le,nt]=o.useState(null),[Ke,Ie]=o.useState(()=>Date.now()),[re,_e]=o.useState(null),[V,Ce]=o.useState(null),[rt,_t]=o.useState(()=>Qt()),[ee,at]=o.useState(null),[he,Be]=o.useState(()=>localStorage.getItem(cn)||"off"),[Ct,Pe]=o.useState(()=>vi(r)),[He,Ee]=o.useState(!0),[b,te]=o.useState(null),[De,it]=o.useState(null),[ot,lt]=o.useState([]),[Cn,Et]=o.useState(!1),[Tt,Xt]=o.useState(""),Mt=o.useRef(null),[ct,En]=o.useState(()=>localStorage.getItem(ln)||"default"),[Zt,es]=o.useState(null),Qe=o.useRef(null),[ts,ss]=o.useState(null),We=o.useRef(null),fe=o.useRef(null),dt=o.useRef(new Set),ns=o.useRef(0),[rs,Tn]=o.useState(0),[de,as]=o.useState(null),ze=o.useRef(null),Ge=o.useRef(new Map),ut=o.useRef(new Map),is=o.useRef(null);is.current=re;const os=o.useRef(null),ls=o.useRef(be);ls.current=be;const mt=o.useRef(null);mt.current||(mt.current=new ya(ga()));const cs=o.useRef(r);cs.current=(s==null?void 0:s.title)||r,o.useEffect(()=>{var a;(a=mt.current)==null||a.reset()},[r]),o.useEffect(()=>{re&&!j&&requestAnimationFrame(()=>{var a;return(a=os.current)==null?void 0:a.focus()})},[re,j]),o.useEffect(()=>{ns.current>0&&G.length===0&&(Tn(a=>a+1),j&&(_(!1),requestAnimationFrame(()=>{var a;return(a=document.getElementById("chat-input"))==null?void 0:a.focus()}))),ns.current=G.length},[G.length,j]),o.useEffect(()=>{if(!G.some(k=>k.sentAt!==void 0))return;const m=setInterval(()=>Ie(Date.now()),1e3);return()=>clearInterval(m)},[G]);const ye=o.useCallback(a=>{es(a),Qe.current&&clearTimeout(Qe.current),Qe.current=setTimeout(()=>es(null),5e3)},[]),ve=o.useCallback(a=>{ss(a),We.current&&clearTimeout(We.current),We.current=setTimeout(()=>ss(null),5e3)},[]),xt=wt({value:ct,apply:a=>{En(a);try{localStorage.setItem(ln,a)}catch{}},send:a=>{const m=fe.current;return m?m.setPermissionMode(a):Promise.reject(new Error("adapter not ready"))},onError:(a,m)=>{console.error("[SessionDetail] set permission mode failed:",a),ye(m==="send"?K("session.mode.switchFailedRequest",{message:a}):a||i("session.mode.switchFailed"))}}),Rt=o.useCallback(a=>xt.set(a),[xt]),[ds,Mn]=o.useState(()=>localStorage.getItem(mn)||"normal"),pt=wt({value:ds,apply:a=>{Mn(a);try{localStorage.setItem(mn,a)}catch{}},send:a=>{const m=fe.current;return m?m.setTokenMode(a):Promise.reject(new Error("adapter not ready"))},onError:(a,m)=>{console.error("[SessionDetail] set token mode failed:",a),ye(m==="send"?K("session.tokenMode.failedRequest",{message:a}):a||i("session.tokenMode.failed"))}}),At=wt({value:he,apply:a=>{Be(a);try{localStorage.setItem(cn,a)}catch{}},send:a=>{var C;const m=fe.current;if(!m)return Promise.reject(new Error("adapter not ready"));const k=((C=tt.find(R=>R.value===a))==null?void 0:C.tokens)??null;return m.setThinkingBudget(k)},onError:(a,m)=>{console.error("[SessionDetail] set thinking budget failed:",a),ye(m==="send"?K("session.thinking.failedRequest",{message:a}):a||i("session.thinking.failed"))}}),Rn=o.useCallback((a,m,k)=>{as({tool:a,decision:m,remembered:k,nonce:Date.now()}),ze.current&&clearTimeout(ze.current),ze.current=setTimeout(()=>as(null),2200)},[]);o.useEffect(()=>()=>{ze.current&&clearTimeout(ze.current)},[]);const L=o.useMemo(()=>new Ha(r,oe,{onStatusChange:a=>{var m;d(a),pe(a==="running"||a==="requires_action"),(m=mt.current)==null||m.onStatus(a,cs.current)},onError:a=>{console.error("[RCSChatAdapter] error:",a)},onPermissionRequest:a=>{je(m=>m.some(k=>k.requestId===a.requestId)?m:[...m,a])},onPermissionSettled:(a,m)=>{var R;if(a===null){je([]),Ge.current.clear(),ut.current.clear();return}const k=we.current.find(O=>O.requestId===a),C=Ge.current.get(a);k&&m&&Rn(k.toolName,m,C),Ge.current.delete(a),ut.current.delete(a),((R=is.current)==null?void 0:R.requestId)===a&&_e(null),je(O=>O.filter(W=>W.requestId!==a))},onModelsStateChange:a=>{Ce(a)},onSubagentUpdate:a=>{_t(a)},onControlResponse:a=>{At.handleControlResponse(a)||pt.handleControlResponse(a)||ps.handleControlResponse(a)||xt.handleControlResponse(a)},onPermissionModeChange:a=>{xt.sync(a)},onWorkerInfoChange:a=>{at(m=>JSON.stringify(m)===JSON.stringify(a)?m:a)},onTurnStart:a=>{te(a)},onElicitationRequest:a=>{it(a)}}),[r,ye]);o.useEffect(()=>(fe.current=L,()=>{L.disconnect()}),[L]);const B=o.useMemo(()=>Ri(ee),[ee]),us=o.useRef(!1);o.useEffect(()=>{var k;if(!B.set_max_thinking_tokens||us.current)return;const a=fe.current;if(!a)return;const m=((k=tt.find(C=>C.value===he))==null?void 0:k.tokens)??null;a.setThinkingBudget(m).then(()=>{us.current=!0}).catch(C=>console.error("[SessionDetail] reconcile thinking budget failed:",C))},[B.set_max_thinking_tokens,he,ee]);const An=B.stop_task?a=>{L.stopSubagent(a).then(m=>{m.ok||ve(m.error||i("session.stopTask.failed"))})}:void 0,ms=o.useRef(!1);o.useEffect(()=>{if(!B.set_token_mode||ms.current)return;const a=fe.current;a&&(ms.current=!0,a.getRemoteSettings().then(m=>{const k=m==null?void 0:m.applied.tokenMode;(k==="normal"||k==="poor"||k==="sa")&&pt.sync(k)}).catch(m=>console.error("[SessionDetail] reconcile token mode failed:",m)))},[B.set_token_mode,pt]);const In=me(),It=o.useMemo(()=>$r((ee==null?void 0:ee.commands)??[],(ee==null?void 0:ee.skills)??[]),[ee,In]),Ye=o.useMemo(()=>Fr(be,v),[be,v]),Pn=o.useCallback(a=>At.set(a),[At]),[xs,Dn]=o.useState(()=>localStorage.getItem(dn)||"auto"),ps=wt({value:xs,apply:a=>{Dn(a);try{localStorage.setItem(dn,a)}catch{}},send:a=>{var C;const m=fe.current;if(!m)return Promise.reject(new Error("adapter not ready"));const k=(C=Nt.find(R=>R.value===a))==null?void 0:C.effort;return m.setEffort(k)},onError:(a,m)=>{console.error("[SessionDetail] set effort failed:",a),ye(m==="send"?K("session.effort.failedRequest",{message:a}):a||i("session.effort.failed"))}}),Ve=o.useCallback(()=>{var a;B.get_context_usage&&((a=fe.current)==null||a.getContextUsage().then(m=>{m&&(Pe(m),ki(r,m))}).catch(()=>{}).finally(()=>Ee(!1)))},[B,r]);o.useEffect(()=>{if(!B.get_context_usage)return;Ve();const a=setInterval(Ve,6e4);return()=>clearInterval(a)},[B,z,Ve]);const hs=(V==null?void 0:V.currentModelId)??null;o.useEffect(()=>{hs&&Ve()},[hs,Ve]),o.useEffect(()=>{ee&&!B.get_context_usage&&Ee(!1)},[ee,B]),o.useEffect(()=>{if(!He)return;const a=setTimeout(()=>Ee(!1),1e4);return()=>clearTimeout(a)},[He]);const fs=o.useRef(Q);fs.current=Q,o.useEffect(()=>xe.onEvent(m=>{m.type!=="artifact_created"&&m.type!=="artifact_updated"||(fs.current&&Ue(k=>k+1),Z(k=>k+1))}),[]);const[qn,ht]=o.useState(0),[ft,ys]=o.useState(null),[ge,yt]=o.useState(!1),[qe,gs]=o.useState(0),[$n,Fn]=o.useState(void 0),gt=o.useRef(ge);gt.current=ge,o.useEffect(()=>xe.onEvent(m=>{m.type==="memory_synced"&&gt.current&&ht(k=>k+1)}),[]),o.useEffect(()=>{bn().then(a=>ys(a.mode)).catch(()=>ys("sqlite"))},[]),o.useEffect(()=>xe.onEvent(m=>{var k,C;if(m.type==="memory_changed")gt.current?ht(R=>R+1):gs(R=>R+1);else if(m.type==="memory_recall"){const R=Array.isArray((k=m.payload)==null?void 0:k.hits)?m.payload.hits:void 0;R&&Fn({query:typeof((C=m.payload)==null?void 0:C.query)=="string"?m.payload.query:"",hits:R}),gt.current&&ht(O=>O+1)}}),[]),o.useEffect(()=>{ge&&gs(0)},[ge]);const[Je,On]=o.useState("idle");o.useEffect(()=>xe.onStateChange(m=>On(m)),[]),o.useEffect(()=>{Q&&Z(0)},[Q]);const $e=o.useCallback(async()=>{if(Ae.current)return;Ae.current=!0;const a=new Set(we.current.map(m=>m.requestId));try{const k=(await Or(r)).permissions.filter(C=>!L.isPermissionSettled(C.requestId));k.some(C=>C.sentAt!==void 0)&&Ie(Date.now()),je(C=>{const R=new Set(k.map(W=>W.requestId)),O=C.filter(W=>!a.has(W.requestId)&&!R.has(W.requestId)&&!L.isPermissionSettled(W.requestId));return[...k,...O]})}catch{}finally{Ae.current=!1}},[r,L]);o.useEffect(()=>{let a=xe.state;return xe.onStateChange((k,C)=>{const R=k==="open"&&(a==="reconnecting"||a==="failed");(C!=null&&C.resync||R)&&$e(),a=k})},[$e]),o.useEffect(()=>{const a=()=>{document.visibilityState==="visible"&&$e()};return document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)},[$e]),o.useEffect(()=>{let a=!1;async function m(){u("");try{const k=await $s(r);if(a)return;n(k),d(k.status),kt(k.status)&&L.markClosed(),pe(k.status==="running"||k.status==="requires_action")}catch(k){if(a)return;u(k instanceof Error?k.message:i("session.loadFailed"));return}try{await L.init()}catch(k){console.warn("Failed to init adapter:",k)}a||await $e()}return m(),()=>{a=!0}},[r,L,$e]);const H=kt(l),bs=o.useRef(l);bs.current=l,o.useEffect(()=>{if(H)return;let a=!1;const k=setInterval(async()=>{try{const C=await $s(r);if(a||C.status===bs.current)return;kt(C.status)&&L.markClosed(),d(C.status),pe(C.status==="running"||C.status==="requires_action")}catch{}},6e4);return()=>{a=!0,clearInterval(k)}},[r,H,L]);const Y=(s==null?void 0:s.access_level)==="read",js=Ct??(He&&!H&&!Y?on():null),Pt=o.useCallback(()=>{oe([]),Pe(on()),Rs(r).catch(a=>{console.warn("[SessionDetail] Failed to clear session history:",a)})},[r]),Xe=o.useCallback(async(a,m)=>{const k=fe.current;if(!k||H)return;if(a.sessionId===r){oe(R=>[...R,{type:"command_output",id:`cmd-resume-${Date.now()}`,commandName:"resume",inputText:m??"/resume",title:"Resume",subtitle:i("session.resume.title"),outputText:i("session.resume.currentBlocked"),variant:"error"}]);return}const C=(R,O="default")=>oe(W=>[...W,{type:"command_output",id:`cmd-resume-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,commandName:"resume",inputText:m??`/resume ${a.sessionId.slice(0,8)}`,title:"Resume",subtitle:i("session.resume.title"),outputText:R,variant:O}]);C(K("session.resume.restoring",{title:a.title??""}));try{await Rs(r),oe([]);const R=await k.resumeSession(a.sessionId);C(R.title?K("session.resume.restoredWithTitle",{count:R.messageCount,title:R.title}):K("session.resume.restored",{count:R.messageCount}))}catch(R){C(K("session.resume.failed",{message:R instanceof Error?R.message:String(R)}),"error")}},[H,r]),Un=o.useCallback(async()=>{if(s!=null&&s.environment_id)try{const a=await Ur({environment_id:s.environment_id});window.location.href=`/code/${a.id}?resumeFrom=${r}`}catch(a){ve(K("session.createFailedWithReason",{message:a instanceof Error?a.message:String(a)}))}},[s,r,ve]),Ln=o.useRef(new URLSearchParams(window.location.search).get("resumeFrom")),ws=o.useRef(!1);o.useEffect(()=>{const a=Ln.current;!a||ws.current||!ee||!B.resume||(ws.current=!0,window.history.replaceState({},"",window.location.pathname),Xe({sessionId:a,title:a.slice(0,8),modified:0},null))},[ee,B.resume,Xe]);const Fe=o.useCallback(async a=>{const m=a.text.trim(),k=a.images&&a.images.length>0||a.attachments&&a.attachments.length>0;if(!m&&!k||H)return;const C=/^\/resume(?:\s+(.*))?$/.exec(m);if(C){const O=(C[1]??"").trim();if(!B.resume){oe(W=>[...W,{type:"user_message",id:`user-${Date.now()}`,content:m},{type:"command_output",id:`cmd-${Date.now()}`,commandName:"resume",inputText:m,title:"Resume",subtitle:i("session.resume.title"),outputText:i("session.resume.unsupported"),variant:"error"}]);return}O?await Xe({sessionId:O,title:O,modified:0},m):$(!0);return}const R=await Lr(m,{sessionId:r,availableCommands:It,availableModels:(V==null?void 0:V.availableModels)??[],currentModel:V?{modelId:V.currentModelId,name:V.currentModelId}:null,supportsImages:!0,entries:ls.current,setModel:async O=>{await le(r,{type:"control_request",request:{subtype:"set_model",model:O}}),Ce(W=>W&&{...W,currentModelId:O})},onNewSession:()=>{oe([])}}).catch(()=>null);if(R){if(St("[SessionDetail] local command result",R),"clearEntries"in R&&R.clearEntries){Pt();return}if("newSession"in R&&R.newSession){Pt();return}if("userEntry"in R){oe(O=>[...O,R.userEntry,R.cmdEntry]);return}}pe(!0);try{await L.sendMessage(m,a.images,a.attachments)}catch(O){if(console.error("Send failed:",O),O instanceof Kr&&O.type==="session_closed"){d("archived"),L.markClosed(),ve(i("session.closedSendBlocked"));return}ve(`${i("session.sendFailed")}${O instanceof Error?`: ${O.message}`:""}`)}},[L,H,r,V,It,Pt,ve,Xe,B]),Kn=o.useCallback(a=>{if(z){lt(m=>[...m,a]);return}Fe(a)},[z,Fe]),[Dt,vs]=o.useState(!1),Bn=o.useCallback(()=>{z||(vs(!0),Fe({text:"/dream"}))},[z,Fe]);o.useEffect(()=>{!z&&Dt&&(vs(!1),ht(a=>a+1))},[z,Dt]);const qt=o.useRef(!1);o.useEffect(()=>{if(H){lt(m=>m.length>0?[]:m);return}if(z||ot.length===0||qt.current)return;const a=ot[0];a&&(qt.current=!0,lt(m=>m.slice(1)),Fe(a).finally(()=>{qt.current=!1}))},[z,ot,Fe,H]);const Hn=o.useCallback((a,m)=>{if(z)return;const k=m==="edit"?i("session.rewind.confirmEdit"):i("session.rewind.confirm");window.confirm(`${k}
83
- ${i("session.rewind.confirmBody")}`)&&L.rewindToMessage(a.id).then(()=>{m==="edit"&&a.content&&U(C=>({text:a.content,nonce:C.nonce+1}))}).catch(C=>{console.error("[SessionDetail] rewind failed:",C),ve(K("session.rewind.failed",{message:C instanceof Error?C.message:String(C)}))})},[z,ve]),Qn=o.useCallback(a=>{const m=Ye.orderedMatchIds;if(m.length===0)return;const k=(a%m.length+m.length)%m.length;h(k);const C=m[k],R=document.querySelector(`[data-entry-id="${CSS.escape(C)}"]`);R==null||R.scrollIntoView({block:"center",behavior:"smooth"})},[Ye]),ks=o.useCallback(async()=>{try{await L.interrupt()}catch(a){console.error("Interrupt failed:",a)}finally{pe(!1)}},[L]),Wn=o.useCallback(()=>{Rt(Ei(ct))},[Rt,ct]);o.useEffect(()=>()=>{Qe.current&&clearTimeout(Qe.current),We.current&&clearTimeout(We.current)},[]);const zn=o.useCallback(async()=>{if(s&&window.confirm(i("dashboard.confirmDelete").replace("{id}",s.title||s.id)))try{await As(s.id),window.location.href="/code/"}catch(a){alert(a instanceof Error?a.message:i("dashboard.deleteFailed"))}},[s]),J=o.useCallback(async a=>{var m,k;if(!dt.current.has(a.requestId)){dt.current.add(a.requestId),ut.current.set(a.requestId,a),Ge.current.delete(a.requestId);try{switch(a.kind){case"approve":await L.respondPermission(a.requestId,!0);break;case"approveAlways":{const O=((m=we.current.find(sr=>sr.requestId===a.requestId))==null?void 0:m.toolName)??"tool",W=Br(a.suggestions,O);W&&Ge.current.set(a.requestId,W),await L.respondPermission(a.requestId,!0,{updated_permissions:a.suggestions});break}case"reject":await L.respondPermission(a.requestId,!1);break;case"answers":await le(r,{type:"permission_response",approved:!0,request_id:a.requestId,updated_input:{questions:a.questions,answers:a.answers}});break;case"plan":if(a.value==="no")await le(r,{type:"permission_response",approved:!1,request_id:a.requestId,...a.feedback?{message:a.feedback}:{}});else{const O={"yes-accept-edits":"acceptEdits","yes-default":"default"};await le(r,{type:"permission_response",approved:!0,request_id:a.requestId,updated_permissions:[{type:"setMode",mode:O[a.value]||"default",destination:"session"}]})}break}const C=Date.now(),R=a.kind==="reject"||a.kind==="plan"&&a.value==="no"?"deny":"allow";Ie(C),je(O=>O.map(W=>W.requestId===a.requestId?{...W,sentAt:C,decision:R}:W)),_e(null)}catch(C){console.error(`[SessionDetail] permission ${a.kind} failed:`,C);const R=(k=G.find(O=>O.requestId===a.requestId))==null?void 0:k.toolName;_e({requestId:a.requestId,message:R?K("permission.respondFailedFor",{tool:R}):i("permission.respondFailed"),action:a})}finally{dt.current.delete(a.requestId)}}},[L,r,G]),Ns=o.useCallback(a=>void J({kind:"approve",requestId:a}),[J]),Gn=o.useCallback((a,m)=>void J({kind:"approveAlways",requestId:a,suggestions:m}),[J]);o.useCallback(async(a,m)=>{const k=De;if(it(null),!!k)try{await L.respondElicitation(k.requestId,a,m)}catch(C){console.error("Failed to submit elicitation:",C)}},[De,L]);const Yn=o.useCallback(()=>{!s||Y||(Xt(s.title||""),Et(!0),setTimeout(()=>{var a,m;(a=Mt.current)==null||a.focus(),(m=Mt.current)==null||m.select()},0))},[s,Y]),Ss=o.useCallback(async()=>{const a=Tt.trim();if(Et(!1),!(!s||!a||a===s.title))try{const m=await Hr(s.id,a);n(k=>k&&{...k,title:m.title??a})}catch(m){console.error("Rename failed:",m),alert(m instanceof Error?m.message:i("session.rename.failed"))}},[s,Tt]),Te=o.useCallback((a=null)=>{nt(a),_(!0)},[]),Vn=o.useCallback(a=>{if(typeof window<"u"&&window.matchMedia("(max-width: 639px)").matches||a.toolName==="AskUserQuestion"||a.toolName==="ExitPlanMode"){Te(a.requestId);return}const k=Array.from(document.querySelectorAll("[data-permission-request-id]")).find(C=>C.dataset.permissionRequestId===a.requestId);if(!k){Te(a.requestId);return}k.scrollIntoView({behavior:"smooth",block:"center"}),k.focus({preventScroll:!0})},[Te]),Jn=o.useCallback(a=>void J({kind:"reject",requestId:a}),[J]),Xn=o.useCallback((a,m,k)=>void J({kind:"answers",requestId:a,answers:m,questions:k}),[J]),Zn=o.useCallback((a,m,k)=>void J({kind:"plan",requestId:a,value:m,feedback:k}),[J]),er=o.useCallback(a=>{dt.current.delete(a);const m=ut.current.get(a);if(m){J(m);return}const k=we.current.find(C=>C.requestId===a);k&&(k.toolName==="AskUserQuestion"||k.toolName==="ExitPlanMode"||J({kind:k.decision==="deny"?"reject":"approve",requestId:a}))},[J]),tr=o.useCallback((a,m,k)=>{var R;if(!k)return;const C=G.find(O=>O.requestId===a);k==="allow_always"&&((R=C==null?void 0:C.suggestions)!=null&&R.length)?J({kind:"approveAlways",requestId:a,suggestions:C.suggestions}):k.startsWith("allow")?J({kind:"approve",requestId:a}):k.startsWith("reject")&&J({kind:"reject",requestId:a})},[G,J]);if(c)return e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx(jt,{onBack:t,title:e.jsx("span",{className:"text-xs font-medium text-text-muted",children:i("session.loadFailed")})}),e.jsx("div",{className:"flex flex-1 items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-status-error",children:c}),e.jsx("a",{href:"/code/",className:"mt-4 inline-block text-brand-text hover:underline",children:i("session.backToDashboard")})]})})]});if(!s)return e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx(jt,{onBack:t,title:e.jsx("span",{className:"h-3.5 w-40 animate-pulse rounded bg-surface-2"})}),e.jsx("div",{className:"flex flex-1 items-center justify-center",children:e.jsx("div",{className:"text-text-muted",children:i("session.loading")})})]});if(s.source==="acp"&&s.environment_id)return e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx("h1",{className:"sr-only",children:s.title||s.id}),e.jsx(jt,{onBack:t,title:e.jsx("span",{className:"truncate text-xs font-semibold text-text-primary",children:s.title||s.id}),meta:e.jsx("span",{className:"rounded-full bg-brand/15 px-2 py-0.5 text-[10px] font-medium text-brand-text",children:"ACP"})}),e.jsx($i,{sessionId:r,agentId:s.environment_id})]});const _s=[(Cs=s.environment)==null?void 0:Cs.machine_name,s.cwd].filter(Boolean).join(" · ")||void 0;return e.jsx(jn,{children:e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx("h1",{className:"sr-only",children:s.title||s.id}),e.jsx(jt,{onBack:t,title:Cn?e.jsx("input",{ref:Mt,value:Tt,onChange:a=>Xt(a.target.value),onKeyDown:a=>{a.key==="Enter"&&!a.nativeEvent.isComposing?(a.preventDefault(),Ss()):a.key==="Escape"&&(a.preventDefault(),Et(!1))},onBlur:()=>void Ss(),maxLength:200,className:"w-full max-w-xs rounded-md border border-brand/50 bg-surface-2 px-2 py-0.5 text-xs font-semibold text-text-primary focus:outline-none focus:ring-2 focus:ring-brand/30"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex min-w-0 items-center gap-2 text-xs font-semibold text-text-primary",children:!Y&&!H?e.jsx("button",{type:"button",onClick:Yn,title:i("session.rename.title"),className:"truncate text-left transition-colors hover:text-text-secondary",children:s.title||s.id}):e.jsx("span",{className:"truncate",children:s.title||s.id})}),s.visibility&&e.jsx(ta,{visibility:s.visibility||"private",className:"hidden flex-shrink-0 text-[10px] sm:inline-flex"})]}),meta:e.jsx(e.Fragment,{children:(()=>{var k;const a=s.source==="acp"?"acp":(k=s.environment)==null?void 0:k.worker_type,m=wn(a);return e.jsx("span",{className:`hidden items-center rounded-full px-2 py-0.5 text-[10px] font-medium sm:inline-flex ${m.colorClass}`,children:m.fullLabel})})()}),actions:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"hidden items-center gap-0.5 sm:flex",children:[e.jsxs("button",{onClick:()=>D(!Q),className:`relative flex h-7 w-7 items-center justify-center rounded-md transition-colors ${Q?"bg-brand-light text-white":"text-text-muted hover:bg-surface-2 hover:text-text-secondary"}`,title:i("artifacts.title"),children:[e.jsx(Is,{className:"h-3.5 w-3.5"}),ne>0&&!Q&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-brand px-0.5 text-[10px] font-bold text-white",children:ne>9?"9+":ne})]}),e.jsxs("button",{onClick:()=>yt(!ge),className:`relative flex h-7 w-7 items-center justify-center rounded-md transition-colors ${ge?"bg-brand-light text-white":"text-text-muted hover:bg-surface-2 hover:text-text-secondary"}`,title:i("memories.title"),children:[e.jsx(Lt,{className:"h-3.5 w-3.5"}),qe>0&&!ge&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-brand px-0.5 text-[10px] font-bold text-white",children:qe>9?"9+":qe})]}),e.jsx("button",{onClick:()=>{const a=!p;g(a),a?setTimeout(()=>{var m;return(m=x.current)==null?void 0:m.focus()},0):(w(""),h(0))},className:`flex h-7 w-7 items-center justify-center rounded-md transition-colors ${p?"bg-brand-light text-white":"text-text-muted hover:bg-surface-2 hover:text-text-secondary"}`,title:i("session.search.title"),children:e.jsx(et,{className:"h-3.5 w-3.5"})}),e.jsxs("button",{onClick:()=>{ie.length>0?Te():f(!y)},className:`relative flex h-7 w-7 items-center justify-center rounded-md transition-colors ${y||j?"bg-brand-light text-white":"text-text-muted hover:bg-surface-2 hover:text-text-secondary"}`,title:i("session.tasks"),"aria-label":i("session.tasks"),"aria-expanded":y||j,children:[e.jsx(Hs,{className:"h-3.5 w-3.5"}),ie.length>0&&!y&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-status-warning px-0.5 text-[10px] font-bold text-surface-0",children:ie.length>9?"9+":ie.length})]}),e.jsxs(Ps,{children:[e.jsx(Ds,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":i("session.actions"),title:i("session.actions"),className:"flex h-7 w-7 items-center justify-center rounded-md text-text-muted transition-colors hover:bg-surface-2 hover:text-text-secondary",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})}),e.jsxs(qs,{align:"end",className:"w-52",children:[B.side_question&&!H&&!Y&&e.jsxs(ue,{className:"gap-2",onSelect:()=>P(!q),children:[e.jsx(Kt,{className:"h-4 w-4 text-text-muted"}),i("session.sideQuestion.title")]}),B.mcp_management&&!H&&!Y&&e.jsxs(ue,{className:"gap-2",onSelect:()=>T(!E),children:[e.jsx(Bt,{className:"h-4 w-4 text-text-muted"}),i("session.mcp.title")]}),B.remote_settings&&!H&&!Y&&e.jsxs(ue,{className:"gap-2",onSelect:()=>N(!A),children:[e.jsx(Ht,{className:"h-4 w-4 text-text-muted"}),i("session.settings.title")]}),!Y&&(s==null?void 0:s.access_level)!=="write"&&e.jsxs(ue,{className:"gap-2",onSelect:()=>se(!0),children:[e.jsx(Qs,{className:"h-4 w-4 text-text-muted"}),i("session.share")]})]})]})]}),e.jsxs(Ps,{children:[e.jsx(Ds,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":i("session.actions"),title:i("session.actions"),className:"relative flex h-11 w-11 items-center justify-center rounded-md text-text-muted transition-colors hover:bg-surface-2 hover:text-text-secondary sm:hidden",children:[e.jsx(Ls,{className:"h-5 w-5"}),ie.length>0&&e.jsx("span",{className:"absolute right-1 top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-status-warning px-0.5 text-[10px] font-bold text-surface-0",children:ie.length>9?"9+":ie.length})]})}),e.jsxs(qs,{align:"end",className:"w-56",children:[e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>D(!Q),children:[e.jsx(Is,{className:"h-4 w-4 text-text-muted"}),e.jsx("span",{className:"flex-1",children:i("artifacts.title")}),ne>0&&e.jsx("span",{className:"font-mono text-[10px] text-brand-text",children:ne>9?"9+":ne})]}),e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>yt(!ge),children:[e.jsx(Lt,{className:"h-4 w-4 text-text-muted"}),e.jsx("span",{className:"flex-1",children:i("memories.title")}),qe>0&&e.jsx("span",{className:"font-mono text-[10px] text-brand-text",children:qe>9?"9+":qe})]}),B.side_question&&!H&&!Y&&e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>P(!q),children:[e.jsx(Kt,{className:"h-4 w-4 text-text-muted"}),i("session.sideQuestion.title")]}),e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>{const a=!p;g(a),a?setTimeout(()=>{var m;return(m=x.current)==null?void 0:m.focus()},0):(w(""),h(0))},children:[e.jsx(et,{className:"h-4 w-4 text-text-muted"}),i("session.search.title")]}),B.mcp_management&&!H&&!Y&&e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>T(!E),children:[e.jsx(Bt,{className:"h-4 w-4 text-text-muted"}),i("session.mcp.title")]}),B.remote_settings&&!H&&!Y&&e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>N(!A),children:[e.jsx(Ht,{className:"h-4 w-4 text-text-muted"}),i("session.settings.title")]}),!Y&&(s==null?void 0:s.access_level)!=="write"&&e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>se(!0),children:[e.jsx(Qs,{className:"h-4 w-4 text-text-muted"}),i("session.share")]}),e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>{ie.length>0?Te():f(!y)},children:[e.jsx(Hs,{className:"h-4 w-4 text-text-muted"}),e.jsx("span",{className:"flex-1",children:i("session.tasks")}),ie.length>0&&e.jsx("span",{className:"rounded-full bg-status-warning px-1.5 py-0.5 font-mono text-[10px] font-bold text-surface-0",children:ie.length>9?"9+":ie.length})]})]})]})]})}),(Je==="reconnecting"||Je==="failed")&&e.jsxs("div",{className:`flex items-center justify-center gap-2 px-4 py-1.5 text-xs font-medium ${Je==="failed"?"bg-status-error/10 text-status-error":"bg-status-warning/10 text-status-warning"}`,children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${Je==="failed"?"bg-status-error":"animate-pulse bg-status-warning"}`}),Je==="failed"?i("session.sseFailed"):i("session.sseReconnecting")]}),Q&&e.jsx("div",{className:"border-b bg-surface-1 py-4",children:e.jsx("div",{className:"mx-auto page-measure px-4 sm:px-8",children:e.jsx(oa,{sessionId:r,embedded:!0,refreshTick:ce})})}),p&&e.jsx("div",{className:"border-b bg-surface-1 py-2",children:e.jsxs("div",{className:"mx-auto flex page-measure px-4 sm:px-8 items-center gap-2",children:[e.jsx(et,{className:"h-3.5 w-3.5 flex-shrink-0 text-text-muted"}),e.jsx("input",{ref:x,value:v,onChange:a=>{w(a.target.value),h(0)},onKeyDown:a=>{a.key==="Enter"&&!a.nativeEvent.isComposing?(a.preventDefault(),Qn(v&&a.shiftKey?S-1:S+1)):a.key==="Escape"&&(a.preventDefault(),g(!1),w(""))},placeholder:i("session.search.placeholder"),className:"w-full bg-transparent text-sm text-text-primary placeholder:text-text-muted focus:outline-none"}),v.trim()&&e.jsx("span",{className:"flex-shrink-0 font-mono text-[10px] text-text-muted",children:Ye.orderedMatchIds.length===0?i("session.search.noResults"):`${S+1}/${Ye.orderedMatchIds.length}`})]})}),e.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:e.jsx(Qr,{entries:be,isLoading:z,turnStartedAt:b,emptyTitle:i("session.emptyTitle"),emptyDescription:i("session.emptyDescription"),emptyExtra:e.jsx(Si,{}),searchMatchIds:v.trim()?Ye.matchIds:void 0,onPermissionRespond:tr,onRewindEntry:B.rewind&&!H&&!Y&&!z?(a,m)=>Hn(a,m):void 0})}),ft!==null&&e.jsx(ke,{open:ge,onOpenChange:yt,children:e.jsxs(Ne,{showCloseButton:!1,"data-testid":"memory-sidebar",className:"mem-drawer mem-drawer--v1 translate-x-0 translate-y-0",children:[e.jsxs("div",{className:"mem-drawer__masthead",children:[e.jsx(Se,{className:"mem-drawer__title",children:i("memorySidebar.title")}),e.jsx("button",{type:"button",onClick:()=>yt(!1),className:"mem-drawer__close","aria-label":i("common.close"),title:i("common.close"),children:e.jsx(Ze,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"mem-drawer__body",children:e.jsx(bi,{refreshTick:qn,recall:ft==="memdir"?$n:void 0,dreaming:ft==="memdir"?z&&Dt:void 0,onDreamTrigger:ft==="memdir"?Bn:void 0})})]})}),ts&&e.jsx("div",{className:"mx-auto page-measure w-full px-4 sm:px-8 pb-1",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-status-error/40 bg-status-error/10 px-3 py-1.5 text-xs text-status-error",children:[e.jsx($t,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1",children:ts})]})}),Zt&&e.jsx("div",{className:"mx-auto page-measure w-full px-4 sm:px-8 pb-1",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-status-error/40 bg-status-error/10 px-3 py-1.5 text-xs text-status-error",children:[e.jsx($t,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1",children:Zt})]})}),e.jsxs("div",{className:"page-measure mx-auto w-full px-4 sm:px-8 pb-1 session-controls",children:[e.jsxs("div",{className:"session-controls__cluster",children:[e.jsx(qi,{mode:ct,onModeChange:Rt,disabled:H||Y}),e.jsx(Di,{models:(V==null?void 0:V.availableModels)??[],currentModelId:(V==null?void 0:V.currentModelId)??null,onSelect:a=>{le(r,{type:"control_request",request:{subtype:"set_model",model:a}}),Ce(m=>m&&{...m,currentModelId:a})},showThinking:B.set_max_thinking_tokens,thinkingBudget:he,onThinkingChange:Pn,showEffort:B.set_effort,effort:xs,onEffortChange:a=>ps.set(a),disabled:H||Y}),B.set_token_mode&&e.jsx(Ai,{mode:ds,onModeChange:a=>pt.set(a),disabled:H||Y})]}),e.jsx("div",{className:"session-controls__usage",children:js&&e.jsx(Pi,{usage:js})})]}),H&&(s==null?void 0:s.environment_id)&&e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-2 sm:px-8",children:e.jsx("button",{type:"button",onClick:()=>void Un(),className:"w-full rounded-lg border border-border bg-surface-1 px-4 py-2.5 text-sm text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary",children:i("session.resumeInNew")})}),e.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:rs>0?i("permission.queueEmpty"):""},rs),de&&e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-1 sm:px-8",children:e.jsxs("div",{role:"status","aria-live":"polite",className:`flex items-center gap-2 rounded-lg border bg-surface-1 px-3 py-2 text-xs font-medium ${de.decision==="allow"?"border-approve/25 text-approve-text":"border-status-error/30 text-status-error"}`,children:[de.decision==="allow"?e.jsx(Wr,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):e.jsx(Ze,{className:"h-4 w-4 flex-shrink-0 text-status-error","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 truncate",children:de.decision==="allow"?de.remembered?K("permission.appliedRemembered",{tool:de.tool,rule:de.remembered}):K("permission.applied",{tool:de.tool}):de.decision==="deny"?K("permission.appliedDenied",{tool:de.tool}):K("permission.appliedCanceled",{tool:de.tool})})]},de.nonce)}),re&&!j&&e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-1 sm:px-8",children:e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-status-error/40 bg-status-error/10 px-3 py-2",children:[e.jsx($t,{className:"h-4 w-4 flex-shrink-0 text-status-error","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1 text-xs text-status-error",children:re.message}),e.jsx("button",{ref:os,type:"button",onClick:()=>void J(re.action),className:"min-h-11 rounded-md border border-status-error/40 px-3 py-1.5 text-xs font-medium text-status-error transition-colors hover:bg-status-error/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:min-h-9",children:i("common.retry")}),e.jsx("button",{type:"button",onClick:()=>_e(null),"aria-label":i("common.close"),className:"flex h-11 w-11 items-center justify-center rounded-md text-text-muted transition-colors hover:bg-surface-2 hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:h-8 sm:w-8",children:e.jsx(Ze,{className:"h-4 w-4"})})]})}),e.jsx("div",{className:j?"invisible":void 0,"aria-hidden":j||void 0,children:e.jsx(ui,{requests:G,onApprove:Ns,onView:Vn,onOpenQueue:()=>Te(),context:_s})}),e.jsx(zr,{onSubmit:Kn,isLoading:z,onInterrupt:ks,onCycleMode:Wn,disabled:H||Y,placeholder:H?i("session.closed"):Y?i("session.readOnly"):i("session.inputPlaceholder"),supportsAttachments:!0,commands:It,queueWhileLoading:!0,queuedCount:ot.length,onDequeue:a=>lt(m=>m.filter((k,C)=>C!==a)),onSearchFiles:B.file_search?a=>L.searchFiles(a):void 0,historyKey:r,draftOverride:M}),E&&e.jsx(ri,{onClose:()=>T(!1),fetchServers:()=>L.getMcpServers(),onToggle:(a,m)=>L.toggleMcpServer(a,m),onReconnect:a=>L.reconnectMcpServer(a)}),A&&e.jsx(oi,{onClose:()=>N(!1),fetchSettings:()=>L.getRemoteSettings(),onApply:a=>L.applyFlagSettings(a)}),q&&e.jsx(li,{onClose:()=>P(!1),onAsk:a=>L.askSideQuestion(a)}),y&&s&&e.jsx(Xa,{onClose:()=>f(!1),session:s,liveStatus:l,pendingPermissions:G,onOpenQueue:()=>Te(),subagentState:rt,onStopTask:An,onInterrupt:ks,onDelete:zn,onEndSession:B.end_session&&!H&&!Y?async()=>{await L.endSession("ended from web"),await As(s.id),window.location.href="/code/"}:void 0}),e.jsx(pi,{open:X,onClose:()=>se(!1),sessionId:s.id,sessionTitle:s.title||void 0}),e.jsx(mi,{open:j,onClose:()=>_(!1),requests:G,initialRequestId:Le,now:Ke,errorMessage:re==null?void 0:re.message,errorRequestId:re==null?void 0:re.requestId,onRetry:er,context:_s,onApprove:Ns,onApproveAlways:Gn,onReject:Jn,onSubmitAnswers:Xn,onSubmitPlan:Zn}),e.jsx(yi,{open:I,onClose:()=>$(!1),adapter:L,onResume:a=>{$(!1),Xe(a,null)}})]})})}function $i({sessionId:r,agentId:t}){const[s,n]=o.useState(null),[l,d]=o.useState("disconnected"),[c,u]=o.useState(null),y=o.useRef(null);return o.useEffect(()=>{const f=Ci(t);return f.setConnectionStateHandler((j,_)=>{d(j),u(_||null)}),y.current=f,n(f),f.connect().catch(j=>{j instanceof Gr||(u(j.message),d("error"))}),()=>{f.disconnect(),y.current=null,n(null),d("disconnected")}},[t]),e.jsx(jn,{children:e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[c&&l==="error"&&e.jsx("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-sm border-b",children:c}),l==="connecting"&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-brand border-t-transparent rounded-full mx-auto mb-3"}),e.jsx("p",{className:"text-text-muted text-sm",children:i("session.connectingAgent")})]})}),l==="error"&&!s&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium mb-1",children:i("session.connectionFailed")}),e.jsx("p",{className:"text-text-muted text-sm",children:c})]})}),s&&l==="connected"&&e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(Yr,{client:s,agentId:t})})]})})}export{Xi as SessionDetail};
75
+ ${E}`})}}const y=u.length===1&&u[0].type==="text"?u[0].text||t:u.length>0?u:t;try{const j=Me();this.postedUserUuids.add(j);const _=await lr(this.sessionId,{type:"user",uuid:j,content:t,message:{content:y}}),E=(f=_==null?void 0:_.event)==null?void 0:f.id;E&&this.setEntries(T=>T.map(A=>A.type==="user_message"&&A.id===c.id?{...A,id:E}:A))}catch(j){throw this.setEntries(_=>_.filter(E=>!(E.type==="user_message"&&E.id===c.id))),j}}async respondPermission(t,s,n){this.pendingPermissionDecisions.set(t,s);const l=Date.now();this.markPermissionSent(t,s?"allow":"deny",l);try{await le(this.sessionId,{type:"permission_response",approved:s,request_id:t,...n})}catch(d){throw this.pendingPermissionDecisions.delete(t),this.markPermissionSent(t,void 0,void 0),d}}markPermissionSent(t,s,n){this.setEntries(l=>l.map(d=>{if(d.type!=="tool_call")return d;const c=d.toolCall.permissionRequest;if((c==null?void 0:c.requestId)!==t)return d;const u={...c};return s?u.decision=s:delete u.decision,n!==void 0?u.sentAt=n:delete u.sentAt,{type:"tool_call",toolCall:{...d.toolCall,permissionRequest:u}}}))}isPermissionSettled(t){return this.settledPermissionIds.has(t)}rememberSettledPermission(t){if(this.settledPermissionIds.add(t),this.settledPermissionIds.size<=200)return;const s=this.settledPermissionIds.values().next().value;s!==void 0&&this.settledPermissionIds.delete(s)}settlePermission(t,s){if(!t||this.settledPermissionIds.has(t))return null;const n=this.pendingPermissionDecisions.get(t);let l;s==="allow"||s==="deny"?l=s:n!==void 0?l=n?"allow":"deny":s==="cancel"?l="cancel":l="allow",this.rememberSettledPermission(t);const d=this.pendingPermissionToolIds.get(t);this.pendingPermissionToolIds.delete(t),this.pendingPermissionDecisions.delete(t),d&&l!=="allow"&&this.pendingToolCallIds.delete(d);const c=l==="allow"?"running":l==="deny"?"rejected":"canceled";return this.setEntries(u=>u.map(y=>{var f;return y.type!=="tool_call"||((f=y.toolCall.permissionRequest)==null?void 0:f.requestId)!==t?y:{type:"tool_call",toolCall:{...y.toolCall,status:c,permissionRequest:void 0}}})),l}async interrupt(){this.finalizePendingToolCalls("canceled"),await cr(this.sessionId)}async setPermissionMode(t){const s=Me();return await le(this.sessionId,{type:"control_request",request_id:s,request:{subtype:"set_permission_mode",mode:t}}),s}async controlRoundTrip(t,s=8e3){const n=Me(),l=new Promise(c=>{this.pendingControlRequests.set(n,c)}),d=setTimeout(()=>{const c=this.pendingControlRequests.get(n);c&&(this.pendingControlRequests.delete(n),c({data:null,error:"timeout"}))},s);try{return await le(this.sessionId,{type:"control_request",request_id:n,request:t}),await l}catch(c){throw this.pendingControlRequests.delete(n),c}finally{clearTimeout(d)}}async searchFiles(t,s=20){const n=await this.controlRoundTrip({subtype:"file_search",query:t,limit:s});try{if(!n.data||!Array.isArray(n.data.suggestions))return[];const l=[];for(const d of n.data.suggestions)d&&typeof d=="object"&&typeof d.path=="string"&&l.push(d.path);return l}catch{return[]}}async respondElicitation(t,s,n){await le(this.sessionId,{type:"permission_response",approved:s==="accept",request_id:t,response:{subtype:"success",request_id:t,response:{action:s,...n?{content:n}:{}}}})}async askSideQuestion(t){const s=await this.controlRoundTrip({subtype:"side_question",question:t},12e4);if(s.error||!s.data)return null;const n=s.data.response;return typeof n=="string"?n:null}async listResumableSessions(){const t=await this.controlRoundTrip({subtype:"list_sessions"});if(!t.data||!Array.isArray(t.data.sessions))throw new Error(t.error??"list_sessions failed");const s=[];for(const n of t.data.sessions){if(!n||typeof n!="object")continue;const l=n;typeof l.session_id!="string"||!l.session_id||s.push({sessionId:l.session_id,title:typeof l.title=="string"&&l.title?l.title:l.session_id.slice(0,8),modified:typeof l.modified=="number"?l.modified:0,...typeof l.created_at=="number"?{createdAt:l.created_at}:{},...typeof l.git_branch=="string"&&l.git_branch?{gitBranch:l.git_branch}:{}})}return s}async resumeSession(t){const s=await this.controlRoundTrip({subtype:"resume_session",session_id:t},3e4);if(!s.data)throw new Error(s.error??"resume_session failed");return{title:typeof s.data.title=="string"?s.data.title:null,messageCount:typeof s.data.message_count=="number"?s.data.message_count:0}}async setEffort(t){const s=Me();return await le(this.sessionId,{type:"control_request",request_id:s,request:{subtype:"set_effort",...t?{effort:t}:{effort:null}}}),s}async setTokenMode(t){const s=Me();return await le(this.sessionId,{type:"control_request",request_id:s,request:{subtype:"set_token_mode",mode:t}}),s}async setThinkingBudget(t){const s=Me();return await le(this.sessionId,{type:"control_request",request_id:s,request:{subtype:"set_max_thinking_tokens",max_thinking_tokens:t}}),s}async getContextUsage(){const t=await this.controlRoundTrip({subtype:"get_context_usage"});try{if(!t.data)return null;const s=t.data.totalTokens,n=t.data.rawMaxTokens,l=t.data.percentage;if(typeof s!="number"||typeof n!="number")return null;const d=t.data.categories,c=Array.isArray(d)?d.filter(u=>!!u&&typeof u=="object"&&typeof u.name=="string").map(u=>({name:u.name,tokens:typeof u.tokens=="number"?u.tokens:0,...u.isDeferred===!0?{isDeferred:!0}:{}})):void 0;return{totalTokens:s,rawMaxTokens:n,percentage:typeof l=="number"?l:0,...typeof t.data.model=="string"&&t.data.model?{model:t.data.model}:{},...c&&c.length>0?{categories:c}:{}}}catch{return null}}async stopSubagent(t){const s=await this.controlRoundTrip({subtype:"stop_task",task_id:t});try{return s.error?{ok:!1,error:s.error==="timeout"?i("adapter.stopTimeout"):s.error}:{ok:!0}}catch{return{ok:!1,error:i("adapter.stopFailed")}}}async getMcpServers(){var l;const s=(l=(await this.controlRoundTrip({subtype:"mcp_status"})).data)==null?void 0:l.mcpServers;if(!Array.isArray(s))return[];const n=[];for(const d of s){if(!d||typeof d!="object")continue;const c=d;if(typeof c.name!="string"||!c.name)continue;const u=c.status;if(u!=="connected"&&u!=="failed"&&u!=="needs-auth"&&u!=="pending"&&u!=="disabled")continue;const y=c.serverInfo,f=c.config;n.push({name:c.name,status:u,...y&&typeof y.name=="string"&&typeof y.version=="string"?{serverInfo:{name:y.name,version:y.version}}:{},...typeof c.error=="string"&&c.error?{error:c.error}:{},...typeof(f==null?void 0:f.url)=="string"&&f.url?{url:f.url}:{},...Array.isArray(c.tools)?{toolCount:c.tools.length}:{}})}return n}async toggleMcpServer(t,s){const n=await this.controlRoundTrip({subtype:"mcp_toggle",serverName:t,enabled:s},15e3);return n.error?{ok:!1,error:n.error==="timeout"?i("adapter.requestTimeout"):n.error}:{ok:!0}}async reconnectMcpServer(t){const s=await this.controlRoundTrip({subtype:"mcp_reconnect",serverName:t},2e4);return s.error?{ok:!1,error:s.error==="timeout"?i("adapter.requestTimeout"):s.error}:{ok:!0}}async getRemoteSettings(){const s=(await this.controlRoundTrip({subtype:"get_settings"})).data;if(!s)return null;const n=s.applied,l=s.effective&&typeof s.effective=="object"&&!Array.isArray(s.effective)?s.effective:{},d=s.sources,c=[];if(Array.isArray(d))for(const u of d){if(!u||typeof u!="object")continue;const y=u;typeof y.source=="string"&&c.push({source:y.source,settings:y.settings&&typeof y.settings=="object"&&!Array.isArray(y.settings)?y.settings:{}})}return{applied:{model:typeof(n==null?void 0:n.model)=="string"?n.model:null,effort:typeof(n==null?void 0:n.effort)=="string"?n.effort:null,tokenMode:typeof(n==null?void 0:n.tokenMode)=="string"?n.tokenMode:null},effective:l,sources:c}}async applyFlagSettings(t){const s=await this.controlRoundTrip({subtype:"apply_flag_settings",settings:t},15e3);return s.error?{ok:!1,error:s.error==="timeout"?i("adapter.requestTimeout"):s.error}:{ok:!0}}async rewindToMessage(t){await dr(this.sessionId,t)}async endSession(t){await le(this.sessionId,{type:"control_request",request_id:Me(),request:{subtype:"end_session",...t?{reason:t}:{}}})}}function Ha(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}function jt({onBack:r,title:t,meta:s,actions:n}){return me(),e.jsx("div",{className:"flex-shrink-0 border-b border-nav-rule bg-surface-1/80 backdrop-blur-md",children:e.jsxs("div",{className:"mx-auto flex h-16 w-full page-measure items-center gap-2 px-4 sm:h-12 sm:px-8",children:[e.jsx("button",{type:"button",onClick:r,"aria-label":i("nav.dashboard"),title:i("nav.dashboard"),className:"-mx-2 flex min-h-11 flex-shrink-0 items-center rounded-md px-2 py-1 text-xs text-text-muted transition hover:-translate-x-0.5 hover:bg-surface-2 hover:text-text-primary sm:min-h-0",children:i("nav.dashboard")}),e.jsx("span",{className:"mx-1 h-4 w-px flex-shrink-0 bg-border","aria-hidden":"true"}),e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[t,s&&e.jsx("div",{className:"flex flex-shrink-0 items-center gap-2",children:s})]}),n&&e.jsx("div",{className:"flex flex-shrink-0 items-center gap-1 sm:gap-0.5",children:n}),e.jsx("span",{className:"mx-0.5 h-4 w-px flex-shrink-0 bg-border","aria-hidden":"true"}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-0.5",children:[e.jsx(mr,{className:"h-11 w-11 sm:h-7 sm:w-7"}),e.jsx(xr,{compact:!0,onSettingsClick:()=>{window.history.pushState(null,"","/settings"),window.dispatchEvent(new PopStateEvent("popstate"))}})]})]})})}function Qa(r){if(r<1e3)return"0s";const t=Math.floor(r/1e3);if(t<60)return`${t}s`;const s=Math.floor(t/60),n=t%60;if(s<60)return n?`${s}m${n}s`:`${s}m`;const l=Math.floor(s/60),d=s%60;return d?`${l}h${d}m`:`${l}h`}function Wa(r){return r===void 0||r<=0?"":r<1e3?`${r}`:r<1e6?`${(r/1e3).toFixed(r<1e4?1:0)}k`:`${(r/1e6).toFixed(1)}M`}function Ga({status:r}){return r==="running"?e.jsx(st,{className:"h-3 w-3 animate-spin text-brand-text"}):r==="completed"?e.jsx(Ia,{className:"h-3 w-3 text-status-success"}):r==="failed"||r==="stopped"?e.jsx(pr,{className:"h-3 w-3 text-status-error"}):null}function za({task:r,onStopTask:t,fullText:s}){const n=r.status==="running",l=n?r.durationMs??Date.now()-r.startTime:(r.endTime??Date.now())-r.startTime,d=Wa(r.tokenCount),c=r.toolUseCount!==void 0&&r.toolUseCount>0?`${r.toolUseCount} tool${r.toolUseCount>1?"s":""}`:"",u=r.summary||r.description||"(no description)";return e.jsxs("div",{className:"group/task flex items-start gap-2 rounded-md bg-surface-2 px-2.5 py-1.5 text-xs",children:[e.jsx("div",{className:"mt-0.5 flex-shrink-0",children:e.jsx(Ga,{status:r.status})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"truncate font-medium text-text-primary",children:r.name}),e.jsx("span",{className:"flex-shrink-0 font-mono text-text-muted",children:Qa(l)})]}),e.jsx("div",{className:`mt-0.5 text-text-secondary ${s?"line-clamp-2 break-words":"truncate"}`,children:u}),(d||c||r.lastToolName)&&e.jsxs("div",{className:"mt-0.5 flex items-center gap-x-2 overflow-hidden whitespace-nowrap font-mono text-[10px] text-text-muted",children:[d&&e.jsxs("span",{className:"flex-shrink-0",children:["↕ ",d," tok"]}),c&&e.jsxs("span",{className:"flex-shrink-0",children:["· ",c]}),r.lastToolName&&e.jsxs("span",{className:"min-w-0 truncate",children:["· last: ",r.lastToolName]})]}),!n&&r.finalSummary&&e.jsx("div",{className:"mt-1 line-clamp-2 rounded bg-status-success/10 px-1.5 py-0.5 text-[10px] text-status-success",children:r.finalSummary})]}),n&&t&&e.jsx("button",{type:"button",onClick:()=>t(r.taskId),title:i("subagent.stop"),className:"mt-0.5 flex-shrink-0 rounded p-0.5 text-text-muted opacity-0 transition-opacity hover:bg-status-error/10 hover:text-status-error focus:opacity-100 group-hover/task:opacity-100",children:e.jsx(Ze,{className:"h-3.5 w-3.5"})})]})}function Ya(r){if(!r)return"never";const t=Math.max(0,Date.now()-r);return t<5e3?"just now":t<6e4?`${Math.floor(t/1e3)}s ago`:t<36e5?`${Math.floor(t/6e4)}m ago`:`${Math.floor(t/36e5)}h ago`}function Va(r){return r?Date.now()-r<6e4:!1}function Ja({onClose:r,session:t,liveStatus:s,pendingPermissions:n,onInterrupt:l,onDelete:d,onOpenQueue:c,subagentState:u,onStopTask:y,onEndSession:f}){const[j,_]=o.useState(!1),E=async()=>{await navigator.clipboard.writeText(t.id),_(!0),setTimeout(()=>_(!1),1500)},[T,A]=o.useState(!1),N=async()=>{if(!(!f||T)&&window.confirm(i("task.endConfirm"))){A(!0);try{await f(),r()}catch{A(!1)}}},q=n.length,P=t.worker,I=t.work_item,$=t.environment;return e.jsx(ke,{open:!0,onOpenChange:p=>{p||r()},children:e.jsxs(Ne,{showCloseButton:!1,className:"fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-96 h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-md overflow-y-auto",children:[e.jsx(Re,{children:e.jsx(Se,{className:"font-display font-semibold text-text-primary",children:"Session Ops"})}),e.jsxs("div",{className:"mt-3 space-y-5 text-sm",children:[e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Status"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hr,{status:s||t.status||"unknown"}),e.jsx("span",{className:"text-xs text-text-muted",children:P&&(Va(P.last_heartbeat_at)?"· worker online":"· worker offline")})]}),e.jsxs("dl",{className:"space-y-1 text-xs text-text-muted",children:[P&&e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("dt",{className:"flex items-center gap-1",children:[e.jsx(Ms,{className:"h-3 w-3"}),"Heartbeat"]}),e.jsx("dd",{className:"font-mono text-text-secondary",children:Ya(P.last_heartbeat_at)})]}),(t.environment_id||$)&&e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("dt",{className:"flex items-center gap-1",children:[e.jsx(vn,{className:"h-3 w-3"}),"Machine"]}),e.jsx("dd",{className:"truncate text-text-secondary",children:($==null?void 0:$.machine_name)||t.environment_id||($==null?void 0:$.id)})]}),(t.cwd||(I==null?void 0:I.cwd))&&e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsxs("dt",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(ea,{className:"h-3 w-3"}),"Directory"]}),e.jsx("dd",{className:"min-w-0 truncate font-mono text-text-secondary",title:t.cwd||(I==null?void 0:I.cwd)||void 0,children:t.cwd||(I==null?void 0:I.cwd)})]}),t.created_at&&e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("dt",{className:"flex items-center gap-1",children:[e.jsx(Ms,{className:"h-3 w-3"}),"Created"]}),e.jsx("dd",{className:"font-mono text-text-secondary",children:fr(t.created_at)})]})]})]}),e.jsx(ei,{state:u,onStopTask:y}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(fn,{className:"h-3.5 w-3.5"}),i("task.pendingActions")]}),q>0?e.jsxs("button",{type:"button",onClick:c,disabled:!c,className:"permit-mini",title:c?i("permission.reviewShort"):void 0,"aria-label":K("permission.pendingAria",{n:q}),children:[e.jsx("span",{className:"permit-mini__count",children:q}),e.jsxs("span",{className:"permit-mini__body",children:[e.jsx("span",{className:"permit-mini__lead",children:i("task.pendingLead")}),e.jsxs("span",{className:"permit-mini__meta",children:[n.slice(0,2).map(p=>p.toolName).join(" · "),q>2?` +${q-2}`:""]})]}),c&&e.jsxs("span",{className:"permit-mini__action",children:[i("permission.reviewShort")," →"]})]}):e.jsx("p",{className:"text-xs text-text-muted",children:i("task.noPendingActions")})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(qa,{className:"h-3.5 w-3.5"}),"Quick Actions"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:l,className:"flex-1 rounded-md border border-border px-3 py-1.5 text-xs text-text-secondary hover:bg-surface-2 transition-colors",children:"Interrupt"}),f&&e.jsx("button",{onClick:N,disabled:T,className:"flex-1 rounded-md border border-status-error/30 px-3 py-1.5 text-xs text-status-error hover:bg-status-error/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:i("task.endHint"),children:T?"Ending…":"End session"}),e.jsxs("button",{onClick:d,className:"flex-1 rounded-md border border-status-error/30 px-3 py-1.5 text-xs text-status-error hover:bg-status-error/10 transition-colors",children:[e.jsx(yr,{className:"mr-1 inline h-3 w-3"}),"Delete"]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(_a,{className:"h-3.5 w-3.5"}),"Session Info"]}),e.jsxs("dl",{className:"space-y-1 text-xs text-text-muted",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("dt",{children:"Session ID"}),e.jsxs("dd",{className:"flex items-center gap-1 min-w-0",children:[e.jsx("code",{className:"break-all font-mono text-text-secondary text-right",children:t.id}),e.jsx("button",{onClick:E,className:"text-text-muted hover:text-text-primary transition-colors flex-shrink-0",title:"Copy session id",children:j?"✓":"⧉"})]})]}),I&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{children:"Spawn mode"}),e.jsx("dd",{className:"font-mono text-text-secondary",children:I.spawn_mode??"default"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{children:"Work state"}),e.jsx("dd",{className:"font-mono text-text-secondary",children:I.state})]})]}),t.source&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{children:"Source"}),e.jsx("dd",{className:"font-mono text-text-secondary",children:t.source})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("dt",{children:"Worker"}),e.jsx("dd",{className:"font-mono text-text-secondary",children:wn(t.source==="acp"?"acp":$==null?void 0:$.worker_type).fullLabel})]})]})]})]})]})})}const Xa={in_process_teammate:"task.type.teammates",local_bash:"task.type.shells",monitor_mcp:"task.type.monitors",remote_agent:"task.type.remoteAgents",local_agent:"task.type.localAgents"},Za=new Set(["dream"]);function ei({state:r,onStopTask:t}){const s=Object.values(r.tasks).some(y=>y.status==="running"),n=Object.values(r.tasks).some(y=>y.status!=="running"&&y.evictAfter!==void 0),[,l]=o.useState(0);o.useEffect(()=>{if(!s&&!n)return;const y=setInterval(()=>{l(f=>f+1)},1e3);return()=>clearInterval(y)},[s,n]);const d=Oa(r),c=d.filter(y=>y.status==="running").length,u=d.length-c;return e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-text-muted",children:[e.jsx(Ea,{className:"h-3.5 w-3.5"}),i("task.backgroundTasks")]}),d.length>0&&e.jsx("span",{className:"font-mono text-[10px] text-text-muted",children:c>0&&u>0?K("task.mixedCount",{running:c,recent:u}):c>0?K("task.runningCount",{count:c}):K("task.recentCount",{count:d.length})})]}),d.length===0?e.jsx("p",{className:"text-xs text-text-muted",children:i("task.noBackgroundTasks")}):e.jsx("div",{className:"max-h-[38vh] space-y-2 overflow-y-auto overscroll-contain pr-1",children:Ua(d).map(y=>{const f=!Za.has(y.taskType),j=Xa[y.taskType]??"task.type.tasks";return e.jsxs("div",{className:"space-y-1",children:[f&&e.jsxs("div",{className:"pl-1 text-[10px] font-medium uppercase tracking-wide text-text-muted/80",children:[i(j)," (",y.tasks.length,")"]}),y.tasks.map(_=>e.jsx(za,{task:_,onStopTask:t,fullText:!0},_.taskId))]},y.taskType)})})]})}const ti={connected:"bg-status-success/15 text-status-success",failed:"bg-status-error/15 text-status-error","needs-auth":"bg-status-warning/15 text-status-warning",pending:"bg-status-active/15 text-status-active",disabled:"bg-surface-3 text-text-muted"},si={connected:"mcp.status.connected",failed:"mcp.status.failed","needs-auth":"mcp.status.needsAuth",pending:"mcp.status.pending",disabled:"mcp.status.disabled"};function ni({onClose:r,fetchServers:t,onToggle:s,onReconnect:n}){me();const[l,d]=o.useState(null),[c,u]=o.useState(null),[y,f]=o.useState(null),[j,_]=o.useState(null),E=o.useCallback(async()=>{f(null),_(null);try{const N=await t();d(N),u(null)}catch(N){St("[McpPanel] fetch failed",N),u(i("mcp.loadFailed"))}},[t]);o.useEffect(()=>{E()},[E]);const T=async N=>{const q=N.status==="disabled";f(`toggle:${N.name}`),_(null);try{const P=await s(N.name,q);P.ok||_(P.error||i("mcp.toggleFailed"))}finally{await E()}},A=async N=>{f(`reconnect:${N.name}`),_(null);try{const q=await n(N.name);q.ok||_(q.error||i("mcp.reconnectFailed"))}finally{await E()}};return e.jsx(ke,{open:!0,onOpenChange:N=>{N||r()},children:e.jsxs(Ne,{showCloseButton:!1,className:"fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-96 h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-md overflow-y-auto",children:[e.jsx(Re,{children:e.jsxs(Se,{className:"flex items-center gap-2 font-display font-semibold text-text-primary",children:[e.jsx(Bt,{className:"h-4 w-4"}),i("session.mcp.title")]})}),e.jsxs("div",{className:"mt-3 space-y-3 text-sm",children:[j&&e.jsx("div",{className:"rounded-md bg-status-error/10 px-3 py-2 text-xs text-status-error",children:j}),l===null&&!c&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[e.jsx(st,{className:"h-3.5 w-3.5 animate-spin"}),i("mcp.loading")]}),c&&e.jsx("p",{className:"text-xs text-status-error",children:c}),l!==null&&l.length===0&&e.jsx("p",{className:"text-xs text-text-muted",children:i("mcp.empty")}),l==null?void 0:l.map(N=>{const q=y===`toggle:${N.name}`,P=y===`reconnect:${N.name}`,I=N.status==="disabled";return e.jsx("div",{className:"rounded-lg border border-border bg-surface-2 px-3 py-2.5",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium text-text-primary",children:N.name}),e.jsx("span",{className:`flex-shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium ${ti[N.status]}`,children:i(si[N.status])})]}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-text-muted",children:[N.serverInfo?`${N.serverInfo.name} v${N.serverInfo.version}`:N.url||"stdio",N.toolCount!==void 0&&` · ${K("mcp.toolCount",{n:N.toolCount})}`]}),N.error&&e.jsx("div",{className:"mt-1 truncate text-xs text-status-error",title:N.error,children:N.error})]}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1",children:[e.jsx("button",{type:"button",onClick:()=>void A(N),disabled:P||I,className:"rounded-md p-1.5 text-text-muted hover:bg-surface-3 hover:text-text-primary transition-colors disabled:opacity-40 disabled:cursor-not-allowed",title:i("mcp.reconnect"),children:e.jsx(na,{className:`h-3.5 w-3.5 ${P?"animate-spin":""}`})}),e.jsx("button",{type:"button",role:"switch","aria-checked":!I,onClick:()=>void T(N),disabled:q,className:`relative h-5 w-9 rounded-full transition-colors disabled:opacity-50 ${I?"bg-surface-3":"bg-brand"}`,title:I?i("mcp.enable"):i("mcp.disable"),children:e.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${I?"left-0.5":"left-4.5"}`})})]})]})},N.name)})]})]})})}const kn=[{key:"autoMemoryEnabled",labelKey:"settings.autoMemory",defaultValue:!0},{key:"teamMemoryEnabled",labelKey:"settings.teamMemory",defaultValue:!1}],ri=new Set(kn.map(r=>r.key));function ai(r){if(r==null)return i("settings.unset");if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}}function nn(r){if(r==null)return i("settings.unset");if(typeof r=="object")try{return JSON.stringify(r,null,2)}catch{return String(r)}return String(r)}function ii({onClose:r,fetchSettings:t,onApply:s}){me();const[n,l]=o.useState(null),[d,c]=o.useState(null),[u,y]=o.useState(""),[f,j]=o.useState(null),[_,E]=o.useState(null),[T,A]=o.useState(null),[N,q]=o.useState(!1),P=o.useCallback(async()=>{j(null),E(null),A(null),q(!1);try{const x=await t();l(x),c(x?null:i("settings.loadFailed"))}catch(x){St("[SettingsDrawer] fetch failed",x),c(i("settings.loadFailed"))}},[t]);o.useEffect(()=>{P()},[P]);const I=o.useMemo(()=>n?Object.entries(n.effective).filter(([,x])=>x!==void 0).filter(([x])=>!x.startsWith("memoryV2")).sort(([x],[M])=>x.localeCompare(M)):[],[n]),$=o.useMemo(()=>{const x=u.trim().toLowerCase();return x?I.filter(([M,U])=>`${M} ${ai(U)}`.toLowerCase().includes(x)):I},[I,u]),p=x=>typeof x[1]=="boolean",g=o.useMemo(()=>$.filter(p).filter(([x])=>!ri.has(x)),[$]),v=o.useMemo(()=>$.filter(x=>!p(x)),[$]),w=o.useMemo(()=>T===null?null:I.find(([x])=>x===T)??null,[I,T]),S=async()=>{if(w)try{await navigator.clipboard.writeText(nn(w[1])),q(!0),window.setTimeout(()=>q(!1),1500)}catch(x){St("[SettingsDrawer] copy failed",x)}},h=async(x,M)=>{j(x),E(null);try{const U=await s({[x]:!M});U.ok||E(U.error||i("settings.writeFailed"))}finally{await P()}};return e.jsx(ke,{open:!0,onOpenChange:x=>{x||r()},children:e.jsxs(Ne,{showCloseButton:!1,className:"fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-96 h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-md overflow-y-auto",children:[e.jsx(Re,{children:e.jsxs(Se,{className:"flex items-center gap-2 font-display font-semibold text-text-primary",children:[e.jsx(Ht,{className:"h-4 w-4"}),i("session.settings.title")]})}),e.jsxs("div",{className:"mt-3 space-y-4 text-sm",children:[_&&e.jsx("div",{className:"rounded-md bg-status-error/10 px-3 py-2 text-xs text-status-error",children:_}),n===null&&!d&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-muted",children:[e.jsx(st,{className:"h-3.5 w-3.5 animate-spin"}),i("settings.loading")]}),d&&e.jsx("p",{className:"text-xs text-status-error",children:d}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"rounded-lg border border-border bg-surface-2 px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-text-muted",children:i("settings.model")}),e.jsx("code",{className:"font-mono text-text-secondary",children:n.applied.model||i("settings.defaultModel")})]}),n.applied.effort&&e.jsxs("div",{className:"mt-1 flex items-center justify-between text-xs",children:[e.jsx("span",{className:"text-text-muted",children:"Effort"}),e.jsx("code",{className:"font-mono text-text-secondary",children:n.applied.effort})]}),e.jsx("p",{className:"mt-2 text-[10px] leading-relaxed text-text-muted",children:i("settings.hint")})]}),w?e.jsxs("section",{className:"space-y-2",children:[e.jsxs("button",{type:"button",onClick:()=>{A(null),q(!1)},className:"flex items-center gap-1.5 text-xs text-text-muted transition-colors hover:text-text-primary",children:[e.jsx(ra,{className:"h-3.5 w-3.5"}),i("settings.back")]}),e.jsx("div",{className:"break-all font-mono text-xs font-medium text-text-primary",children:w[0]}),e.jsx("pre",{className:"max-h-[60vh] overflow-y-auto whitespace-pre-wrap break-all rounded-md border border-border bg-surface-2 p-3 font-mono text-[10px] leading-relaxed text-text-secondary",children:nn(w[1])}),e.jsxs("button",{type:"button",onClick:()=>void S(),className:"flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary",children:[N?e.jsx(Wt,{className:"h-3.5 w-3.5 text-status-success"}):e.jsx(ia,{className:"h-3.5 w-3.5"}),N?i("settings.copied"):i("settings.copyValue")]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-surface-2 px-2.5 py-1.5",children:[e.jsx(et,{className:"h-3.5 w-3.5 flex-shrink-0 text-text-muted"}),e.jsx("input",{value:u,onChange:x=>y(x.target.value),placeholder:i("settings.searchPlaceholder"),className:"w-full bg-transparent text-sm text-text-primary placeholder:text-text-muted focus:outline-none"})]}),$.length===0&&e.jsx("p",{className:"text-xs text-text-muted",children:i("settings.noMatch")}),e.jsxs("section",{className:"space-y-1.5",children:[e.jsx("h3",{className:"text-[10px] font-medium uppercase tracking-wide text-text-muted",children:i("settings.memorySection")}),kn.map(x=>{const M=n.effective[x.key],U=typeof M=="boolean"?M:x.defaultValue,X=f===x.key;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-border bg-surface-2 px-3 py-2",children:[e.jsx("div",{className:"truncate text-xs text-text-primary",children:i(x.labelKey)}),e.jsx("button",{type:"button",role:"switch","aria-checked":U,disabled:X,onClick:()=>void h(x.key,U),className:`relative h-5 w-9 flex-shrink-0 rounded-full transition-colors disabled:opacity-50 ${U?"bg-brand":"bg-surface-3"}`,title:U?i("settings.turnOff"):i("settings.turnOn"),children:e.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${U?"left-4.5":"left-0.5"}`})})]},x.key)}),e.jsx("p",{className:"text-[10px] leading-relaxed text-text-muted",children:i("settings.memoryHint")})]}),g.length>0&&e.jsxs("section",{className:"space-y-1.5",children:[e.jsx("h3",{className:"text-[10px] font-medium uppercase tracking-wide text-text-muted",children:K("settings.togglable",{n:g.length})}),g.map(([x,M])=>{const U=f===x;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-border bg-surface-2 px-3 py-2",children:[e.jsx("div",{className:"truncate font-mono text-xs text-text-primary",children:x}),e.jsx("button",{type:"button",role:"switch","aria-checked":M,disabled:U,onClick:()=>void h(x,M),className:`relative h-5 w-9 flex-shrink-0 rounded-full transition-colors disabled:opacity-50 ${M?"bg-brand":"bg-surface-3"}`,title:M?i("settings.turnOff"):i("settings.turnOn"),children:e.jsx("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all ${M?"left-4.5":"left-0.5"}`})})]},x)})]}),v.length>0&&e.jsxs("section",{className:"space-y-1.5",children:[e.jsx("h3",{className:"text-[10px] font-medium uppercase tracking-wide text-text-muted",children:K("settings.readOnly",{n:v.length})}),v.map(([x])=>e.jsxs("button",{type:"button",onClick:()=>A(x),className:"flex w-full items-center justify-between gap-3 rounded-md border border-border bg-surface-2 px-3 py-2 text-left transition-colors hover:bg-surface-3",title:i("settings.viewDetail"),children:[e.jsx("span",{className:"truncate font-mono text-xs text-text-primary",children:x}),e.jsx(ta,{className:"h-3.5 w-3.5 flex-shrink-0 text-text-muted"})]},x))]})]})]})]})]})})}function oi({onClose:r,onAsk:t}){me();const[s,n]=o.useState([]),[l,d]=o.useState(""),[c,u]=o.useState(!1),y=async()=>{const f=l.trim();if(!f||c)return;const j=Date.now();n(_=>[..._,{id:j,question:f,answer:null}]),d(""),u(!0);try{const _=await t(f);n(E=>E.map(T=>T.id===j?{...T,answer:_??i("sideQuestion.noAnswer"),error:_===null}:T))}finally{u(!1)}};return e.jsx(ke,{open:!0,onOpenChange:f=>{f||r()},children:e.jsxs(Ne,{showCloseButton:!1,className:"fixed inset-y-0 right-0 top-auto left-auto translate-x-0 translate-y-0 w-full sm:w-[26rem] h-full max-w-none max-h-none rounded-none border-l border-border bg-surface-1 p-4 sm:max-w-md flex flex-col",children:[e.jsx(Re,{children:e.jsxs(Se,{className:"flex items-center gap-2 font-display font-semibold text-text-primary",children:[e.jsx(Kt,{className:"h-4 w-4"}),i("sideQuestion.title")]})}),e.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-text-muted",children:i("sideQuestion.desc")}),e.jsxs("div",{className:"mt-3 flex-1 space-y-4 overflow-y-auto",children:[s.length===0&&e.jsx("p",{className:"text-xs text-text-muted",children:i("sideQuestion.empty")}),s.map(f=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-md border border-user-bubble-border bg-user-bubble px-4 py-2 text-sm text-text-primary",children:f.question})}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-brand/8 flex items-center justify-center flex-shrink-0 overflow-hidden",children:e.jsx("img",{src:"/code/pony.svg",alt:"Saluzi",width:24,height:24,className:"object-contain",draggable:!1})}),e.jsx("div",{className:"min-w-0 flex-1 pt-1 text-sm text-text-primary",children:f.answer===null?e.jsxs("span",{className:"chat-typing-indicator inline-flex items-center gap-1","aria-hidden":"true",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):e.jsx("div",{className:f.error?"text-status-error":"",children:e.jsx(gr,{children:f.answer})})})]})]},f.id))]}),e.jsxs("div",{className:"mt-3 flex items-end gap-2",children:[e.jsx("textarea",{value:l,onChange:f=>d(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&!f.nativeEvent.isComposing&&(f.preventDefault(),y())},rows:Math.min(4,Math.max(1,l.split(`
76
+ `).length)),placeholder:i("sideQuestion.placeholder"),disabled:c,className:"flex-1 resize-none rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none disabled:opacity-50"}),e.jsx("button",{type:"button",onClick:()=>void y(),disabled:c||!l.trim(),className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-brand text-white transition-colors hover:bg-brand-light disabled:opacity-40 disabled:cursor-not-allowed",title:i("sideQuestion.send"),children:c?e.jsx(st,{className:"h-4 w-4 animate-spin"}):e.jsx(br,{className:"h-4 w-4"})})]})]})})}function li({request:r,handlers:t,now:s,onRetry:n,variant:l}){const d=r.toolName,c=r.toolInput,u=r.description||"";if(r.sentAt!==void 0){const y=d!=="AskUserQuestion"&&d!=="ExitPlanMode";return e.jsx(jr,{decision:r.decision??"allow",stale:gn(r.sentAt,s),onRetry:y&&n?()=>n(r.requestId):void 0})}if(d==="AskUserQuestion"){const y=c.questions||[];return e.jsx(wr,{requestId:r.requestId,questions:y,description:u,onSubmit:f=>t.onSubmitAnswers(r.requestId,f,y),onSkip:()=>t.onReject(r.requestId)})}if(d==="ExitPlanMode"){const y=c.plan||"";return e.jsx(vr,{requestId:r.requestId,planContent:y,description:u,onSubmit:(f,j)=>t.onSubmitPlan(r.requestId,f,j)})}return e.jsx(kr,{requestId:r.requestId,toolName:d,toolInput:c,description:u,suggestions:r.suggestions,onApprove:()=>t.onApprove(r.requestId),onApproveAlways:r.suggestions&&r.suggestions.length>0?()=>t.onApproveAlways(r.requestId,r.suggestions):void 0,onReject:()=>t.onReject(r.requestId),variant:l})}function Nn(r){return r==="AskUserQuestion"?i("permission.waitingAnswer"):r==="ExitPlanMode"?i("permission.waitingPlan"):i("permission.waitingApprove")}function ci(r){return r==="AskUserQuestion"?i("permission.answerShort"):r==="ExitPlanMode"?i("permission.reviewShort"):i("permission.allowShort")}function di({requests:r,onView:t,onOpenQueue:s,onApprove:n,context:l}){if(me(),r.length===0)return null;const d=r.filter(f=>f.sentAt===void 0);if(d.length===0)return e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-1 sm:px-8",children:e.jsxs("button",{type:"button",onClick:s,className:"flex w-full items-center gap-2 border-l-2 border-border bg-surface-1/60 px-3 py-2 text-text-muted transition-colors hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",children:[e.jsx(st,{className:"h-3.5 w-3.5 flex-shrink-0 animate-spin text-approve-text","aria-hidden":"true"}),e.jsx("span",{role:"status","aria-live":"polite",className:"min-w-0 flex-1 text-left text-xs",children:i("permission.syncing")}),e.jsx("span",{className:"permit-mini__action flex-shrink-0",children:i("permission.view")})]})});const c=d[0],u=Nn(c.toolName),y=c.toolName==="AskUserQuestion"||c.toolName==="ExitPlanMode";return e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-1 sm:px-8",children:e.jsxs("div",{className:"permit-bar",children:[e.jsxs("div",{className:"permit-bar__main",children:[e.jsx(fn,{className:"h-4 w-4 flex-shrink-0 text-approve-text","aria-hidden":"true"}),e.jsx("span",{className:"permit-bar__label",children:u}),e.jsxs("span",{className:"permit-bar__detail",children:[c.toolName,c.description?` · ${c.description}`:"",l?` · ${l}`:""]})]}),e.jsx("span",{role:"status","aria-live":"polite",className:"sr-only",children:K("permission.pendingAnnounce",{n:d.length,label:u,tool:c.toolName})}),e.jsx("button",{type:"button",onClick:()=>y?t(c):n(c.requestId),className:yn("permit-btn",y?"permit-btn--brand":"permit-btn--primary"),children:ci(c.toolName)}),e.jsx("button",{type:"button",onClick:()=>t(c),title:i("permission.evidenceHint"),"aria-label":K("permission.revealAria",{tool:c.toolName}),className:"permit-btn permit-btn--secondary",children:i("permission.view")}),d.length>1&&e.jsx("button",{type:"button",onClick:s,className:"permit-btn permit-btn--quiet",children:K("permission.viewAll",{n:d.length})})]})})}function ui({open:r,onClose:t,requests:s,initialRequestId:n,now:l,errorMessage:d,errorRequestId:c,onRetry:u,context:y,...f}){me();const[j,_]=o.useState(null),E=o.useRef(!1),T=o.useRef(new Map),A=s.filter(S=>S.sentAt===void 0),N=s.find(S=>S.requestId===j)??A[0]??s[0];if(o.useEffect(()=>{var S,h;if(r&&!E.current){const x=n&&s.some(M=>M.requestId===n)?n:((S=A[0])==null?void 0:S.requestId)??((h=s[0])==null?void 0:h.requestId)??null;_(x),requestAnimationFrame(()=>{var M;x&&((M=T.current.get(x))==null||M.focus())})}E.current=r},[r,n,s,A]),o.useEffect(()=>{r&&s.length===0&&t()},[r,s.length,t]),o.useEffect(()=>{var h,x;if(!r||!j||s.some(M=>M.requestId===j))return;const S=((h=A[0])==null?void 0:h.requestId)??((x=s[0])==null?void 0:x.requestId)??null;_(S),requestAnimationFrame(()=>{var M;S&&((M=T.current.get(S))==null||M.focus())})},[r,j,s,A]),s.length===0)return null;const q=N&&c===N.requestId?d:void 0,P=S=>{if(!N)return;const h=s.findIndex(M=>M.requestId===N.requestId);if(h<0)return;const x=s[Math.min(Math.max(h+S,0),s.length-1)];_(x.requestId),requestAnimationFrame(()=>{var M;return(M=T.current.get(x.requestId))==null?void 0:M.focus()})};if(!N)return null;const I=S=>S.sentAt===void 0?Nn(S.toolName):gn(S.sentAt,l)?i("permission.ackStale"):i("permission.syncing"),$=N.toolName!=="AskUserQuestion"&&N.toolName!=="ExitPlanMode",p=s.findIndex(S=>S.requestId===N.requestId),g=String(Math.max(p,0)+1).padStart(2,"0"),v=hn(N.suggestions,N.toolName)[0],w=I(N);return e.jsx(ke,{open:r,onOpenChange:S=>{S||t()},children:e.jsxs(Ne,{showCloseButton:!1,onKeyDown:S=>{const h=S.target;h.tagName==="INPUT"||h.tagName==="TEXTAREA"||h.tagName==="SELECT"||h.isContentEditable||(S.key==="ArrowUp"?(S.preventDefault(),P(-1)):S.key==="ArrowDown"&&(S.preventDefault(),P(1)))},className:"permit-sheet permit-docket translate-x-0 translate-y-0",children:[e.jsxs(Re,{className:"permit-masthead permit-docket__masthead",children:[e.jsxs("div",{className:"permit-docket__top",children:[e.jsxs("span",{className:"permit-docket__runhead",children:[i("permission.docketRunhead")," · ",g]}),e.jsx("button",{type:"button",onClick:t,"aria-label":i("common.close"),title:i("common.close"),className:"permit-close",children:e.jsx(Ze,{className:"h-4 w-4","aria-hidden":"true"})})]}),y&&e.jsx("p",{className:"permit-docket__context",title:y,children:y}),e.jsx(Se,{className:"permit-docket__question",children:$&&N.sentAt===void 0?K("permission.allowQuestion",{tool:N.toolName}):i("permission.queueHeading")}),$?N.description?e.jsx(Fs,{className:"permit-docket__lede",children:N.description}):null:e.jsx(Fs,{className:"permit-docket__lede",children:i("permission.queueListHint")}),e.jsxs("dl",{className:"permit-docket__meta",children:[e.jsx("dt",{children:i("permission.docketTool")}),e.jsx("dd",{children:N.toolName}),e.jsx("dt",{children:i("permission.docketState")}),e.jsx("dd",{children:w}),e.jsx("dt",{children:i("permission.docketScope")}),e.jsx("dd",{children:(v==null?void 0:v.scope)??i("permission.scope.localSettings")})]})]}),s.length>1&&e.jsx("ul",{className:"permit-docket__list",children:s.map((S,h)=>{const x=S.requestId===N.requestId;return e.jsx("li",{children:e.jsxs("button",{ref:M=>{M?T.current.set(S.requestId,M):T.current.delete(S.requestId)},type:"button",onClick:()=>_(S.requestId),"aria-expanded":x,className:yn("permit-docket__row",x&&"permit-docket__row--active"),children:[e.jsx("span",{className:"permit-docket__row-index","aria-hidden":"true",children:String(h+1).padStart(2,"0")}),e.jsx("span",{className:"permit-docket__row-name",children:S.toolName}),e.jsx("span",{className:"permit-docket__row-desc",children:S.description}),e.jsx("span",{className:"permit-docket__row-state",children:I(S)})]})},S.requestId)})}),e.jsxs("div",{className:"permit-docket__body",children:[q&&e.jsxs("div",{role:"alert",className:"permit-error",children:[e.jsx("span",{className:"permit-error__text",children:q}),u&&e.jsx("button",{type:"button",onClick:()=>u(N.requestId),className:"permit-btn permit-btn--secondary permit-btn--tiny",children:i("common.retry")})]}),e.jsx(li,{request:N,handlers:f,now:l,onRetry:u,variant:"docket"})]})]})})}function mi(r){const[t,s]=o.useState([]),[n,l]=o.useState(!0),[d,c]=o.useState(null),u=o.useCallback(async()=>{l(!0),c(null);try{const j=await Nr(r);s(j)}catch(j){c(j instanceof Error?j.message:"Failed to load shares")}finally{l(!1)}},[r]);o.useEffect(()=>{u()},[u]);const y=o.useCallback(async j=>{c(null);try{const _=await Sr(r,j);return await u(),_}catch(_){throw c(_ instanceof Error?_.message:"Failed to create share"),_}},[r,u]),f=o.useCallback(async j=>{c(null);try{await _r(r,j),await u()}catch(_){throw c(_ instanceof Error?_.message:"Failed to revoke share"),_}},[r,u]);return{shares:t,isLoading:n,error:d,createShare:y,revokeShare:f,refresh:u}}function xi({open:r,onClose:t,sessionId:s,sessionTitle:n}){me();const{shares:l,isLoading:d,error:c,createShare:u,revokeShare:y}=mi(s),[f,j]=o.useState("user"),[_,E]=o.useState(""),[T,A]=o.useState(""),[N,q]=o.useState("read"),[P,I]=o.useState(""),[$,p]=o.useState(!1),[g,v]=o.useState(null),[w,S]=o.useState(""),[h,x]=o.useState(!1),[M,U]=o.useState(!1);o.useEffect(()=>{r&&(j("user"),E(""),A(""),q("read"),I(""),p(!1),v(null),S(""),x(!1),U(!1))},[r]);const X=async()=>{p(!0),S(""),v(null);try{const D={grantedTo:f==="user"?{userId:_.trim()}:{teamId:T.trim()},permission:N};P.trim()&&(D.expiresAt=P.trim());const ne=await u(D);v(`${window.location.origin}/code/s/${ne.shareToken}`)}catch(D){S(D instanceof Error?D.message:"Failed to create share")}finally{p(!1)}},se=async D=>{try{await y(D)}catch{}},Q=async()=>{if(!g)return;U(!1);try{if(navigator.clipboard&&window.isSecureContext){await navigator.clipboard.writeText(g),x(!0),setTimeout(()=>x(!1),2e3);return}}catch{}const D=document.createElement("textarea");D.value=g,D.style.position="fixed",D.style.opacity="0",document.body.appendChild(D),D.select();try{document.execCommand("copy"),x(!0),setTimeout(()=>x(!1),2e3)}catch{U(!0)}document.body.removeChild(D)};return e.jsx(ke,{open:r,onOpenChange:D=>{D||t()},children:e.jsxs(Ne,{className:"max-w-lg rounded-2xl border-border bg-surface-1 p-6 shadow-2xl",children:[e.jsx(Re,{children:e.jsxs(Se,{className:"font-display text-lg font-semibold text-text-primary",children:[i("share.title"),n?`: ${n}`:""]})}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-text-secondary",children:i("share.grantTo")}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsx("button",{onClick:()=>j("user"),className:`rounded-md px-3 py-1 text-sm transition-colors ${f==="user"?"bg-brand text-white":"bg-surface-2 text-text-secondary hover:bg-surface-3"}`,children:i("share.user")}),e.jsx("button",{onClick:()=>j("team"),className:`rounded-md px-3 py-1 text-sm transition-colors ${f==="team"?"bg-brand text-white":"bg-surface-2 text-text-secondary hover:bg-surface-3"}`,children:i("share.team")})]}),f==="user"?e.jsx(aa,{onSelect:E,placeholder:i("share.userIdPlaceholder"),actionLabel:i("share.selectUser")}):e.jsx("input",{type:"text",value:T,onChange:D=>A(D.target.value),placeholder:i("share.teamIdPlaceholder"),className:"w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-brand focus:outline-none"}),f==="user"&&_&&e.jsxs("p",{className:"mt-1 text-xs text-text-muted",children:[i("share.selectedUser"),": ",e.jsx("span",{className:"font-mono",children:_})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-text-secondary",children:i("share.permission")}),e.jsxs("select",{value:N,onChange:D=>q(D.target.value),className:"w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-brand focus:outline-none",children:[e.jsx("option",{value:"read",children:i("share.permissionRead")}),e.jsx("option",{value:"write",children:i("share.permissionWrite")})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-text-secondary",children:i("share.expiresAt")}),e.jsx("input",{type:"datetime-local",value:P,onChange:D=>I(D.target.value),className:"w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-brand focus:outline-none"})]}),(w||c)&&e.jsx("div",{className:"rounded-md bg-destructive/10 px-3 py-2 text-sm text-status-error",children:w||c}),g&&e.jsxs("div",{className:"rounded-md bg-surface-2 px-3 py-2",children:[e.jsx("p",{className:"text-sm text-text-secondary mb-1",children:i("share.linkCreated")}),e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[e.jsx("code",{className:"min-w-0 flex-1 break-all text-xs text-text-primary",children:g}),e.jsx("button",{onClick:Q,className:"shrink-0 rounded-md bg-brand px-2 py-1 text-xs text-white hover:bg-brand-light transition-colors",children:h?i("share.copied"):i("share.copy")})]}),M&&e.jsx("p",{className:"mt-1 text-xs text-status-error",children:i("share.copyFailed")})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium text-text-secondary",children:i("share.existingShares")}),d?e.jsx("p",{className:"text-sm text-text-muted",children:i("share.loading")}):l.length===0?e.jsx("p",{className:"text-sm text-text-muted",children:i("share.none")}):e.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto",children:l.map(D=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md bg-surface-2 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm text-text-primary",children:D.granted_to_user||D.granted_to_team||"Unknown"}),e.jsxs("p",{className:"truncate text-xs text-text-muted",children:[D.permission==="write"?i("share.permissionWrite"):i("share.permissionRead"),D.expires_at?` · expires ${D.expires_at}`:""]})]}),e.jsx("button",{onClick:()=>se(D.id),className:"shrink-0 rounded-md px-2 py-1 text-xs text-status-error hover:bg-surface-3 transition-colors",children:i("share.revoke")})]},D.id))})]})]}),e.jsxs(Zr,{children:[e.jsx("button",{onClick:t,className:"rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:bg-surface-2 transition-colors",children:i("common.close")}),e.jsx("button",{onClick:X,disabled:$||(f==="user"?!_.trim():!T.trim()),className:"rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-light disabled:opacity-50 transition-colors",children:$?i("common.creating"):i("share.createShare")})]})]})})}function pi(r){const t=new Date,s=new Date(t.getTime()-1440*60*1e3),n=(c,u)=>c.getFullYear()===u.getFullYear()&&c.getMonth()===u.getMonth()&&c.getDate()===u.getDate(),l={today:[],yesterday:[],earlier:[]};for(const c of r){const u=new Date(c.modified||0);n(u,t)?l.today.push(c):n(u,s)?l.yesterday.push(c):l.earlier.push(c)}return[["today",i("resume.today")],["yesterday",i("resume.yesterday")],["earlier",i("resume.earlier")]].map(([c,u])=>({label:u,items:l[c]})).filter(c=>c.items.length>0)}function hi(r){return r?new Date(r).toLocaleString():""}function fi({open:r,onClose:t,adapter:s,onResume:n}){const l=me(),[d,c]=o.useState([]),[u,y]=o.useState(!1),[f,j]=o.useState("");o.useEffect(()=>{if(!r)return;let E=!1;return y(!0),j(""),c([]),s.listResumableSessions().then(T=>{E||c(T)}).catch(T=>{E||j(T instanceof Error?T.message:String(T))}).finally(()=>{E||y(!1)}),()=>{E=!0}},[r,s]);const _=o.useMemo(()=>pi(d),[d,l]);return e.jsx(ke,{open:r,onOpenChange:E=>{E||t()},children:e.jsxs(Ne,{className:"max-w-lg rounded-2xl border-border bg-surface-1 p-6 shadow-2xl",children:[e.jsx(Re,{children:e.jsx(Se,{className:"font-display text-lg font-semibold text-text-primary",children:i("session.resume.title")})}),e.jsxs("div",{className:"max-h-96 min-w-0 space-y-4 overflow-y-auto",children:[u&&e.jsx("p",{className:"py-6 text-center text-sm text-text-muted",children:i("resume.loading")}),!u&&f&&e.jsx("div",{className:"rounded-md bg-destructive/10 px-3 py-2 text-sm text-status-error",children:f}),!u&&!f&&d.length===0&&e.jsx("p",{className:"py-6 text-center text-sm text-text-muted",children:i("resume.empty")}),!u&&!f&&_.map(E=>e.jsxs("div",{children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-text-muted",children:E.label}),e.jsx("div",{className:"space-y-1",children:E.items.map(T=>e.jsxs("button",{type:"button",onClick:()=>n(T),className:"w-full rounded-md px-3 py-2 text-left transition-colors hover:bg-surface-3",children:[e.jsx("p",{className:"truncate text-sm text-text-primary",children:T.title}),e.jsxs("p",{className:"truncate text-xs text-text-muted",children:[hi(T.modified),T.gitBranch?` · ${T.gitBranch}`:""]})]},T.sessionId))})]},E.label))]}),e.jsx("div",{className:"mt-4 flex justify-end",children:e.jsx("button",{type:"button",onClick:t,className:"rounded-lg border border-border px-4 py-2 text-sm text-text-secondary transition-colors hover:bg-surface-2",children:i("common.cancel")})})]})})}const rn=["working","episodic","semantic","procedural"],yi=["user","feedback","project","reference"];function gi({refreshTick:r,recall:t,dreaming:s,onDreamTrigger:n}){me();const{myTeams:l}=Cr(),[d,c]=o.useState(null),[u,y]=o.useState("memories"),[f,j]=o.useState("personal"),[_,E]=o.useState([]),[T,A]=o.useState(!1),[N,q]=o.useState(""),[P,I]=o.useState(""),[$,p]=o.useState(null),[g,v]=o.useState(null),[w,S]=o.useState(!1),[h,x]=o.useState(Ft),M=ca(),[U,X]=o.useState(""),[se,Q]=o.useState(null),[D,ne]=o.useState(!1),Z=o.useRef(null);o.useEffect(()=>{bn().then(c).catch(()=>c(null))},[]);const ce=o.useCallback(async()=>{A(!0),q("");try{E(await Er(f))}catch{q(i("memorySidebar.loadFailed"))}finally{A(!1)}},[f]);o.useEffect(()=>{ce()},[ce,r]),o.useEffect(()=>{const b=()=>void ce();return window.addEventListener("focus",b),()=>window.removeEventListener("focus",b)},[ce]),o.useEffect(()=>{u==="governance"&&Tr().then(v).catch(()=>v(null))},[u,r]),o.useEffect(()=>{Z.current&&clearTimeout(Z.current);const b=P.trim();if(!b){p(null);return}return Z.current=setTimeout(()=>{Mr(b).then(p).catch(()=>p([]))},300),()=>{Z.current&&clearTimeout(Z.current)}},[P]);const Ue=b=>M.expandedKey===b?e.jsx("pre",{className:"mt-1 max-h-48 overflow-y-auto whitespace-pre-wrap rounded bg-surface-3 p-2 text-[10px] leading-relaxed text-text-secondary",children:M.fileContent[b]??"…"}):null,be=(d==null?void 0:d.mode)==="sqlite",[oe,G]=o.useState(!1),[pe,z]=o.useState(""),[je,we]=o.useState(""),[ae,Ae]=o.useState("project"),[Le,nt]=o.useState(""),[Ke,Ie]=o.useState(""),[re,_e]=o.useState(!1),V=()=>{var b;G(!0),z(""),we(""),Ae("project"),nt(""),Ie(((b=l[0])==null?void 0:b.id)??"")},Ce=be&&f==="team",rt=pe.trim().length>0&&Le.trim().length>0&&!re&&(!Ce||!!Ke),_t=async()=>{if(rt){_e(!0),q("");try{await Pr({scope:f,name:pe.trim(),description:je.trim()||void 0,type:ae,content:Le,...Ce?{teamId:Ke}:{}}),G(!1),await ce()}catch(b){q(b instanceof Error?b.message:i("memorySidebar.createFailed"))}finally{_e(!1)}}},ee=()=>{n==null||n()},at=o.useCallback(async()=>{const b=U.trim();if(!(!b||D)){ne(!0),Q(null);try{Q(await Rr(b,5))}catch{Q([])}finally{ne(!1)}}},[U,D]),he=(d==null?void 0:d.teamEnabled)===!0,Be=d==null?void 0:d.automation,Ct=he&&u==="memories"&&!P,Pe=o.useMemo(()=>da(_,h),[_,h]),He=o.useMemo(()=>ua(_),[_]),Ee=(h.types.size>0?1:0)+(ma(h.layers)?0:1)+(h.days!==null?1:0)+(h.minConfidence>0?1:0)+(h.minAccessCount>0?1:0);return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsxs("div",{className:"flex items-center gap-4 px-3 pt-2 pb-1",children:[["memories","governance"].map(b=>e.jsxs("button",{type:"button",onClick:()=>y(b),"aria-pressed":u===b,className:`relative pb-1 text-xs tracking-wide transition-colors ${u===b?"font-semibold text-text-primary":"text-text-muted hover:text-text-secondary"}`,children:[i(b==="memories"?"memorySidebar.memoriesTab":"memorySidebar.governanceTab"),e.jsx("span",{"aria-hidden":"true",className:`absolute inset-x-0 -bottom-2 h-px bg-brand transition-opacity duration-200 ${u===b?"opacity-100":"opacity-0"}`})]},b)),e.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[u==="memories"&&!P&&e.jsx("button",{type:"button",onClick:oe?()=>G(!1):V,disabled:f==="team"&&!he,className:"rounded p-1 text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-50",title:i("memorySidebar.new"),children:oe?e.jsx(Ar,{className:"h-3 w-3"}):e.jsx(Ir,{className:"h-3 w-3"})}),u==="memories"&&!P&&e.jsxs("button",{type:"button",onClick:()=>S(b=>!b),"data-testid":"memory-filter-toggle",className:`relative rounded p-1 transition-colors ${w||Ee>0?"text-brand-text":"text-text-secondary hover:bg-surface-2 hover:text-text-primary"}`,title:i("memorySidebar.filters"),children:[e.jsx(Os,{className:"h-3 w-3"}),Ee>0&&!w&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-3 min-w-3 items-center justify-center rounded-full bg-brand px-0.5 text-[10px] font-bold text-white",children:Ee})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[e.jsx(et,{className:"h-3 w-3 flex-shrink-0 text-text-muted"}),e.jsx("input",{value:P,onChange:b=>I(b.target.value),placeholder:i("memorySidebar.searchPlaceholder"),title:i("memorySidebar.searchHint"),className:"w-full min-w-0 bg-transparent text-xs text-text-primary placeholder:text-text-muted focus:outline-none"}),e.jsx("span",{className:"flex-shrink-0 font-mono text-[10px] tabular-nums text-text-muted",children:$!==null?$.length:Pe.length})]}),N&&e.jsx("p",{className:"px-3 py-1 text-xs text-status-error",children:N}),w&&u==="memories"&&!P&&e.jsxs("div",{className:"space-y-2.5 px-3 pb-3","data-testid":"memory-filter-panel",children:[e.jsx(xa,{filters:h,onChange:x}),e.jsx(pa,{filters:h,onChange:x,counts:He}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-text-muted",children:i("memories.filter.time")}),e.jsx("div",{className:"flex rounded-md bg-surface-2 p-0.5 text-[10px]",children:ha.map(b=>e.jsx("button",{type:"button",onClick:()=>x(te=>({...te,days:b.value})),className:`rounded px-1.5 py-0.5 ${h.days===b.value?"bg-brand-light text-white":"text-text-muted hover:text-text-secondary"}`,children:i(b.labelKey)},String(b.value)))})]}),e.jsxs("div",{className:"flex items-center gap-1.5",title:i("memories.filter.confidence"),children:[e.jsx("span",{className:"flex-shrink-0 text-[10px] text-text-muted",children:i("memories.filter.confidence")}),e.jsx("input",{type:"range",min:0,max:100,step:10,value:h.minConfidence*100,onChange:b=>x(te=>({...te,minConfidence:Number(b.target.value)/100})),style:{"--mem-pct":`${h.minConfidence*100}%`},className:"mem-slider min-w-16 flex-1"}),e.jsx("span",{className:`flex-shrink-0 font-mono text-[10px] ${h.minConfidence>0?"text-brand-text":"text-text-muted"}`,children:K("memories.filter.minConfidence",{pct:h.minConfidence*100})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",title:i("memories.filter.access"),children:[e.jsx("span",{className:"flex-shrink-0 text-[10px] text-text-muted",children:i("memories.filter.access")}),e.jsx("input",{type:"range",min:0,max:10,step:1,value:h.minAccessCount,onChange:b=>x(te=>({...te,minAccessCount:Number(b.target.value)})),style:{"--mem-pct":`${h.minAccessCount*10}%`},className:"mem-slider min-w-12 flex-1"}),e.jsx("span",{className:`flex-shrink-0 font-mono text-[10px] ${h.minAccessCount>0?"text-brand-text":"text-text-muted"}`,children:K("memories.filter.minAccess",{n:h.minAccessCount})}),e.jsx("button",{type:"button",onClick:()=>x(Ft),disabled:!Us(h),className:"flex-shrink-0 rounded px-1 py-0.5 text-[10px] text-text-muted transition-colors hover:bg-surface-2 hover:text-text-primary disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-text-muted",children:i("memories.filter.clear")})]})]}),Be&&Be.mode!=="normal"&&e.jsx("div",{className:"border-b border-status-warning/30 bg-status-warning/10 px-3 py-1.5 text-xs text-status-warning",children:Be.mode==="sa"?i("memorySidebar.saModeBanner"):i("memorySidebar.poorModeBanner")}),$!==null&&e.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-1.5",children:$.length===0?e.jsx("p",{className:"py-8 text-center text-xs text-text-muted",children:i("memorySidebar.noResults")}):e.jsx("ul",{className:"space-y-1",children:$.map(b=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>void M.toggleExpand({path:b.path}),className:"w-full rounded-md px-2 py-1.5 text-left hover:bg-surface-2",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-xs font-medium text-text-primary",children:b.name}),e.jsx(fa,{layer:b.layer})]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5",children:b.matches.map((te,De)=>e.jsxs("li",{className:"flex gap-1.5 text-[10px] leading-relaxed",children:[e.jsx("span",{className:"flex-shrink-0 font-mono text-text-muted",children:te.line===0?"file":`L${te.line}`}),e.jsx("span",{className:"truncate text-text-secondary",children:te.text})]},De))})]}),Ue(b.path)]},b.path))})}),$===null&&u==="memories"&&e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-1.5",children:[t&&t.hits.length>0&&e.jsxs("div",{className:"mb-3 border-l-2 border-brand/30 pl-2.5",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-brand-text",children:i("memorySidebar.recallTitle")}),e.jsxs("p",{className:"mb-1 truncate text-[10px] text-text-muted",title:t.query,children:[i("memorySidebar.recallQuery"),": ",t.query]}),e.jsx("ul",{className:"space-y-0.5",children:t.hits.slice(0,5).map(b=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>void M.toggleExpand({path:b.path}),className:"flex w-full items-center justify-between gap-2 rounded px-1 py-0.5 text-left text-xs hover:bg-surface-2",title:b.path,children:[e.jsx("span",{className:"truncate text-text-secondary",children:b.path.replace(/^team\//,"").replace(/\.md$/,"")}),b.score!==void 0&&e.jsxs("span",{className:"flex-shrink-0 text-[10px] text-text-muted",children:[(b.score*100).toFixed(0),"%"]})]}),Ue(b.path)]},b.path))})]}),Ct&&e.jsx("div",{className:"mb-2 flex items-center gap-4 px-1 text-xs",children:["personal","team"].map(b=>e.jsx("button",{type:"button",onClick:()=>j(b),className:`pb-1 transition-colors ${f===b?"font-semibold text-text-primary":"text-text-muted hover:text-text-secondary"}`,children:b==="personal"?i("memorySidebar.personal"):i("memorySidebar.team")},b))}),f==="team"&&he&&!oe&&e.jsx("p",{className:"mb-2 px-1 text-[10px] leading-relaxed text-text-muted",children:i("memorySidebar.teamHint")}),oe&&e.jsxs("div",{className:"mb-2 space-y-1.5 rounded-md bg-surface-2 p-2",children:[e.jsx("input",{value:pe,onChange:b=>z(b.target.value),placeholder:i("memorySidebar.create.namePlaceholder"),className:"w-full rounded bg-surface-3 px-2 py-1 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-brand/40"}),e.jsx("input",{value:je,onChange:b=>we(b.target.value),placeholder:i("memorySidebar.create.descriptionPlaceholder"),className:"w-full rounded bg-surface-3 px-2 py-1 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-brand/40"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("select",{value:ae,onChange:b=>Ae(b.target.value),className:"flex-shrink-0 rounded bg-surface-3 px-1.5 py-1 text-xs text-text-primary focus:outline-none",children:yi.map(b=>e.jsx("option",{value:b,children:b},b))}),Ce?e.jsxs("select",{value:Ke,onChange:b=>Ie(b.target.value),"aria-label":i("memories.scope.team"),className:"min-w-0 flex-1 rounded bg-surface-3 px-1.5 py-1 text-xs text-text-primary focus:outline-none",children:[l.length===0&&e.jsx("option",{value:"",children:"—"}),l.map(b=>e.jsx("option",{value:b.id,children:b.name},b.id))]}):e.jsx("span",{className:"truncate text-[10px] text-text-muted",children:f==="team"?i("memorySidebar.team"):i("memorySidebar.personal")})]}),e.jsx("textarea",{value:Le,onChange:b=>nt(b.target.value),placeholder:i("memorySidebar.create.contentPlaceholder"),rows:6,className:"w-full rounded bg-surface-3 p-2 text-[10px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-brand/40"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{type:"button",onClick:()=>void _t(),disabled:!rt,className:"rounded bg-accent px-2 py-0.5 text-[10px] font-medium text-white hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50",children:re?"…":i("memorySidebar.new")}),e.jsx("button",{type:"button",onClick:()=>G(!1),className:"rounded px-2 py-0.5 text-[10px] text-text-muted hover:bg-surface-3",children:i("memorySidebar.cancel")})]})]}),T?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(b=>e.jsx("div",{className:"h-12 animate-pulse rounded-md bg-surface-2"},b))}):_.length===0?e.jsxs("div",{className:"py-10 text-center",children:[e.jsx(Lt,{className:"mx-auto h-6 w-6 text-text-muted/40"}),e.jsx("p",{className:"mt-2 text-xs text-text-muted",children:i("memorySidebar.empty")})]}):Pe.length===0?e.jsxs("div",{className:"py-10 text-center",children:[e.jsx(Os,{className:"mx-auto h-6 w-6 text-text-muted/40"}),e.jsx("p",{className:"mt-2 text-xs text-text-muted",children:i("memories.filter.empty")}),Us(h)?e.jsx("button",{type:"button",onClick:()=>x(Ft),className:"mt-2 rounded-md px-2.5 py-1 text-xs text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary",children:i("memories.filter.clear")}):e.jsx("p",{className:"mt-1 px-4 text-[10px] leading-relaxed text-text-muted",children:i("memories.filter.layersHidden")})]}):e.jsx(ya,{files:Pe,teamEnabled:he,teams:be?l:void 0,onChanged:ce,expandedKey:M.expandedKey,fileContent:M.fileContent,onToggleExpand:M.toggleExpand})]}),$===null&&u==="governance"&&e.jsx("div",{className:"flex-1 overflow-y-auto p-3 text-xs",children:g?e.jsxs("div",{className:"space-y-4",children:[n&&e.jsxs("div",{children:[e.jsxs("button",{type:"button",disabled:s||!g.automation.autoDream,onClick:ee,className:"inline-flex w-full items-center justify-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx(oa,{className:"h-3.5 w-3.5"}),s?i("memorySidebar.dreaming"):i("memorySidebar.dream")]}),!g.automation.autoDream&&e.jsx("p",{className:"mt-1 text-center text-[10px] text-text-muted",children:i("memorySidebar.dreamDisabled")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1 text-[10px] font-semibold uppercase tracking-wide text-text-muted",children:i("memorySidebar.recallTest.title")}),e.jsx("p",{className:"mb-1.5 text-[10px] leading-relaxed text-text-muted",children:i("memorySidebar.recallTest.hint")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("input",{value:U,onChange:b=>X(b.target.value),onKeyDown:b=>{b.key==="Enter"&&!b.nativeEvent.isComposing&&at()},placeholder:i("memorySidebar.recallTest.placeholder"),className:"min-w-0 flex-1 rounded-md bg-surface-2 px-2 py-1 text-xs text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-brand/40"}),e.jsx("button",{type:"button",onClick:()=>void at(),disabled:D||!U.trim(),className:"flex-shrink-0 rounded-md bg-accent px-2.5 py-1 text-xs font-medium text-white hover:bg-accent/90 disabled:cursor-not-allowed disabled:opacity-50",children:D?i("memorySidebar.recallTest.running"):i("memorySidebar.recallTest.run")})]}),se!==null&&e.jsx("ul",{className:"mt-1.5 space-y-0.5 rounded-md bg-surface-2 p-2",children:se.length===0?e.jsx("li",{className:"text-[10px] text-text-muted",children:i("memorySidebar.recallTest.noResults")}):se.map(b=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>void M.toggleExpand({path:b.path}),className:"flex w-full items-center justify-between gap-2 rounded px-1 py-0.5 text-left text-xs hover:bg-surface-3",title:b.path,children:[e.jsx("span",{className:"truncate text-text-secondary",children:b.path.replace(/^team\//,"").replace(/\.md$/,"")}),e.jsxs("span",{className:"flex-shrink-0 text-[10px] text-text-muted",children:[(b.score*100).toFixed(0),"%",b.confidence!==void 0?` · conf ${b.confidence.toFixed(2)}`:""]})]}),Ue(b.path)]},b.path))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted",children:i("memorySidebar.layers")}),e.jsx("ul",{className:"space-y-1",children:rn.map(b=>{const te=g.layers[b],De=Math.max(...rn.map(it=>g.layers[it]),1);return e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-16 flex-shrink-0 text-text-secondary",children:b}),e.jsx("div",{className:"h-1.5 flex-1 overflow-hidden rounded-full bg-surface-2",children:e.jsx("div",{className:"h-full rounded-full bg-brand",style:{width:`${te/De*100}%`}})}),e.jsx("span",{className:"w-6 text-right text-text-muted",children:te})]},b)})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted",children:i("memorySidebar.health")}),e.jsxs("div",{className:"rounded-md bg-surface-2 p-2 text-[10px] text-text-secondary",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:i("memorySidebar.total")}),e.jsx("span",{children:g.health.totalMemories})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:i("memorySidebar.capacity")}),e.jsxs("span",{className:g.health.capacity.tier==="critical"?"text-status-error":g.health.capacity.tier==="warning"?"text-status-warning":"text-status-active",children:[g.health.capacity.utilizationPct.toFixed(0),"% · ",g.health.capacity.tier]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:i("memorySidebar.avgConfidence")}),e.jsx("span",{children:g.health.avgConfidence.toFixed(2)})]})]})]}),g.alerts.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted",children:[i("memorySidebar.alerts")," (",g.alerts.length,")"]}),e.jsx("ul",{className:"space-y-1 rounded-md bg-status-warning/5 p-2",children:g.alerts.slice(-8).reverse().map((b,te)=>e.jsx("li",{className:"text-[10px] leading-relaxed text-text-secondary",children:b},te))})]}),g.conflicts&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-status-warning",children:i("memorySidebar.conflicts")}),e.jsx("pre",{className:"max-h-40 overflow-y-auto whitespace-pre-wrap rounded-md bg-surface-2 p-2 text-[10px] leading-relaxed text-text-secondary",children:g.conflicts})]})]}):e.jsx("p",{className:"py-10 text-center text-text-muted",children:i("memorySidebar.loadFailed")})})]})}class bi{constructor(t,s,n,l){F(this,"pending",null);this.current=t,this.apply=s,this.send=n,this.onError=l}set(t){if(t===this.current)return;const s=this.current;this.current=t,this.pending={requestId:null,previous:s},this.apply(t);try{Promise.resolve(this.send(t)).then(n=>{this.pending&&(this.pending.requestId=n)}).catch(n=>{this.rollback(s,an(n),"send")})}catch(n){this.rollback(s,an(n),"send")}}handleControlResponse(t){const s=this.pending;if(!s||s.requestId!==t.requestId)return!1;const{previous:n}=s;return this.pending=null,t.subtype==="error"&&this.rollback(n,t.error??"","response"),!0}sync(t){t!==this.current&&(this.current=t,this.apply(t),this.pending=null)}adoptExternal(t){this.pending||t!==this.current&&(this.current=t)}getCurrent(){return this.current}rollback(t,s,n){var l;this.pending=null,this.current=t,this.apply(t),s&&((l=this.onError)==null||l.call(this,s,n))}}function an(r){return r instanceof Error?r.message:String(r)}function wt(r){const t=o.useRef(r);t.current=r;const s=o.useRef(null);s.current||(s.current=new bi(r.value,l=>t.current.apply(l),l=>t.current.send(l),(l,d)=>{var c,u;return(u=(c=t.current).onError)==null?void 0:u.call(c,l,d)}));const n=s.current;return o.useEffect(()=>{n.adoptExternal(r.value)}),o.useMemo(()=>({set:l=>n.set(l),handleControlResponse:l=>n.handleControlResponse(l),sync:l=>n.sync(l)}),[n])}const Sn="rcs_context_usage_";function _n(){try{if(typeof localStorage<"u")return localStorage}catch{}return null}function on(){return{totalTokens:0,rawMaxTokens:0,percentage:0}}function ji(r){if(!r||typeof r!="object"||Array.isArray(r))return null;const t=r,{totalTokens:s,rawMaxTokens:n,percentage:l}=t;if(typeof s!="number"||typeof n!="number"||typeof l!="number")return null;const d=t.categories,c=Array.isArray(d)?d.filter(u=>!!u&&typeof u=="object"&&typeof u.name=="string").map(u=>({name:u.name,tokens:typeof u.tokens=="number"?u.tokens:0,...u.isDeferred===!0?{isDeferred:!0}:{}})):void 0;return{totalTokens:s,rawMaxTokens:n,percentage:l,...typeof t.model=="string"&&t.model?{model:t.model}:{},...c&&c.length>0?{categories:c}:{}}}function wi(r,t=_n()){if(!t||!r)return null;try{const s=t.getItem(Sn+r);return s?ji(JSON.parse(s)):null}catch{return null}}function vi(r,t,s=_n()){if(!(!s||!r))try{s.setItem(Sn+r,JSON.stringify(t))}catch{}}const ki=[{key:"nav",entries:["artifacts","memories","side","search","mcp","settings","share","tasks"]},{key:"bar",entries:["mode","model","token","context"]}];function Ni(){return me(),e.jsx("div",{className:"w-full",children:ki.map((r,t)=>e.jsxs("section",{className:t>0?"mt-8 min-w-0":"min-w-0",children:[e.jsx("h4",{className:"sr-only",children:i(`session.emptyGuide.${r.key}`)}),e.jsx("dl",{className:"grid grid-cols-1 gap-y-[0.95rem]",children:r.entries.map(s=>e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-y-[0.15rem] sm:grid-cols-[minmax(0,9.5rem)_minmax(0,1fr)] sm:items-baseline sm:gap-x-5 sm:gap-y-0",children:[e.jsx("dt",{className:"font-sans text-[0.8125rem] font-medium leading-[1.45] text-text-primary",children:i(`session.emptyGuide.${r.key}.${s}`)}),e.jsx("dd",{className:"font-sans text-xs leading-[1.5] text-text-muted",children:i(`session.emptyGuide.${r.key}.${s}Desc`)})]},s))})]},r.key))})}function Si(r){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/acp/relay/${r}`}function _i(r){const t=Si(r),s=qr(),n=s?{proxyUrl:t,token:s}:{proxyUrl:t};return new Dr(n)}const Oe=[{value:"default",labelKey:"session.mode.default",descKey:"session.mode.defaultDesc"},{value:"acceptEdits",labelKey:"session.mode.acceptEdits",descKey:"session.mode.acceptEditsDesc"},{value:"plan",labelKey:"session.mode.plan",descKey:"session.mode.planDesc"},{value:"bypassPermissions",labelKey:"session.mode.bypass",descKey:"session.mode.bypassDesc"}],ln="rcs_permission_mode";function vt(r){return r<1e3?String(r):r<1e6?`${(r/1e3).toFixed(1)}k`:`${(r/1e6).toFixed(1)}M`}function Ci(r){const t=Oe.findIndex(s=>s.value===r);return Oe[(t+1+Oe.length)%Oe.length].value}const tt=[{value:"off",labelKey:"session.thinking.off",descKey:"session.thinking.offDesc",label:void 0,description:void 0,tokens:0},{value:"on",labelKey:"session.thinking.on",descKey:"session.thinking.onDesc",label:void 0,description:void 0,tokens:null},{value:"8192",labelKey:void 0,descKey:void 0,label:"8k",description:"8192 tokens",tokens:8192},{value:"16384",labelKey:void 0,descKey:void 0,label:"16k",description:"16384 tokens",tokens:16384},{value:"32768",labelKey:void 0,descKey:void 0,label:"32k",description:"32768 tokens",tokens:32768}],cn="rcs_thinking_budget",Nt=[{value:"auto",effort:void 0,labelKey:"session.effort.auto",descKey:"session.effort.autoDesc",label:void 0},{value:"low",effort:"low",labelKey:void 0,descKey:"session.effort.lowDesc",label:"low"},{value:"medium",effort:"medium",labelKey:void 0,descKey:"session.effort.mediumDesc",label:"medium"},{value:"high",effort:"high",labelKey:void 0,descKey:"session.effort.highDesc",label:"high"},{value:"xhigh",effort:"xhigh",labelKey:void 0,descKey:"session.effort.xhighDesc",label:"xhigh"},{value:"max",effort:"max",labelKey:void 0,descKey:"session.effort.maxDesc",label:"max"}],Ei=r=>r.labelKey?i(r.labelKey):r.label,Ti=r=>r.labelKey?i(r.labelKey):r.label,dn="rcs_effort",un=[{value:"normal",descKey:"session.tokenMode.normalDesc"},{value:"poor",descKey:"session.tokenMode.poorDesc"},{value:"sa",descKey:"session.tokenMode.saDesc"}],mn="rcs_token_mode";function Mi(r){return r!=null&&r.capabilities?r.capabilities:r?{file_search:!0,clear:!0,set_max_thinking_tokens:!0,get_context_usage:!0,stop_task:!0,set_model:!0,set_permission_mode:!0,interrupt:!0,end_session:!0,mcp_management:!0,remote_settings:!0,rewind:!0,resume:!0,set_effort:!0,set_token_mode:!1,side_question:!0}:{file_search:!1,clear:!0,set_max_thinking_tokens:!0,get_context_usage:!1,stop_task:!0,set_model:!0,set_permission_mode:!0,interrupt:!0,end_session:!1,mcp_management:!1,remote_settings:!1,rewind:!1,resume:!1,set_effort:!1,set_token_mode:!1,side_question:!1}}function xn({icon:r,label:t,levels:s,index:n,onChange:l,disabled:d}){const c=Math.max(s.length-1,0),u=Math.min(Math.max(n,0),c),[y,f]=o.useState(null),j=y??u,_=s[j],E=c>0?j/c*100:0,T=()=>{y!==null&&(y!==u&&l(y),f(null))};return e.jsxs("div",{className:d?"opacity-55":void 0,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-brand/10 text-brand-text",children:e.jsx(r,{className:"h-3 w-3",strokeWidth:2})}),e.jsx("span",{className:"truncate font-display text-xs font-semibold text-text-primary",children:t})]}),e.jsx("span",{className:"shrink-0 rounded-full border border-brand/20 bg-brand/10 px-1.5 py-0.5 font-mono text-[10px] font-medium tabular-nums text-brand-text",children:_.label})]}),e.jsxs("div",{className:"relative mt-2 h-6",children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-[7px] top-1/2 h-[3px] -translate-y-1/2 overflow-hidden rounded-full bg-surface-3",children:e.jsx("div",{className:"h-full rounded-full bg-brand transition-[width] duration-200 ease-out",style:{width:`${E}%`}})}),e.jsx("div",{className:"pointer-events-none absolute inset-x-[7px] top-1/2 h-[7px] -translate-y-1/2",children:s.map((A,N)=>e.jsx("span",{className:`absolute top-0 h-full w-[1.5px] -translate-x-1/2 rounded-full ${N<=j?"bg-primary-foreground/55":"bg-text-muted/25"}`,style:{left:c>0?`${N/c*100}%`:"50%"}},A.value))}),e.jsx("input",{type:"range",min:0,max:c,step:1,value:j,disabled:d,"aria-label":t,"aria-valuetext":_.label,onChange:A=>f(Number(A.target.value)),onPointerUp:T,onKeyUp:T,onBlur:T,className:"rcs-range relative z-10"})]}),e.jsx("div",{className:"mt-1 flex items-start justify-between gap-1",children:s.map((A,N)=>e.jsx("button",{type:"button",disabled:d,onClick:()=>{f(null),l(N)},className:`min-w-0 truncate font-mono text-[10px] leading-4 tabular-nums transition-colors disabled:cursor-not-allowed ${N===j?"font-semibold text-brand-text":"text-text-muted/70 hover:text-text-primary"}`,children:A.label},A.value))}),e.jsx("p",{className:"mt-0.5 min-h-4 text-xs leading-4 text-text-muted",children:_.description})]})}function Ri({mode:r,onModeChange:t,disabled:s}){const[n,l]=o.useState(!1),d=un.find(c=>c.value===r);return e.jsxs(Gt,{open:n,onOpenChange:l,children:[e.jsx(zt,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:s,className:"flex items-center gap-1.5 rounded-lg px-2 h-7 text-xs text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-display",title:i("session.tokenMode.title"),children:[e.jsx(wa,{className:"h-3 w-3"}),e.jsx("span",{className:`min-w-0 truncate ${r!=="normal"?"font-medium text-brand-text":""}`,children:d?i(`session.tokenMode.${d.value}`):i("session.tokenMode.fallback")}),n?e.jsx(Yt,{className:"h-3 w-3"}):e.jsx(Vt,{className:"h-3 w-3"})]})}),e.jsx(Jt,{className:"w-64 p-1",align:"start",children:un.map(c=>e.jsxs("button",{type:"button",onClick:()=>{t(c.value),l(!1)},className:"flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left hover:bg-surface-2 transition-colors",children:[e.jsx("span",{className:"mt-0.5 flex h-4 w-4 flex-shrink-0 items-center justify-center",children:r===c.value&&e.jsx(Wt,{className:"h-3.5 w-3.5 text-brand-text"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-text-primary",children:i(`session.tokenMode.${c.value}`)}),e.jsx("div",{className:"text-xs text-text-muted",children:i(c.descKey)})]})]},c.value))})]})}const Ai=new Set(["Free space","Autocompact buffer","Compact buffer"]),pn=["bg-brand","bg-status-active","bg-status-success","bg-violet-500","bg-amber-500","bg-pink-500","bg-teal-500"];function Ii({usage:r}){const t=Math.min(100,Math.max(0,r.percentage)),s=t>=80,n=(r.categories??[]).filter(u=>!u.isDeferred&&!Ai.has(u.name)),l=(r.categories??[]).filter(u=>u.isDeferred),d=n.reduce((u,y)=>u+y.tokens,0),c=[`${K("session.context.tooltip",{used:vt(r.totalTokens),max:vt(r.rawMaxTokens)})}${r.model?` · ${r.model}`:""}`,...n.slice(0,8).map(u=>`${u.name}: ${vt(u.tokens)}`),...l.slice(0,3).map(u=>`${u.name.replace(/\s*\(deferred\)$/i,"")}${i("session.context.deferredSuffix")}: ${vt(u.tokens)}`)];return e.jsxs("span",{className:"flex items-center gap-1.5 text-[10px] text-text-muted font-mono",title:c.join(`
77
+ `),children:[e.jsx("span",{className:"relative flex h-1.5 w-16 overflow-hidden rounded-full bg-surface-3",children:n.length>0?n.map((u,y)=>e.jsx("span",{className:s&&y===0?"bg-status-warning":pn[y%pn.length],style:{width:`${Math.min(100,Math.max(0,d>0?u.tokens/d*t:0))}%`}},u.name)):e.jsx("span",{className:`absolute inset-y-0 left-0 rounded-full transition-all ${s?"bg-status-warning":"bg-brand/70"}`,style:{width:`${t}%`}})}),e.jsxs("span",{children:[t,"%"]})]})}function Pi({models:r,currentModelId:t,onSelect:s,showThinking:n,thinkingBudget:l,onThinkingChange:d,showEffort:c,effort:u,onEffortChange:y,disabled:f}){const[j,_]=o.useState(!1),E=r.find(w=>w.modelId===t)??null,T=r.length>0,A=n||c,N=T||A,q=tt.findIndex(w=>w.value===l),P=q>=0?q:1,I=Nt.findIndex(w=>w.value===u),$=I>=0?I:0,p=tt.map(w=>({value:w.value,label:Ti(w),description:w.descKey?i(w.descKey):w.description??""})),g=Nt.map(w=>({value:w.value,label:Ei(w),description:i(w.descKey)})),v=[i("session.model.title"),n?p[P].label:null,c?g[$].label:null].filter(Boolean).join(" · ");return e.jsxs(Gt,{open:j,onOpenChange:N?_:void 0,children:[e.jsx(zt,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:f||!N,className:"flex items-center gap-1.5 rounded-lg px-2 h-7 text-xs text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-display",title:v,children:[e.jsx(vn,{className:"h-3 w-3"}),e.jsx("span",{className:"min-w-0 truncate",children:(E==null?void 0:E.name)??t??i("session.model.title")}),A&&e.jsxs("span",{className:"ml-0.5 flex items-center gap-1 border-l border-border/70 pl-1.5",children:[n&&e.jsx(Bs,{className:"h-3 w-3"}),c&&e.jsx(Ks,{className:"h-3 w-3"})]}),j?e.jsx(Yt,{className:"h-3 w-3"}):e.jsx(Vt,{className:"h-3 w-3"})]})}),e.jsxs(Jt,{className:"w-[21rem] max-w-[calc(100vw-2rem)] max-h-[calc(100dvh-2rem)] overflow-y-auto overflow-x-hidden p-0",align:"start",children:[e.jsxs("div",{className:"px-3 pt-3 pb-1.5",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between px-1",children:[e.jsx("span",{className:"font-display text-[10px] font-semibold uppercase tracking-[0.16em] text-text-muted",children:i("session.model.section")}),T&&e.jsx("span",{className:"font-mono text-[10px] tabular-nums text-text-muted",children:r.length})]}),T?e.jsx("div",{className:"[&_[data-slot=command-list]]:max-h-[min(15rem,38vh)]",children:e.jsx(Jr,{models:r,currentModelId:t,onSelect:w=>{s(w.modelId),_(!1)},showSearch:r.length>5})}):e.jsx("p",{className:"px-1 py-2 text-xs text-text-muted",children:i("session.model.unavailable")})]}),A&&e.jsxs("div",{className:"border-t border-border/60 bg-surface-2/35 px-3 pt-2.5 pb-3",children:[e.jsx("div",{className:"mb-2.5 px-1",children:e.jsx("span",{className:"font-display text-[10px] font-semibold uppercase tracking-[0.16em] text-text-muted",children:i("session.model.tuning")})}),e.jsxs("div",{className:"space-y-3.5",children:[n&&e.jsx(xn,{icon:Bs,label:i("session.thinking.title"),levels:p,index:P,onChange:w=>d(tt[w].value),disabled:f}),c&&e.jsx(xn,{icon:Ks,label:i("session.effort.title"),levels:g,index:$,onChange:w=>y(Nt[w].value),disabled:f})]})]})]})]})}function Di({mode:r,onModeChange:t,disabled:s}){const[n,l]=o.useState(!1),d=Oe.find(c=>c.value===r);return e.jsxs(Gt,{open:n,onOpenChange:l,children:[e.jsx(zt,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:s,className:"flex items-center gap-1.5 rounded-lg px-2 h-7 text-xs text-text-muted hover:text-text-primary hover:bg-surface-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-display",title:i("session.mode.title"),children:[e.jsx(Vr,{className:"h-3 w-3"}),e.jsx("span",{className:"min-w-0 truncate",children:d?i(d.labelKey):r}),n?e.jsx(Yt,{className:"h-3 w-3"}):e.jsx(Vt,{className:"h-3 w-3"})]})}),e.jsx(Jt,{className:"w-64 p-1",align:"start",children:Oe.map(c=>e.jsxs("button",{type:"button",onClick:()=>{t(c.value),l(!1)},className:"flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left hover:bg-surface-2 transition-colors",children:[e.jsx("span",{className:"mt-0.5 flex h-4 w-4 flex-shrink-0 items-center justify-center",children:r===c.value&&e.jsx(Wt,{className:"h-3.5 w-3.5 text-brand-text"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-text-primary",children:i(c.labelKey)}),e.jsx("div",{className:"text-xs text-text-muted",children:i(c.descKey)})]})]},c.value))})]})}function Ji({sessionId:r,onBack:t}){var Cs;me();const[s,n]=o.useState(null),[l,d]=o.useState(null),[c,u]=o.useState(""),[y,f]=o.useState(!1),[j,_]=o.useState(!1),[E,T]=o.useState(!1),[A,N]=o.useState(!1),[q,P]=o.useState(!1),[I,$]=o.useState(!1),[p,g]=o.useState(!1),[v,w]=o.useState(""),[S,h]=o.useState(0),x=o.useRef(null),[M,U]=o.useState({text:"",nonce:0}),[X,se]=o.useState(!1),[Q,D]=o.useState(!1),[ne,Z]=o.useState(0),[ce,Ue]=o.useState(0),[be,oe]=o.useState([]),[G,pe]=o.useState(!1),[z,je]=o.useState([]),we=o.useRef(z);we.current=z;const ae=o.useMemo(()=>z.filter(a=>a.sentAt===void 0),[z]),Ae=o.useRef(!1),[Le,nt]=o.useState(null),[Ke,Ie]=o.useState(()=>Date.now()),[re,_e]=o.useState(null),[V,Ce]=o.useState(null),[rt,_t]=o.useState(()=>Qt()),[ee,at]=o.useState(null),[he,Be]=o.useState(()=>localStorage.getItem(cn)||"off"),[Ct,Pe]=o.useState(()=>wi(r)),[He,Ee]=o.useState(!0),[b,te]=o.useState(null),[De,it]=o.useState(null),[ot,lt]=o.useState([]),[Cn,Et]=o.useState(!1),[Tt,Xt]=o.useState(""),Mt=o.useRef(null),[ct,En]=o.useState(()=>localStorage.getItem(ln)||"default"),[Zt,es]=o.useState(null),Qe=o.useRef(null),[ts,ss]=o.useState(null),We=o.useRef(null),fe=o.useRef(null),dt=o.useRef(new Set),ns=o.useRef(0),[rs,Tn]=o.useState(0),[de,as]=o.useState(null),Ge=o.useRef(null),ze=o.useRef(new Map),ut=o.useRef(new Map),is=o.useRef(null);is.current=re;const os=o.useRef(null),ls=o.useRef(be);ls.current=be;const mt=o.useRef(null);mt.current||(mt.current=new ga(ba()));const cs=o.useRef(r);cs.current=(s==null?void 0:s.title)||r,o.useEffect(()=>{var a;(a=mt.current)==null||a.reset()},[r]),o.useEffect(()=>{re&&!j&&requestAnimationFrame(()=>{var a;return(a=os.current)==null?void 0:a.focus()})},[re,j]),o.useEffect(()=>{ns.current>0&&z.length===0&&(Tn(a=>a+1),j&&(_(!1),requestAnimationFrame(()=>{var a;return(a=document.getElementById("chat-input"))==null?void 0:a.focus()}))),ns.current=z.length},[z.length,j]),o.useEffect(()=>{if(!z.some(k=>k.sentAt!==void 0))return;const m=setInterval(()=>Ie(Date.now()),1e3);return()=>clearInterval(m)},[z]);const ye=o.useCallback(a=>{es(a),Qe.current&&clearTimeout(Qe.current),Qe.current=setTimeout(()=>es(null),5e3)},[]),ve=o.useCallback(a=>{ss(a),We.current&&clearTimeout(We.current),We.current=setTimeout(()=>ss(null),5e3)},[]),xt=wt({value:ct,apply:a=>{En(a);try{localStorage.setItem(ln,a)}catch{}},send:a=>{const m=fe.current;return m?m.setPermissionMode(a):Promise.reject(new Error("adapter not ready"))},onError:(a,m)=>{console.error("[SessionDetail] set permission mode failed:",a),ye(m==="send"?K("session.mode.switchFailedRequest",{message:a}):a||i("session.mode.switchFailed"))}}),Rt=o.useCallback(a=>xt.set(a),[xt]),[ds,Mn]=o.useState(()=>localStorage.getItem(mn)||"normal"),pt=wt({value:ds,apply:a=>{Mn(a);try{localStorage.setItem(mn,a)}catch{}},send:a=>{const m=fe.current;return m?m.setTokenMode(a):Promise.reject(new Error("adapter not ready"))},onError:(a,m)=>{console.error("[SessionDetail] set token mode failed:",a),ye(m==="send"?K("session.tokenMode.failedRequest",{message:a}):a||i("session.tokenMode.failed"))}}),At=wt({value:he,apply:a=>{Be(a);try{localStorage.setItem(cn,a)}catch{}},send:a=>{var C;const m=fe.current;if(!m)return Promise.reject(new Error("adapter not ready"));const k=((C=tt.find(R=>R.value===a))==null?void 0:C.tokens)??null;return m.setThinkingBudget(k)},onError:(a,m)=>{console.error("[SessionDetail] set thinking budget failed:",a),ye(m==="send"?K("session.thinking.failedRequest",{message:a}):a||i("session.thinking.failed"))}}),Rn=o.useCallback((a,m,k)=>{as({tool:a,decision:m,remembered:k,nonce:Date.now()}),Ge.current&&clearTimeout(Ge.current),Ge.current=setTimeout(()=>as(null),2200)},[]);o.useEffect(()=>()=>{Ge.current&&clearTimeout(Ge.current)},[]);const L=o.useMemo(()=>new Ba(r,oe,{onStatusChange:a=>{var m;d(a),pe(a==="running"||a==="requires_action"),(m=mt.current)==null||m.onStatus(a,cs.current)},onError:a=>{console.error("[RCSChatAdapter] error:",a)},onPermissionRequest:a=>{je(m=>m.some(k=>k.requestId===a.requestId)?m:[...m,a])},onPermissionSettled:(a,m)=>{var R;if(a===null){je([]),ze.current.clear(),ut.current.clear();return}const k=we.current.find(O=>O.requestId===a),C=ze.current.get(a);k&&m&&Rn(k.toolName,m,C),ze.current.delete(a),ut.current.delete(a),((R=is.current)==null?void 0:R.requestId)===a&&_e(null),je(O=>O.filter(W=>W.requestId!==a))},onModelsStateChange:a=>{Ce(a)},onSubagentUpdate:a=>{_t(a)},onControlResponse:a=>{At.handleControlResponse(a)||pt.handleControlResponse(a)||ps.handleControlResponse(a)||xt.handleControlResponse(a)},onPermissionModeChange:a=>{xt.sync(a)},onWorkerInfoChange:a=>{at(m=>JSON.stringify(m)===JSON.stringify(a)?m:a)},onTurnStart:a=>{te(a)},onElicitationRequest:a=>{it(a)}}),[r,ye]);o.useEffect(()=>(fe.current=L,()=>{L.disconnect()}),[L]);const B=o.useMemo(()=>Mi(ee),[ee]),us=o.useRef(!1);o.useEffect(()=>{var k;if(!B.set_max_thinking_tokens||us.current)return;const a=fe.current;if(!a)return;const m=((k=tt.find(C=>C.value===he))==null?void 0:k.tokens)??null;a.setThinkingBudget(m).then(()=>{us.current=!0}).catch(C=>console.error("[SessionDetail] reconcile thinking budget failed:",C))},[B.set_max_thinking_tokens,he,ee]);const An=B.stop_task?a=>{L.stopSubagent(a).then(m=>{m.ok||ve(m.error||i("session.stopTask.failed"))})}:void 0,ms=o.useRef(!1);o.useEffect(()=>{if(!B.set_token_mode||ms.current)return;const a=fe.current;a&&(ms.current=!0,a.getRemoteSettings().then(m=>{const k=m==null?void 0:m.applied.tokenMode;(k==="normal"||k==="poor"||k==="sa")&&pt.sync(k)}).catch(m=>console.error("[SessionDetail] reconcile token mode failed:",m)))},[B.set_token_mode,pt]);const In=me(),It=o.useMemo(()=>$r((ee==null?void 0:ee.commands)??[],(ee==null?void 0:ee.skills)??[]),[ee,In]),Ye=o.useMemo(()=>Fr(be,v),[be,v]),Pn=o.useCallback(a=>At.set(a),[At]),[xs,Dn]=o.useState(()=>localStorage.getItem(dn)||"auto"),ps=wt({value:xs,apply:a=>{Dn(a);try{localStorage.setItem(dn,a)}catch{}},send:a=>{var C;const m=fe.current;if(!m)return Promise.reject(new Error("adapter not ready"));const k=(C=Nt.find(R=>R.value===a))==null?void 0:C.effort;return m.setEffort(k)},onError:(a,m)=>{console.error("[SessionDetail] set effort failed:",a),ye(m==="send"?K("session.effort.failedRequest",{message:a}):a||i("session.effort.failed"))}}),Ve=o.useCallback(()=>{var a;B.get_context_usage&&((a=fe.current)==null||a.getContextUsage().then(m=>{m&&(Pe(m),vi(r,m))}).catch(()=>{}).finally(()=>Ee(!1)))},[B,r]);o.useEffect(()=>{if(!B.get_context_usage)return;Ve();const a=setInterval(Ve,6e4);return()=>clearInterval(a)},[B,G,Ve]);const hs=(V==null?void 0:V.currentModelId)??null;o.useEffect(()=>{hs&&Ve()},[hs,Ve]),o.useEffect(()=>{ee&&!B.get_context_usage&&Ee(!1)},[ee,B]),o.useEffect(()=>{if(!He)return;const a=setTimeout(()=>Ee(!1),1e4);return()=>clearTimeout(a)},[He]);const fs=o.useRef(Q);fs.current=Q,o.useEffect(()=>xe.onEvent(m=>{m.type!=="artifact_created"&&m.type!=="artifact_updated"||(fs.current&&Ue(k=>k+1),Z(k=>k+1))}),[]);const[qn,ht]=o.useState(0),[ft,ys]=o.useState(null),[ge,yt]=o.useState(!1),[qe,gs]=o.useState(0),[$n,Fn]=o.useState(void 0),gt=o.useRef(ge);gt.current=ge,o.useEffect(()=>xe.onEvent(m=>{m.type==="memory_synced"&&gt.current&&ht(k=>k+1)}),[]),o.useEffect(()=>{bn().then(a=>ys(a.mode)).catch(()=>ys("sqlite"))},[]),o.useEffect(()=>xe.onEvent(m=>{var k,C;if(m.type==="memory_changed")gt.current?ht(R=>R+1):gs(R=>R+1);else if(m.type==="memory_recall"){const R=Array.isArray((k=m.payload)==null?void 0:k.hits)?m.payload.hits:void 0;R&&Fn({query:typeof((C=m.payload)==null?void 0:C.query)=="string"?m.payload.query:"",hits:R}),gt.current&&ht(O=>O+1)}}),[]),o.useEffect(()=>{ge&&gs(0)},[ge]);const[Je,On]=o.useState("idle");o.useEffect(()=>xe.onStateChange(m=>On(m)),[]),o.useEffect(()=>{Q&&Z(0)},[Q]);const $e=o.useCallback(async()=>{if(Ae.current)return;Ae.current=!0;const a=new Set(we.current.map(m=>m.requestId));try{const k=(await Or(r)).permissions.filter(C=>!L.isPermissionSettled(C.requestId));k.some(C=>C.sentAt!==void 0)&&Ie(Date.now()),je(C=>{const R=new Set(k.map(W=>W.requestId)),O=C.filter(W=>!a.has(W.requestId)&&!R.has(W.requestId)&&!L.isPermissionSettled(W.requestId));return[...k,...O]})}catch{}finally{Ae.current=!1}},[r,L]);o.useEffect(()=>{let a=xe.state;return xe.onStateChange((k,C)=>{const R=k==="open"&&(a==="reconnecting"||a==="failed");(C!=null&&C.resync||R)&&$e(),a=k})},[$e]),o.useEffect(()=>{const a=()=>{document.visibilityState==="visible"&&$e()};return document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)},[$e]),o.useEffect(()=>{let a=!1;async function m(){u("");try{const k=await $s(r);if(a)return;n(k),d(k.status),kt(k.status)&&L.markClosed(),pe(k.status==="running"||k.status==="requires_action")}catch(k){if(a)return;u(k instanceof Error?k.message:i("session.loadFailed"));return}try{await L.init()}catch(k){console.warn("Failed to init adapter:",k)}a||await $e()}return m(),()=>{a=!0}},[r,L,$e]);const H=kt(l),bs=o.useRef(l);bs.current=l,o.useEffect(()=>{if(H)return;let a=!1;const k=setInterval(async()=>{try{const C=await $s(r);if(a||C.status===bs.current)return;kt(C.status)&&L.markClosed(),d(C.status),pe(C.status==="running"||C.status==="requires_action")}catch{}},6e4);return()=>{a=!0,clearInterval(k)}},[r,H,L]);const Y=(s==null?void 0:s.access_level)==="read",js=Ct??(He&&!H&&!Y?on():null),Pt=o.useCallback(()=>{oe([]),Pe(on()),Rs(r).catch(a=>{console.warn("[SessionDetail] Failed to clear session history:",a)})},[r]),Xe=o.useCallback(async(a,m)=>{const k=fe.current;if(!k||H)return;if(a.sessionId===r){oe(R=>[...R,{type:"command_output",id:`cmd-resume-${Date.now()}`,commandName:"resume",inputText:m??"/resume",title:"Resume",subtitle:i("session.resume.title"),outputText:i("session.resume.currentBlocked"),variant:"error"}]);return}const C=(R,O="default")=>oe(W=>[...W,{type:"command_output",id:`cmd-resume-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,commandName:"resume",inputText:m??`/resume ${a.sessionId.slice(0,8)}`,title:"Resume",subtitle:i("session.resume.title"),outputText:R,variant:O}]);C(K("session.resume.restoring",{title:a.title??""}));try{await Rs(r),oe([]);const R=await k.resumeSession(a.sessionId);C(R.title?K("session.resume.restoredWithTitle",{count:R.messageCount,title:R.title}):K("session.resume.restored",{count:R.messageCount}))}catch(R){C(K("session.resume.failed",{message:R instanceof Error?R.message:String(R)}),"error")}},[H,r]),Un=o.useCallback(async()=>{if(s!=null&&s.environment_id)try{const a=await Ur({environment_id:s.environment_id});window.location.href=`/code/${a.id}?resumeFrom=${r}`}catch(a){ve(K("session.createFailedWithReason",{message:a instanceof Error?a.message:String(a)}))}},[s,r,ve]),Ln=o.useRef(new URLSearchParams(window.location.search).get("resumeFrom")),ws=o.useRef(!1);o.useEffect(()=>{const a=Ln.current;!a||ws.current||!ee||!B.resume||(ws.current=!0,window.history.replaceState({},"",window.location.pathname),Xe({sessionId:a,title:a.slice(0,8),modified:0},null))},[ee,B.resume,Xe]);const Fe=o.useCallback(async a=>{const m=a.text.trim(),k=a.images&&a.images.length>0||a.attachments&&a.attachments.length>0;if(!m&&!k||H)return;const C=/^\/resume(?:\s+(.*))?$/.exec(m);if(C){const O=(C[1]??"").trim();if(!B.resume){oe(W=>[...W,{type:"user_message",id:`user-${Date.now()}`,content:m},{type:"command_output",id:`cmd-${Date.now()}`,commandName:"resume",inputText:m,title:"Resume",subtitle:i("session.resume.title"),outputText:i("session.resume.unsupported"),variant:"error"}]);return}O?await Xe({sessionId:O,title:O,modified:0},m):$(!0);return}const R=await Lr(m,{sessionId:r,availableCommands:It,availableModels:(V==null?void 0:V.availableModels)??[],currentModel:V?{modelId:V.currentModelId,name:V.currentModelId}:null,supportsImages:!0,entries:ls.current,setModel:async O=>{await le(r,{type:"control_request",request:{subtype:"set_model",model:O}}),Ce(W=>W&&{...W,currentModelId:O})},onNewSession:()=>{oe([])}}).catch(()=>null);if(R){if(St("[SessionDetail] local command result",R),"clearEntries"in R&&R.clearEntries){Pt();return}if("newSession"in R&&R.newSession){Pt();return}if("userEntry"in R){oe(O=>[...O,R.userEntry,R.cmdEntry]);return}}pe(!0);try{await L.sendMessage(m,a.images,a.attachments)}catch(O){if(console.error("Send failed:",O),O instanceof Kr&&O.type==="session_closed"){d("archived"),L.markClosed(),ve(i("session.closedSendBlocked"));return}ve(`${i("session.sendFailed")}${O instanceof Error?`: ${O.message}`:""}`)}},[L,H,r,V,It,Pt,ve,Xe,B]),Kn=o.useCallback(a=>{if(G){lt(m=>[...m,a]);return}Fe(a)},[G,Fe]),[Dt,vs]=o.useState(!1),Bn=o.useCallback(()=>{G||(vs(!0),Fe({text:"/dream"}))},[G,Fe]);o.useEffect(()=>{!G&&Dt&&(vs(!1),ht(a=>a+1))},[G,Dt]);const qt=o.useRef(!1);o.useEffect(()=>{if(H){lt(m=>m.length>0?[]:m);return}if(G||ot.length===0||qt.current)return;const a=ot[0];a&&(qt.current=!0,lt(m=>m.slice(1)),Fe(a).finally(()=>{qt.current=!1}))},[G,ot,Fe,H]);const Hn=o.useCallback((a,m)=>{if(G)return;const k=m==="edit"?i("session.rewind.confirmEdit"):i("session.rewind.confirm");window.confirm(`${k}
78
+ ${i("session.rewind.confirmBody")}`)&&L.rewindToMessage(a.id).then(()=>{m==="edit"&&a.content&&U(C=>({text:a.content,nonce:C.nonce+1}))}).catch(C=>{console.error("[SessionDetail] rewind failed:",C),ve(K("session.rewind.failed",{message:C instanceof Error?C.message:String(C)}))})},[G,ve]),Qn=o.useCallback(a=>{const m=Ye.orderedMatchIds;if(m.length===0)return;const k=(a%m.length+m.length)%m.length;h(k);const C=m[k],R=document.querySelector(`[data-entry-id="${CSS.escape(C)}"]`);R==null||R.scrollIntoView({block:"center",behavior:"smooth"})},[Ye]),ks=o.useCallback(async()=>{try{await L.interrupt()}catch(a){console.error("Interrupt failed:",a)}finally{pe(!1)}},[L]),Wn=o.useCallback(()=>{Rt(Ci(ct))},[Rt,ct]);o.useEffect(()=>()=>{Qe.current&&clearTimeout(Qe.current),We.current&&clearTimeout(We.current)},[]);const Gn=o.useCallback(async()=>{if(s&&window.confirm(i("dashboard.confirmDelete").replace("{id}",s.title||s.id)))try{await As(s.id),window.location.href="/code/"}catch(a){alert(a instanceof Error?a.message:i("dashboard.deleteFailed"))}},[s]),J=o.useCallback(async a=>{var m,k;if(!dt.current.has(a.requestId)){dt.current.add(a.requestId),ut.current.set(a.requestId,a),ze.current.delete(a.requestId);try{switch(a.kind){case"approve":await L.respondPermission(a.requestId,!0);break;case"approveAlways":{const O=((m=we.current.find(sr=>sr.requestId===a.requestId))==null?void 0:m.toolName)??"tool",W=Br(a.suggestions,O);W&&ze.current.set(a.requestId,W),await L.respondPermission(a.requestId,!0,{updated_permissions:a.suggestions});break}case"reject":await L.respondPermission(a.requestId,!1);break;case"answers":await le(r,{type:"permission_response",approved:!0,request_id:a.requestId,updated_input:{questions:a.questions,answers:a.answers}});break;case"plan":if(a.value==="no")await le(r,{type:"permission_response",approved:!1,request_id:a.requestId,...a.feedback?{message:a.feedback}:{}});else{const O={"yes-accept-edits":"acceptEdits","yes-default":"default"};await le(r,{type:"permission_response",approved:!0,request_id:a.requestId,updated_permissions:[{type:"setMode",mode:O[a.value]||"default",destination:"session"}]})}break}const C=Date.now(),R=a.kind==="reject"||a.kind==="plan"&&a.value==="no"?"deny":"allow";Ie(C),je(O=>O.map(W=>W.requestId===a.requestId?{...W,sentAt:C,decision:R}:W)),_e(null)}catch(C){console.error(`[SessionDetail] permission ${a.kind} failed:`,C);const R=(k=z.find(O=>O.requestId===a.requestId))==null?void 0:k.toolName;_e({requestId:a.requestId,message:R?K("permission.respondFailedFor",{tool:R}):i("permission.respondFailed"),action:a})}finally{dt.current.delete(a.requestId)}}},[L,r,z]),Ns=o.useCallback(a=>void J({kind:"approve",requestId:a}),[J]),zn=o.useCallback((a,m)=>void J({kind:"approveAlways",requestId:a,suggestions:m}),[J]);o.useCallback(async(a,m)=>{const k=De;if(it(null),!!k)try{await L.respondElicitation(k.requestId,a,m)}catch(C){console.error("Failed to submit elicitation:",C)}},[De,L]);const Yn=o.useCallback(()=>{!s||Y||(Xt(s.title||""),Et(!0),setTimeout(()=>{var a,m;(a=Mt.current)==null||a.focus(),(m=Mt.current)==null||m.select()},0))},[s,Y]),Ss=o.useCallback(async()=>{const a=Tt.trim();if(Et(!1),!(!s||!a||a===s.title))try{const m=await Hr(s.id,a);n(k=>k&&{...k,title:m.title??a})}catch(m){console.error("Rename failed:",m),alert(m instanceof Error?m.message:i("session.rename.failed"))}},[s,Tt]),Te=o.useCallback((a=null)=>{nt(a),_(!0)},[]),Vn=o.useCallback(a=>{if(typeof window<"u"&&window.matchMedia("(max-width: 639px)").matches||a.toolName==="AskUserQuestion"||a.toolName==="ExitPlanMode"){Te(a.requestId);return}const k=Array.from(document.querySelectorAll("[data-permission-request-id]")).find(C=>C.dataset.permissionRequestId===a.requestId);if(!k){Te(a.requestId);return}k.scrollIntoView({behavior:"smooth",block:"center"}),k.focus({preventScroll:!0})},[Te]),Jn=o.useCallback(a=>void J({kind:"reject",requestId:a}),[J]),Xn=o.useCallback((a,m,k)=>void J({kind:"answers",requestId:a,answers:m,questions:k}),[J]),Zn=o.useCallback((a,m,k)=>void J({kind:"plan",requestId:a,value:m,feedback:k}),[J]),er=o.useCallback(a=>{dt.current.delete(a);const m=ut.current.get(a);if(m){J(m);return}const k=we.current.find(C=>C.requestId===a);k&&(k.toolName==="AskUserQuestion"||k.toolName==="ExitPlanMode"||J({kind:k.decision==="deny"?"reject":"approve",requestId:a}))},[J]),tr=o.useCallback((a,m,k)=>{var R;if(!k)return;const C=z.find(O=>O.requestId===a);k==="allow_always"&&((R=C==null?void 0:C.suggestions)!=null&&R.length)?J({kind:"approveAlways",requestId:a,suggestions:C.suggestions}):k.startsWith("allow")?J({kind:"approve",requestId:a}):k.startsWith("reject")&&J({kind:"reject",requestId:a})},[z,J]);if(c)return e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx(jt,{onBack:t,title:e.jsx("span",{className:"text-xs font-medium text-text-muted",children:i("session.loadFailed")})}),e.jsx("div",{className:"flex flex-1 items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-status-error",children:c}),e.jsx("a",{href:"/code/",className:"mt-4 inline-block text-brand-text hover:underline",children:i("session.backToDashboard")})]})})]});if(!s)return e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx(jt,{onBack:t,title:e.jsx("span",{className:"h-3.5 w-40 animate-pulse rounded bg-surface-2"})}),e.jsx("div",{className:"flex flex-1 items-center justify-center",children:e.jsx("div",{className:"text-text-muted",children:i("session.loading")})})]});if(s.source==="acp"&&s.environment_id)return e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx("h1",{className:"sr-only",children:s.title||s.id}),e.jsx(jt,{onBack:t,title:e.jsx("span",{className:"truncate text-xs font-semibold text-text-primary",children:s.title||s.id}),meta:e.jsx("span",{className:"rounded-full bg-brand/15 px-2 py-0.5 text-[10px] font-medium text-brand-text",children:"ACP"})}),e.jsx(qi,{sessionId:r,agentId:s.environment_id})]});const _s=[(Cs=s.environment)==null?void 0:Cs.machine_name,s.cwd].filter(Boolean).join(" · ")||void 0;return e.jsx(jn,{children:e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx("h1",{className:"sr-only",children:s.title||s.id}),e.jsx(jt,{onBack:t,title:Cn?e.jsx("input",{ref:Mt,value:Tt,onChange:a=>Xt(a.target.value),onKeyDown:a=>{a.key==="Enter"&&!a.nativeEvent.isComposing?(a.preventDefault(),Ss()):a.key==="Escape"&&(a.preventDefault(),Et(!1))},onBlur:()=>void Ss(),maxLength:200,className:"w-full max-w-xs rounded-md border border-brand/50 bg-surface-2 px-2 py-0.5 text-xs font-semibold text-text-primary focus:outline-none focus:ring-2 focus:ring-brand/30"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex min-w-0 items-center gap-2 text-xs font-semibold text-text-primary",children:!Y&&!H?e.jsx("button",{type:"button",onClick:Yn,title:i("session.rename.title"),className:"truncate text-left transition-colors hover:text-text-secondary",children:s.title||s.id}):e.jsx("span",{className:"truncate",children:s.title||s.id})}),s.visibility&&e.jsx(sa,{visibility:s.visibility||"private",className:"hidden flex-shrink-0 text-[10px] sm:inline-flex"})]}),meta:e.jsx(e.Fragment,{children:(()=>{var k;const a=s.source==="acp"?"acp":(k=s.environment)==null?void 0:k.worker_type,m=wn(a);return e.jsx("span",{className:`hidden items-center rounded-full px-2 py-0.5 text-[10px] font-medium sm:inline-flex ${m.colorClass}`,children:m.fullLabel})})()}),actions:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"hidden items-center gap-0.5 sm:flex",children:[e.jsxs("button",{onClick:()=>D(!Q),className:`relative flex h-7 w-7 items-center justify-center rounded-md transition-colors ${Q?"bg-brand-light text-white":"text-text-muted hover:bg-surface-2 hover:text-text-secondary"}`,title:i("artifacts.title"),children:[e.jsx(Is,{className:"h-3.5 w-3.5"}),ne>0&&!Q&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-brand px-0.5 text-[10px] font-bold text-white",children:ne>9?"9+":ne})]}),e.jsxs("button",{onClick:()=>yt(!ge),className:`relative flex h-7 w-7 items-center justify-center rounded-md transition-colors ${ge?"bg-brand-light text-white":"text-text-muted hover:bg-surface-2 hover:text-text-secondary"}`,title:i("memories.title"),children:[e.jsx(Lt,{className:"h-3.5 w-3.5"}),qe>0&&!ge&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-brand px-0.5 text-[10px] font-bold text-white",children:qe>9?"9+":qe})]}),e.jsx("button",{onClick:()=>{const a=!p;g(a),a?setTimeout(()=>{var m;return(m=x.current)==null?void 0:m.focus()},0):(w(""),h(0))},className:`flex h-7 w-7 items-center justify-center rounded-md transition-colors ${p?"bg-brand-light text-white":"text-text-muted hover:bg-surface-2 hover:text-text-secondary"}`,title:i("session.search.title"),children:e.jsx(et,{className:"h-3.5 w-3.5"})}),e.jsxs("button",{onClick:()=>{ae.length>0?Te():f(!y)},className:`relative flex h-7 w-7 items-center justify-center rounded-md transition-colors ${y||j?"bg-brand-light text-white":"text-text-muted hover:bg-surface-2 hover:text-text-secondary"}`,title:i("session.tasks"),"aria-label":i("session.tasks"),"aria-expanded":y||j,children:[e.jsx(Hs,{className:"h-3.5 w-3.5"}),ae.length>0&&!y&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-status-warning px-0.5 text-[10px] font-bold text-surface-0",children:ae.length>9?"9+":ae.length})]}),e.jsxs(Ps,{children:[e.jsx(Ds,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":i("session.actions"),title:i("session.actions"),className:"flex h-7 w-7 items-center justify-center rounded-md text-text-muted transition-colors hover:bg-surface-2 hover:text-text-secondary",children:e.jsx(Ls,{className:"h-3.5 w-3.5"})})}),e.jsxs(qs,{align:"end",className:"w-52",children:[B.side_question&&!H&&!Y&&e.jsxs(ue,{className:"gap-2",onSelect:()=>P(!q),children:[e.jsx(Kt,{className:"h-4 w-4 text-text-muted"}),i("session.sideQuestion.title")]}),B.mcp_management&&!H&&!Y&&e.jsxs(ue,{className:"gap-2",onSelect:()=>T(!E),children:[e.jsx(Bt,{className:"h-4 w-4 text-text-muted"}),i("session.mcp.title")]}),B.remote_settings&&!H&&!Y&&e.jsxs(ue,{className:"gap-2",onSelect:()=>N(!A),children:[e.jsx(Ht,{className:"h-4 w-4 text-text-muted"}),i("session.settings.title")]}),!Y&&(s==null?void 0:s.access_level)!=="write"&&e.jsxs(ue,{className:"gap-2",onSelect:()=>se(!0),children:[e.jsx(Qs,{className:"h-4 w-4 text-text-muted"}),i("session.share")]})]})]})]}),e.jsxs(Ps,{children:[e.jsx(Ds,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":i("session.actions"),title:i("session.actions"),className:"relative flex h-11 w-11 items-center justify-center rounded-md text-text-muted transition-colors hover:bg-surface-2 hover:text-text-secondary sm:hidden",children:[e.jsx(Ls,{className:"h-5 w-5"}),ae.length>0&&e.jsx("span",{className:"absolute right-1 top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-status-warning px-0.5 text-[10px] font-bold text-surface-0",children:ae.length>9?"9+":ae.length})]})}),e.jsxs(qs,{align:"end",className:"w-56",children:[e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>D(!Q),children:[e.jsx(Is,{className:"h-4 w-4 text-text-muted"}),e.jsx("span",{className:"flex-1",children:i("artifacts.title")}),ne>0&&e.jsx("span",{className:"font-mono text-[10px] text-brand-text",children:ne>9?"9+":ne})]}),e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>yt(!ge),children:[e.jsx(Lt,{className:"h-4 w-4 text-text-muted"}),e.jsx("span",{className:"flex-1",children:i("memories.title")}),qe>0&&e.jsx("span",{className:"font-mono text-[10px] text-brand-text",children:qe>9?"9+":qe})]}),B.side_question&&!H&&!Y&&e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>P(!q),children:[e.jsx(Kt,{className:"h-4 w-4 text-text-muted"}),i("session.sideQuestion.title")]}),e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>{const a=!p;g(a),a?setTimeout(()=>{var m;return(m=x.current)==null?void 0:m.focus()},0):(w(""),h(0))},children:[e.jsx(et,{className:"h-4 w-4 text-text-muted"}),i("session.search.title")]}),B.mcp_management&&!H&&!Y&&e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>T(!E),children:[e.jsx(Bt,{className:"h-4 w-4 text-text-muted"}),i("session.mcp.title")]}),B.remote_settings&&!H&&!Y&&e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>N(!A),children:[e.jsx(Ht,{className:"h-4 w-4 text-text-muted"}),i("session.settings.title")]}),!Y&&(s==null?void 0:s.access_level)!=="write"&&e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>se(!0),children:[e.jsx(Qs,{className:"h-4 w-4 text-text-muted"}),i("session.share")]}),e.jsxs(ue,{className:"min-h-11 gap-2",onSelect:()=>{ae.length>0?Te():f(!y)},children:[e.jsx(Hs,{className:"h-4 w-4 text-text-muted"}),e.jsx("span",{className:"flex-1",children:i("session.tasks")}),ae.length>0&&e.jsx("span",{className:"rounded-full bg-status-warning px-1.5 py-0.5 font-mono text-[10px] font-bold text-surface-0",children:ae.length>9?"9+":ae.length})]})]})]})]})}),(Je==="reconnecting"||Je==="failed")&&e.jsxs("div",{className:`flex items-center justify-center gap-2 px-4 py-1.5 text-xs font-medium ${Je==="failed"?"bg-status-error/10 text-status-error":"bg-status-warning/10 text-status-warning"}`,children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${Je==="failed"?"bg-status-error":"animate-pulse bg-status-warning"}`}),Je==="failed"?i("session.sseFailed"):i("session.sseReconnecting")]}),Q&&e.jsx("div",{className:"border-b bg-surface-1 py-4",children:e.jsx("div",{className:"mx-auto page-measure px-4 sm:px-8",children:e.jsx(la,{sessionId:r,embedded:!0,refreshTick:ce})})}),p&&e.jsx("div",{className:"border-b bg-surface-1 py-2",children:e.jsxs("div",{className:"mx-auto flex page-measure px-4 sm:px-8 items-center gap-2",children:[e.jsx(et,{className:"h-3.5 w-3.5 flex-shrink-0 text-text-muted"}),e.jsx("input",{ref:x,value:v,onChange:a=>{w(a.target.value),h(0)},onKeyDown:a=>{a.key==="Enter"&&!a.nativeEvent.isComposing?(a.preventDefault(),Qn(v&&a.shiftKey?S-1:S+1)):a.key==="Escape"&&(a.preventDefault(),g(!1),w(""))},placeholder:i("session.search.placeholder"),className:"w-full bg-transparent text-sm text-text-primary placeholder:text-text-muted focus:outline-none"}),v.trim()&&e.jsx("span",{className:"flex-shrink-0 font-mono text-[10px] text-text-muted",children:Ye.orderedMatchIds.length===0?i("session.search.noResults"):`${S+1}/${Ye.orderedMatchIds.length}`})]})}),e.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:e.jsx(Qr,{entries:be,isLoading:G,turnStartedAt:b,emptyTitle:i("session.emptyTitle"),emptyDescription:i("session.emptyDescription"),emptyExtra:e.jsx(Ni,{}),searchMatchIds:v.trim()?Ye.matchIds:void 0,onPermissionRespond:tr,onRewindEntry:B.rewind&&!H&&!Y&&!G?(a,m)=>Hn(a,m):void 0})}),ft!==null&&e.jsx(ke,{open:ge,onOpenChange:yt,children:e.jsxs(Ne,{showCloseButton:!1,"data-testid":"memory-sidebar",className:"mem-drawer mem-drawer--v1 translate-x-0 translate-y-0",children:[e.jsxs("div",{className:"mem-drawer__masthead",children:[e.jsx(Se,{className:"mem-drawer__title",children:i("memorySidebar.title")}),e.jsx("button",{type:"button",onClick:()=>yt(!1),className:"mem-drawer__close","aria-label":i("common.close"),title:i("common.close"),children:e.jsx(Ze,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"mem-drawer__body",children:e.jsx(gi,{refreshTick:qn,recall:ft==="memdir"?$n:void 0,dreaming:ft==="memdir"?G&&Dt:void 0,onDreamTrigger:ft==="memdir"?Bn:void 0})})]})}),ts&&e.jsx("div",{className:"mx-auto page-measure w-full px-4 sm:px-8 pb-1",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-status-error/40 bg-status-error/10 px-3 py-1.5 text-xs text-status-error",children:[e.jsx($t,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1",children:ts})]})}),Zt&&e.jsx("div",{className:"mx-auto page-measure w-full px-4 sm:px-8 pb-1",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-status-error/40 bg-status-error/10 px-3 py-1.5 text-xs text-status-error",children:[e.jsx($t,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1",children:Zt})]})}),e.jsxs("div",{className:"page-measure mx-auto w-full px-4 sm:px-8 pb-1 session-controls",children:[e.jsxs("div",{className:"session-controls__cluster",children:[e.jsx(Di,{mode:ct,onModeChange:Rt,disabled:H||Y}),e.jsx(Pi,{models:(V==null?void 0:V.availableModels)??[],currentModelId:(V==null?void 0:V.currentModelId)??null,onSelect:a=>{le(r,{type:"control_request",request:{subtype:"set_model",model:a}}),Ce(m=>m&&{...m,currentModelId:a})},showThinking:B.set_max_thinking_tokens,thinkingBudget:he,onThinkingChange:Pn,showEffort:B.set_effort,effort:xs,onEffortChange:a=>ps.set(a),disabled:H||Y}),B.set_token_mode&&e.jsx(Ri,{mode:ds,onModeChange:a=>pt.set(a),disabled:H||Y})]}),e.jsx("div",{className:"session-controls__usage",children:js&&e.jsx(Ii,{usage:js})})]}),H&&(s==null?void 0:s.environment_id)&&e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-2 sm:px-8",children:e.jsx("button",{type:"button",onClick:()=>void Un(),className:"w-full rounded-lg border border-border bg-surface-1 px-4 py-2.5 text-sm text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary",children:i("session.resumeInNew")})}),e.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:rs>0?i("permission.queueEmpty"):""},rs),de&&e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-1 sm:px-8",children:e.jsxs("div",{role:"status","aria-live":"polite",className:`flex items-center gap-2 rounded-lg border bg-surface-1 px-3 py-2 text-xs font-medium ${de.decision==="allow"?"border-approve/25 text-approve-text":"border-status-error/30 text-status-error"}`,children:[de.decision==="allow"?e.jsx(Wr,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}):e.jsx(Ze,{className:"h-4 w-4 flex-shrink-0 text-status-error","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 truncate",children:de.decision==="allow"?de.remembered?K("permission.appliedRemembered",{tool:de.tool,rule:de.remembered}):K("permission.applied",{tool:de.tool}):de.decision==="deny"?K("permission.appliedDenied",{tool:de.tool}):K("permission.appliedCanceled",{tool:de.tool})})]},de.nonce)}),re&&!j&&e.jsx("div",{className:"mx-auto w-full page-measure px-4 pb-1 sm:px-8",children:e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-x-3 gap-y-2 rounded-lg border border-status-error/40 bg-status-error/10 px-3 py-2",children:[e.jsx($t,{className:"h-4 w-4 flex-shrink-0 text-status-error","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1 text-xs text-status-error",children:re.message}),e.jsx("button",{ref:os,type:"button",onClick:()=>void J(re.action),className:"min-h-11 rounded-md border border-status-error/40 px-3 py-1.5 text-xs font-medium text-status-error transition-colors hover:bg-status-error/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:min-h-9",children:i("common.retry")}),e.jsx("button",{type:"button",onClick:()=>_e(null),"aria-label":i("common.close"),className:"flex h-11 w-11 items-center justify-center rounded-md text-text-muted transition-colors hover:bg-surface-2 hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:h-8 sm:w-8",children:e.jsx(Ze,{className:"h-4 w-4"})})]})}),e.jsx("div",{className:j?"invisible":void 0,"aria-hidden":j||void 0,children:e.jsx(di,{requests:z,onApprove:Ns,onView:Vn,onOpenQueue:()=>Te(),context:_s})}),e.jsx(Gr,{onSubmit:Kn,isLoading:G,onInterrupt:ks,onCycleMode:Wn,disabled:H||Y,placeholder:H?i("session.closed"):Y?i("session.readOnly"):i("session.inputPlaceholder"),supportsAttachments:!0,commands:It,queueWhileLoading:!0,queuedCount:ot.length,onDequeue:a=>lt(m=>m.filter((k,C)=>C!==a)),onSearchFiles:B.file_search?a=>L.searchFiles(a):void 0,historyKey:r,draftOverride:M}),E&&e.jsx(ni,{onClose:()=>T(!1),fetchServers:()=>L.getMcpServers(),onToggle:(a,m)=>L.toggleMcpServer(a,m),onReconnect:a=>L.reconnectMcpServer(a)}),A&&e.jsx(ii,{onClose:()=>N(!1),fetchSettings:()=>L.getRemoteSettings(),onApply:a=>L.applyFlagSettings(a)}),q&&e.jsx(oi,{onClose:()=>P(!1),onAsk:a=>L.askSideQuestion(a)}),y&&s&&e.jsx(Ja,{onClose:()=>f(!1),session:s,liveStatus:l,pendingPermissions:z,onOpenQueue:()=>Te(),subagentState:rt,onStopTask:An,onInterrupt:ks,onDelete:Gn,onEndSession:B.end_session&&!H&&!Y?async()=>{await L.endSession("ended from web"),await As(s.id),window.location.href="/code/"}:void 0}),e.jsx(xi,{open:X,onClose:()=>se(!1),sessionId:s.id,sessionTitle:s.title||void 0}),e.jsx(ui,{open:j,onClose:()=>_(!1),requests:z,initialRequestId:Le,now:Ke,errorMessage:re==null?void 0:re.message,errorRequestId:re==null?void 0:re.requestId,onRetry:er,context:_s,onApprove:Ns,onApproveAlways:zn,onReject:Jn,onSubmitAnswers:Xn,onSubmitPlan:Zn}),e.jsx(fi,{open:I,onClose:()=>$(!1),adapter:L,onResume:a=>{$(!1),Xe(a,null)}})]})})}function qi({sessionId:r,agentId:t}){const[s,n]=o.useState(null),[l,d]=o.useState("disconnected"),[c,u]=o.useState(null),y=o.useRef(null);return o.useEffect(()=>{const f=_i(t);return f.setConnectionStateHandler((j,_)=>{d(j),u(_||null)}),y.current=f,n(f),f.connect().catch(j=>{j instanceof zr||(u(j.message),d("error"))}),()=>{f.disconnect(),y.current=null,n(null),d("disconnected")}},[t]),e.jsx(jn,{children:e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[c&&l==="error"&&e.jsx("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-sm border-b",children:c}),l==="connecting"&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-brand border-t-transparent rounded-full mx-auto mb-3"}),e.jsx("p",{className:"text-text-muted text-sm",children:i("session.connectingAgent")})]})}),l==="error"&&!s&&e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium mb-1",children:i("session.connectionFailed")}),e.jsx("p",{className:"text-text-muted text-sm",children:c})]})}),s&&l==="connected"&&e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(Yr,{client:s,agentId:t})})]})})}export{Ji as SessionDetail};